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

Python UNIT 2

This document outlines the content to be covered in Unit II, including using if/else statements, elif clauses, while loops, avoiding infinite loops, and compound conditions. It introduces examples like a password program, mood computer, and 3-year-old simulator to demonstrate these programming concepts. The document also examines the syntax of if/else/elif statements and while loops in Python and how indentation is used to indicate blocks of code.

Uploaded by

Sunay B S
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python UNIT 2

This document outlines the content to be covered in Unit II, including using if/else statements, elif clauses, while loops, avoiding infinite loops, and compound conditions. It introduces examples like a password program, mood computer, and 3-year-old simulator to demonstrate these programming concepts. The document also examines the syntax of if/else/elif statements and while loops in Python and how indentation is used to indicate blocks of code.

Uploaded by

Sunay B S
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

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

Sharadadevi Kaganurmath, Dept of ISE 1


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

Sharadadevi Kaganurmath, Dept of ISE 2


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

Sharadadevi Kaganurmath, Dept of ISE 3


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

Sharadadevi Kaganurmath, Dept of ISE 4


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

Sharadadevi Kaganurmath, Dept of ISE 5


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

Sharadadevi Kaganurmath, Dept of ISE 6


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.

Sharadadevi Kaganurmath, Dept of ISE 7


Building Your Own if Statement
Python if statement

The syntax of if statement in Python is:


if condition:
# body of if statement number = 10

# check if number is greater than 0

if number > 0:

print('Number is positive.’)

print('The if statement is easy')

Sharadadevi Kaganurmath, Dept of ISE 8


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

Sharadadevi Kaganurmath, Dept of ISE 9


2. Using the else Clause

Using the else Clause

Introducing the Granted or Denied Program

Examining the else Clause

Sharadadevi Kaganurmath, Dept of ISE 10


Python if else statement

The syntax of if-else statement in Python is:


if condition;
# block of code if condition is True number = 10
else:
# block of code if condition is False if number > 0:

print('Positive number’)

else:

print('Negative number’)

print('This statement is always executed’)

Sharadadevi Kaganurmath, Dept of ISE 11


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

Sharadadevi Kaganurmath, Dept of ISE 12


3. Using the elif Clause

Using the elif Clause

Introducing the Mood Computer Program

Examining the elif Clause

Sharadadevi Kaganurmath, Dept of ISE 13


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

Sharadadevi Kaganurmath, Dept of ISE 14


Python if..elif..else statement

number = 0
The syntax of if...elif...else construct
statement in Python is: if number > 0:

if condition1: print("Positive number")


# code block 1
elif number == 0:
elif condition2:
# code block 2 print('Zero’)

else: else:
# code block 3
print('Negative number’)

print('This statement is always executed’)

Sharadadevi Kaganurmath, Dept of ISE 15


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

Sharadadevi Kaganurmath, Dept of ISE 16


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

Sharadadevi Kaganurmath, Dept of ISE 17


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

Sharadadevi Kaganurmath, Dept of ISE 18


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

Sharadadevi Kaganurmath, Dept of ISE 19


Examining the while Loop

Examining the while Loop

while response != "Because.":


response = input("Why?\n")

Sharadadevi Kaganurmath, Dept of ISE 20


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

Sharadadevi Kaganurmath, Dept of ISE 21


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.

Sharadadevi Kaganurmath, Dept of ISE 22


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)
Sharadadevi Kaganurmath, Dept of ISE 23
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

Sharadadevi Kaganurmath, Dept of ISE 24


5. Avoiding Infinite Loops

 Introducing the Losing Battle Program

 Tracing the Program

 Creating Conditions That Can Become False

Sharadadevi Kaganurmath, Dept of ISE 25


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

Sharadadevi Kaganurmath, Dept of ISE 26


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

Sharadadevi Kaganurmath, Dept of ISE 27


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

Sharadadevi Kaganurmath, Dept of ISE 28


Treating Values as Conditions

 Introducing the Maitre D’ Program

 Interpreting Any Value as True or False

Sharadadevi Kaganurmath, Dept of ISE 29


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

Sharadadevi Kaganurmath, Dept of ISE 30


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.

Sharadadevi Kaganurmath, Dept of ISE 31


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

Sharadadevi Kaganurmath, Dept of ISE 32


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.")
Sharadadevi Kaganurmath, Dept of ISE 33
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

Sharadadevi Kaganurmath, Dept of ISE 34


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.”

Sharadadevi Kaganurmath, Dept of ISE 35


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

Sharadadevi Kaganurmath, Dept of ISE 36


7. Using Compound Conditions and Operators

Arithmetic Operators

Assignment Operators

Comparison Operators

Identity Operators

Membership Operators

Bitwise Operators

Sharadadevi Kaganurmath, Dept of ISE 37


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

Sharadadevi Kaganurmath, Dept of ISE 38


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

Sharadadevi Kaganurmath, Dept of ISE 39


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

Sharadadevi Kaganurmath, Dept of ISE 40


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

Sharadadevi Kaganurmath, Dept of ISE 41


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

Sharadadevi Kaganurmath, Dept of ISE 42


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

Sharadadevi Kaganurmath, Dept of ISE 43

You might also like