Now we dive into math operations. It is very simple, just like basic math. Python keeps it intuitive. These are the basic math operations.
+ addition
– subtraction
* multiplication
/ division
** power of
% modulus
In IDLE you can just type 1+1 and it outputs 2.
Math Calulator
Below is a basic calculator code. See if you can figure out how it works by reading the code. Copy and paste the code into PyCharms or text editor. Run it a few times to see what it does.
#defining the add function that takes 2 arguments num1 and num2
def add(num1, num2):
return num1 + num2
#defining the minus function that takes 2 arguments num1 and num2
def subtract(num1, num2):
return num1 - num2
#defining the multiply function that takes 2 arguments num1 and num2
def multiply(num1, num2):
return num1 * num2
#defining the divide function that takes 2 arguments num1 and num2
def divide(num1, num2):
return num1 / num2
#defining the to the power of function that takes 2 arguments num1 and num2
def powerOf(num1, num2):
return num1 ** num2
#defining the to the power of function that takes 2 arguments num1 and num2
def modulus(num1, num2):
return num1 % num2
#main is the last thing in a Python program and is like a command post
def main():
operation = input("What math do you want to perform? (+, -, *, /, **, %): ")
if(operation != '+' and operation != '-' and operation != '*' and operation != '/' and operation != '**' and operation != '%'):
#invalid operation choice
print('You must enter a valid operation.')
else:
var1 = int(input("Enter first number: "))
var2 = int(input("Enter second number: "))
if(operation == '+'):
print("Answer: " , add(var1, var2))
elif(operation == '-'):
print("Answer: " , subtract(var1, var2))
elif(operation == '*'):
print("Answer: " , multiply(var1, var2))
elif(operation == '/'):
print("Answer: " , multiply(var1, var2))
elif(operation == '**'):
print("Answer: " , powerOf(var1, var2))
else:
print("Answer: " , modulus(var1, var2))
#this normally runs the main function
#main()
#now I want to introduce this, which also runs the mail program
#it is a simple if statement same the ones we have used already. More on this to come
if __name__ == '__main__': main()
We will talk more about this mysterious if statement soon!