operators_control_structure
operators_control_structure
and
Iterations
Operators
Types of Operator
• Arithmetic Operators
• Unary Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Assignment Operators
• Membership Operators
• Logical Operators
• Identity Operators
Arithmetic Operators
• + Addition
• - Subtraction
• * Multiplication
• / Division
• %Modulus (Remainder)
• // Floor Division( removes digit after decimal point)
• ** Exponent (Raise to)
The modulus operator
• import random
• n1=random.randint(1,9)
• n2=random.randint(1,9)
• ans=eval(input("What is "+str(n1)+" + "+str(n2)+" "))
• print("Your ans is ",n1+n2==ans)
• Print(int(true))
Displays 1
• Print(int(false))
Displays 0
• Print(bool(0))
Displays false
• Print(bool(4))
Displays true
Comparison Operators
• x != y # x is not equal to y
• x>y # x is greater than y
• x<y # x is less than y
• x >= y x=<y # x is greater than or equal to
y
• x <= y # x is less than or equal to y
NOTE: “= is an assignment operator and == is a comparison operator”.
Also, there is no such thing as =< or =>.
Logical operators
• X=true
• Y=false
• Print(“x and y is”,x and y) #output: false
• Print(“x or y is”,x or y) #output: true
• Print(“not x is”,not x) #output: false
•
Identity operators
=-x-1
Membership Operators
Continue…
• If a > 0:
print (“a is positive”)
Alternative Execution
• A second form of the if statement is alternative execution, in which there
are two possibilities and the condition determines which one gets
executed.
• Eg:
if x%2 == 0:
print (x, "is even“)
else:
print (x, "is odd“)
• The alternatives are called branches.
If else Condition example
>>> printParity(17)
17 is odd
>>> y = 17
>>> printParity(y+1)
18 is even
Example
Calling of function depending upon input enter by user:
Example:
if choice == 'A':
functionA()
elif choice == 'B':
functionB()
elif choice == 'C':
functionC()
else:
print "Invalid choice."
Avoid Nested If