We have learned to print ‘hello world’ in the previous program.
If you haven’t , Please go here.
Now we are going to look into a simple program to
add, subtract, multiply and divide two numbers,something like a simple calculator.
Now lets look into our program.
Here in the first line I just used a print function to print,
“program to add,subtract, multiply and divide numbers”.
In the next line I again used the print function to print,’enter the first number’.
Now I used the ‘input‘ function, to enter a value to the variable ‘a’.
And the data type of the value entered is specified as ‘integer’ here, by using int() function
and by using the ‘input‘ function inside the int() function as ‘int(input())’
I used the print() again to print,‘enter the second number‘.
Then yet again ,I used the ‘input’ function, to enter a value to the variable ‘b’.
And the data type of the value entered is specified as ‘int’ here, by using int() function
and by using the input function inside the int() function, as I have done above.
Then I used the ‘print’ function, again to give the option for the function to be selected, which is to
Now comes the main segment of the program.
Here we use the ‘else if’ statement to select the function.
Look this code snippet:
if(c==1): d=a+b elif(c==2): d=a-b elif(c==3): d=a*b elif(c==4): d=a/b else: print("enter the correct option")
Here one important thing is that in python,
we cannot use use ‘braces’ to group a code snippet as we use in the c++ and other programming languages and instead of that we use indentation here.
We shall discuss about it in detail when we come to more complex programs.
Here, all our statements is written with same indentation in the ‘elif’ statements.
To be more specific, the statements-
'd=a+b', 'd=a-b', 'd=a*b'and ' d=a/b'
are written with same indentation.
And if not the program will show error.
Here in the above code snippet ,if the value of the variable is equal to ‘1’, then the code given below the first ‘if’
statement is executed. If it is not equal to ‘1’, then the next condition’c==2′, is checked.
Here keyword ‘elif‘ is used to enter the second condition after the first ‘if’ condition.
The keyword corresponding to ‘elif‘ in c++ is ‘else if‘.
If all the conditions in the ‘elif’ and ‘if’ statements becomes false, the last else condition is
executed, which means in our program if the value that we entered into the variable ‘c’ is not equal
to ‘1’ or ‘2’ or ‘3’ or ‘4’, then we get a message to ‘enter a valid input’.
and if this message is shown, we need to start over the program.
Look below to see what happens when I enter 5 as C
As I enter this value,the following window appears.
To obtain the correct output we have to enter a value <4.
If the value entered into the variable ‘c’, is any one among’1,2,3,4′ the arithmetic operation
corresponding to the value we entered is performed and we obtain the output.
See you again..
Comment in any queries.