Python UNIT 2
Python UNIT 2
CONTENT OUTLINE
Creating Conditions
# Password
if password == "secret":
print("Access Granted")
The if statement is pretty straightforward. You can probably figure out what’s happening just by reading the
code. I
1.if statement
2.if...else statement
3.if...elif...else statement
Equals: a == b
Not Equals: a != b
if number > 0:
print('Number is positive.’)
CONTENT OUTLINE
else:
print('Negative number’)
executed’)
CONTENT OUTLINE
number = 0
The syntax of if...elif...else construct
if number > 0:
statement in Python is:
if condition1: print("Positive number")
# code block 1
elif number == 0:
elif condition2:
print('Zero’)
# code block 2
else: else:
# code block 3
print('Negative number’)
CONTENT OUTLINE
Make sure that it’s possible for the while condition to evaluate to True at some point;
Otherwise, the block will never run.
Take, for example, one minor change to the loop you’ve been working with
response = "Because."
while response != "Because.":
response = input("Why?\n")
Since response is equal to "Because." right before the loop, the block will never run.
CONTENT OUTLINE
print("Your hero unsheathes his sword for the last fight of his life.\n")
health = 10
trolls = 0
damage = 3
while health != 0:
trolls += 1
health -= damage
print("Your hero swings and defeats an evil troll, " \ "but takes", damage, "damage points.\n")
print("Your hero fought valiantly and defeated", trolls, "trolls.")
Evaluating condition
money = int(input("How many dollars do you slip the Maitre D'? "))
if money:
print("Ah, I am reminded of a table. Right this way.")
else:
print("Please, sit. It may be a while.")
if money:
Notice that money is not compared to any other value.
money is the condition.
When it comes to evaluating a number as a condition, 0 is False and everything else is True.
if money != 0:
The first version is simpler, more elegant, and more intuitive. It reads more naturally and could be translated to
“if there is money.
count = 0
while True:
count += 1
if count > 10:
break
if count == 5: (skips if 5)
continue
print(count)
input("\n\nPress the enter key to exit.")
Rajesh R M, Asst Prof. Dept. of AIML 34
Using the break Statement to Exit a Loop
# skip 5
if count == 5:
continue
The continue statement means “jump back to the top of the loop.”
You can use break and continue in any loop you create.
Both break and continue make Branching, while Loops, and Program Planning
Arithmetic Operators
Assignment Operators
Comparison Operators
Identity Operators
Membership Operators
Bitwise Operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
== Equal x == y
!= Not equal x != y
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost
shift bits fall off