0% found this document useful (0 votes)
34 views

Python UNIT 2

This document outlines the content of a unit on branching and loops in programming. It covers using if statements, else clauses, and elif clauses to execute code conditionally. It also discusses creating while loops, avoiding infinite loops, and using compound conditions with nested if statements. The document provides code examples and explanations for each topic.

Uploaded by

bchiranthan95204
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Python UNIT 2

This document outlines the content of a unit on branching and loops in programming. It covers using if statements, else clauses, and elif clauses to execute code conditionally. It also discusses creating while loops, avoiding infinite loops, and using compound conditions with nested if statements. The document provides code examples and explanations for each topic.

Uploaded by

bchiranthan95204
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to

Branching While Loops, and


Program Planning
Programming
UNIT-1
UNIT 2
Prof. Rajesh R M
Dept. of AIML
Prof. Narasimha Swamy S
RV College of Engineering
Department of AIML
RV Bengaluru
College of Engineering
Bengaluru-59 Go, Change the World
UNIT - II

CONTENT OUTLINE

1. Using the If statement


2. Using the else Clause
3. Using the elif clause
4. Creating while Loops
5. Avoiding Infinite Loops
6. Creating Intentional infinite Loops
7. Using Compound Conditions

Rajesh R M, Asst Prof. Dept. of AIML 2


1. Using the If statement

 Introducing the Password Program

 Examining the if Statement

 Creating Conditions

 Understanding Comparison Operators

 Using Indentation to Create Blocks

 Building Your Own if Statement

Rajesh R M, Asst Prof. Dept. of AIML 3


Introducing the Password Program

# Password

# Demonstrates the if statement

print("Welcome to System Security Inc.")

print("-- where security is our middle name\n")

password = input("Enter your password: ")

if password == "secret": print("Access Granted")

input("\n\nPress the enter key to exit."

Rajesh R M, Asst Prof. Dept. of AIML 4


Examining the if Statement

The key to program Password is the if statement:

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

Rajesh R M, Asst Prof. Dept. of AIML 5


Creating Conditions

ining the if Statement


In Python, there are three forms of the if...else statement.

1.if statement

2.if...else statement

3.if...elif...else statement

Rajesh R M, Asst Prof. Dept. of AIML 6


Understanding Comparison Operators in if Statement

Python supports the usual logical conditions from mathematics:

Equals: a == b

Not Equals: a != b

Less than: a < b

Less than or equal to: a <= b

Greater than: a > b

Greater than or equal to: a >= b

Rajesh R M, Asst Prof. Dept. of AIML 7


Using Indentation to Create Blocks

Using Indentation to Create Blocks

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability

only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Rajesh R M, Asst Prof. Dept. of AIML 8


Building Your Own if Statement
Python if statement
The syntax of if statement in
Python is:
if condition: number = 10
# body of if statement
# check if number is greater than 0

if number > 0:

print('Number is positive.’)

print('The if statement is easy')

Rajesh R M, Asst Prof. Dept. of AIML 9


UNIT - II

CONTENT OUTLINE

1. Using the If statement

2. Using the else Clause


3. Using the elif clause
4. Creating while Loops
5. Avoiding Infinite Loops
6. Creating Intentional infinite Loops
7. Using Compound Conditions

Rajesh R M, Asst Prof. Dept. of AIML 10


2. Using the else Clause

Using the else Clause

Introducing the Granted or Denied Program

Examining the else Clause

Rajesh R M, Asst Prof. Dept. of AIML 11


Python if else statement

The syntax of if-else statement in Python


number = 10
is:
if condition;
# block of code if condition is True if number > 0:
else:
# block of code if condition is False
print('Positive number’)

else:

print('Negative number’)

print('This statement is always

executed’)

Rajesh R M, Asst Prof. Dept. of AIML 12


UNIT - II

CONTENT OUTLINE

1. Using the If statement


2. Using the else Clause

3. Using the elif clause


4. Creating while Loops
5. Avoiding Infinite Loops
6. Creating Intentional infinite Loops
7. Using Compound Conditions

Rajesh R M, Asst Prof. Dept. of AIML 13


3. Using the elif Clause

Using the elif Clause

Introducing the Mood Computer Program

Examining the elif Clause

Rajesh R M, Asst Prof. Dept. of AIML 14


Python if..elif..else statement

The syntax of if...elif...else construct


statement in Python is:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

Rajesh R M, Asst Prof. Dept. of AIML 15


Python if..elif..else statement

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’)

print('This statement is always executed’)

Rajesh R M, Asst Prof. Dept. of AIML 16


Python nested..if.. statement

number = 5 # outer if statement


The syntax of if...elif...else construct
statement in Python is: if (number >= 0):
if expression1: # inner if statement
statement(s)
if expression2: if number == 0:
statement(s) print('Number is 0’)
else
statement(s) # inner else statement
else else:
if expression3:
statement(s) print('Number is positive’)
else # outer else statement
statement(s)
else:
print('Number is negative')

Rajesh R M, Asst Prof. Dept. of AIML 17


UNIT - II

CONTENT OUTLINE

1. Using the If statement


2. Using the else Clause
3. Using the elif clause

4. Creating while Loops


5. Avoiding Infinite Loops
6. Creating Intentional infinite Loops
7. Using Compound Conditions

Rajesh R M, Asst Prof. Dept. of AIML 18


4. Creating while Loops

 Creating while Loops


 Introducing the Three-Year-Old Simulator Program
 Examining the while Loop
 Initializing the Sentry Variable
 Checking the Sentry Variable
 Updating the Sentry Variable

Rajesh R M, Asst Prof. Dept. of AIML 19


Introducing the Three-Year-Old Simulator Program

# Three Year-Old Simulator


# Demonstrates the while loop

print("\t Welcome to the 'Three-Year-Old Simulator'\n")


print("This program simulates a conversation with a three-year-old child.")
print("Try to stop the madness.\n")
response = ""
while response != "Because.":
response = input("Why?\n")
print("Oh. Okay.")

Rajesh R M, Asst Prof. Dept. of AIML 20


Examining the while Loop

Examining the while Loop

while response != "Because.":


response = input("Why?\n")

Rajesh R M, Asst Prof. Dept. of AIML 21


Initializing the Sentry Variable
• Often, while loops are controlled by a sentry variable, a variable used in the condition and compared to
some other value or values.
• Like a human sentry, you can think of your sentry variable as a guard, helping form a barrier around the
while loop’s block.
• In the Three-YearOld Simulator program, the sentry variable is response.
• It’s used in the condition and is compared to the string "Because." before the block is executed each time.
• It’s important to initialize your sentry variable. Most of the time, sentry variables are initialized right before
the loop itself.
• That’s what I did with: response = "" If the sentry variable doesn’t have a value when the condition is
evaluated, your program will generate an error

Rajesh R M, Asst Prof. Dept. of AIML 22


Checking the Sentry Variable

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.

Rajesh R M, Asst Prof. Dept. of AIML 23


Updating the Sentry Variable:

Updating the Sentry Variable:

Once you’ve established your condition, initialized your sentry variable,


and are sure that under some conditions the loop block will execute, you have yourself a working loop.
Next, make sure the loop will end at some point.
If you write a loop that never stops, you’ve created an infinite loop.
Welcome to the club. At one time or another, all programmers have accidentally created an infinite loop and
watched their program get stuck doing something over and over.
Or they see their programs just plain freeze up.
Here’s a simple example of an infinite loop:
counter = 0
while counter <= 10 print(counter)
Rajesh R M, Asst Prof. Dept. of AIML 24
UNIT - II

CONTENT OUTLINE

1. Using the If statement


2. Using the else Clause
3. Using the elif clause
4. Creating while Loops

5. Avoiding Infinite Loops


6. Creating Intentional infinite Loops
7. Using Compound Conditions

Rajesh R M, Asst Prof. Dept. of AIML 25


5. Avoiding Infinite Loops

 Introducing the Losing Battle Program

 Tracing the Program

 Creating Conditions That Can Become False

Rajesh R M, Asst Prof. Dept. of AIML 26


Introducing the Losing Battle Program

# Losing Battle # Demonstrates the dreaded infinite loop

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.")

Rajesh R M, Asst Prof. Dept. of AIML 27


Tracing the Program

# Demonstrates the dreaded infinite loop


health trolls damage health != 0
10 0 3 True
7 1 3 True
4 2 3 True
1 3 3 True
-2 4 3 True
-5 5 3 True
-7 6 3 True

Rajesh R M, Asst Prof. Dept. of AIML 28


Creating Conditions That Can Become False

The line with the condition just needs to become


while health > 0:
Now, if health becomes 0 or negative, the condition evaluates to False and the loop ends. To be sure, you can
trace the program using this new condition:
health trolls damage health != 0
10 0 3 True
7 1 3 True
4 2 3 True
1 3 3 True
-2 4 3 False

Rajesh R M, Asst Prof. Dept. of AIML 29


Treating Values as Conditions

 Introducing the Maitre D’ Program

 Interpreting Any Value as True or False

Rajesh R M, Asst Prof. Dept. of AIML 30


Introducing the Maitre D’ Program

Evaluating condition

print("Welcome to the Chateau D' Food")


print("It seems we are quite full this evening.\n")

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.")

input("\n\nPress the enter key to exit.")

Rajesh R M, Asst Prof. Dept. of AIML 31


Interpreting Any Value as True or False

The new concept is demonstrated in the line:

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.

So, the above line is equivalent to

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.

Rajesh R M, Asst Prof. Dept. of AIML 32


6. Creating Intentional Infinite Loops

 Introducing the Finicky Counter Program

 Using the break Statement to Exit a Loop

 Using the continue Statement to Jump Back to the Top of a Loop

 Understanding When to Use break and continue

Rajesh R M, Asst Prof. Dept. of AIML 33


Introducing the Finicky Counter Program
The Finicky Counter program counts from 1 to 10 using an intentional infinite loop. It’s finicky because it
doesn’t like the number 5 and skips it. # Finicky Counter # Demonstrates the break and continue statements

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

I set up the loop with:


while True:
This technically means that the loop will continue forever, unless there is an exit condition in the
loop body. Luckily, I put one in:
# end loop if count greater than 10

if count > 10:


break
Since count is increased by 1 each time the loop body begins, it will eventually reach 11.
When it does, the break statement, which here means “break out of the loop,” is executed and the
loop ends

Rajesh R M, Asst Prof. Dept. of AIML 35


Using the continue Statement to Jump Back to
the Top of a Loop

Just before count is printed,

I included the lines:

# skip 5
if count == 5:
continue
The continue statement means “jump back to the top of the loop.”

Rajesh R M, Asst Prof. Dept. of AIML 36


Understanding When to Use break and continue

 You can use break and continue in any loop you create.

 They aren’t just restricted for use in intentional infinite loops.

 But they should be used sparingly.

 Both break and continue make Branching, while Loops, and Program Planning

Rajesh R M, Asst Prof. Dept. of AIML 37


7. Using Compound Conditions and Operators

Arithmetic Operators

Assignment Operators

Comparison Operators

Identity Operators

Membership Operators

Bitwise Operators

Rajesh R M, Asst Prof. Dept. of AIML 38


Arithmetic Operator

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Rajesh R M, Asst Prof. Dept. of AIML 39


Assignment Operator
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Rajesh R M, Asst Prof. Dept. of AIML 40
Comparison Operator

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Rajesh R M, Asst Prof. Dept. of AIML 41


Identity Operator

Operator Description Example

is Returns true if both variables are the x is y


same object

is not Returns true if both variables are not x is not y


the same object

Rajesh R M, Asst Prof. Dept. of AIML 42


Membership Operator

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

Rajesh R M, Asst Prof. Dept. of AIML 43


Bitwise Operator

Operator Name Description

& AND Sets each bit to 1 if both bits are 1


| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off
shift

>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost
shift bits fall off

Rajesh R M, Asst Prof. Dept. of AIML 44

You might also like