[go: up one dir, main page]

0% found this document useful (0 votes)
4 views18 pages

Python Unit-II Notes

The document covers Python program flow control, focusing on conditional statements (if, else, elif) and loops (for, while). It explains the syntax and usage of these constructs, including logical operators, nested conditions, and loop manipulation with break and continue statements. Additionally, it provides examples and exercises for practical understanding of these concepts.

Uploaded by

Ab Cd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

Python Unit-II Notes

The document covers Python program flow control, focusing on conditional statements (if, else, elif) and loops (for, while). It explains the syntax and usage of these constructs, including logical operators, nested conditions, and loop manipulation with break and continue statements. Additionally, it provides examples and exercises for practical understanding of these concepts.

Uploaded by

Ab Cd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit – II

Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
python, for loop using ranges, string, list and dictionaries. Use of while loops in python, Loop
manipulation using pass, continue, break and else. Programming using Python conditional
and loop blocks.
Conditional statements

Conditional statements are decision-making statements that control the flow of a program
based on certain conditions.

Need for conditional statements

Conditional statements are used when we want our program to make decisions based on
certain conditions. Without them, the program would always perform the same action,
regardless of the situation.
They help us write code that behaves differently based on input or scenario, just like we do in
real life.
Conditional Statements

1. if Statement

The if statement is the simplest decision-making statement. If the condition is True, the
block of code inside the if statement runs. If the condition is found True, the set of
statements to be executed is given in the same indent called block.In Python, Identation has
the same effect as curly brackets In C.

Syntax:
Flowchart:

Example:
i = 10
if i > 15:
print("10 is less than 15")
print("I am Not in if")

Output:
I am Not in if

2. if-else Statement

The if-else statement is used when we need to decide between two options.
If the condition is True, the if block runs.
If the condition is False, the else block runs.
Syntax:

Flowchart:

Example:
i = 20
if i > 0:
print("i is positive")
else:
print("i is 0 or Negative")

Output:
i is positive

3. Logical Operators with if-else

We can combine multiple conditions using logical operators:


• and → True if both conditions are True

• or → True if any one condition is True


• not → Reverses the result

Example:
age = 25
exp = 10

if age > 23 and exp > 8:


print("Eligible.")
else:
print("Not eligible.")

Output:
Eligible.

4. if-elif-else Statement

Used for multi-way decision making.


Checks conditions one by one.
Runs the block for the first condition which is True.
If none are True, the else block runs.

Syntax:

Flowchart:
Example:
i = 25
if i == 10:
print("i is 10")
elif i == 15:
print("i is 15")
elif i == 20:
print("i is 20")
else:
print("i is not present")

Output:
i is not present

5. Nested if-else
We can use one if-else inside another if or else block.
This is helpful for checking conditions inside another condition.
Example:
x = 15
if x > 10:
print("x is greater than 10")
if x > 20:
print("x is also greater than 20")
else:
print("x is not greater than 20")
else:
print("x is less than or equal to 10")

Output:
x is greater than 10
x is not greater than 20

Questions based on Conditional statements(Questions Given in Class)

1. Write a program to check if a number is positive or negative.

# Check if a number is positive or negative

num = -5

if num > 0:

print("The number is positive")


else:

print("The number is negative")


Output:

The number is negative

Need for iteration Statements

Loops comes in situation where the same task has to be repeated specific number of times or
until a particular condition is satisfied.

While statement

“while” is a very simple method of implementing iteration or loops. we give a condition after
the ‘while’ keyword, so that the condition is verified and if it is true, it executes the set of
statements in the body of the loop. else, it is skipped.
while expression :

statement1

Flowchart

#Printing even numbers upto n

#printing odd numbers upto n

For statement

For variable_name inlist_name :

Body of loop
In the first step executing for loop, the loop variable is assigned with the first value of the list
specified with list_name. After that, body of the loop is executed. Now, the loop variable is
assigned with the next value in the list. Finally, the loop variable is assigned with the last item
of the list and the loop body is executed last time.

Range() function

The range() function is a built in function that is used to generating a sequence of numbers
which can be assigned to the loop variable.

Syntax :

range(start,end,steps)

Example :

for i in range(1,5,1):

print(i)

OUTPUT :

3
4

range(a,b) will generate numbers from a to b – 1 with default step size of 1.

Range(b) will generate numbers from 0 to b – 1 with default step size of 1.

Break and Continue Statement


The break statement is used to exit from the loop immediately and transfer the control of the
execution to the statement just after the loop.

The Continue statement is used to execute from the start of the loop, thereby skipping the
execution of the remaining part of the loop.

Syntax: (Break Statement)

while(condition):

if(condition):

Break;

else:
//codes to repeat in loop

for variable_name in list_name:

if(condition):

Break;

else:

//codes to repeat in loop

continue statement Syntax:

while(condition):

if(condition):
continue;

//while loop block

for variable_name in list_name:

if(condition):

continue;

//codes to repeat in loop


Flowchart

Flowchart(Continue statement)

while Loop with an else Block

The else block in a while loop runs when the condition becomes False without the loop being
interrupted by a break statement.

Example:

i=1
while i < 4:

print(i)

i += 1

else:
print("Loop ended because condition is false")

Output:

1
2

Loop ended because condition is false

• The while loop runs as long as i < 4.

• Once i becomes 4, the condition becomes False, and the loop stops.

• The else block runs when the loop finishes normally (i.e., without a break).

Flowchart

Nested loop

Write a program to assign a grade based on a student's score using if-elif-else.

# Check the grade based on the score


score = 85

if score >= 90:

print("Grade: A")

elif score >= 75:


print("Grade: B")

else:

print("Grade: C")

Output:

Grade: B

3. Write a for loop to print numbers from 0 to 4 using range().


# Print numbers from 0 to 4
for i in range(5):

print(i)

Output:

1
2

4. Write a for loop to print each character in a string.

# Print each character in a string


word = "Python"

for char in word:

print(char)
Output:

t
h

5. Write a for loop to iterate over a list of fruits and print each fruit.

# Print each fruit in the list

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

Output:

apple

banana

cherry

6. Write a for loop to iterate over the key-value pairs of a dictionary and print them.

# Looping through key-value pairs in a dictionary

person = {"name": "Alice", "age": 25, "city": "New York"}


for key, value in person.items():

print(f"{key}: {value}")

Output:
name: Alice

age: 25

city: New York

7. Write a while loop to print numbers from 1 to 4.

# Using a while loop to print numbers from 1 to 4

i=1

while i < 5:

print(i)
i += 1
Output:

Copy code

8.Write a program using for loop and break to exit the loop when the number reaches 3.

# Break the loop when i equals 3

for i in range(5):

if i == 3:

break

print(i)

Output:
0

2
9. Write a program using for loop and continue to skip the number 2.

# Skip printing the number 2 using continue

for i in range(5):
if i == 2:

continue

print(i)

Output:

Copy code

1
3
4

10. Write a for loop using pass and use else to print a message when the loop completes.

# Use pass to ignore a condition, else block runs when the loop completes normally

for i in range(5):

if i == 2:
pass # Placeholder

print(i)

else:

print("Loop completed")

Output:

1
2

4
Loop completed

Right-angled triangle pattern of stars

rows = int(input("Enter the number of rows: "))

for i in range(1, rows + 1):

print("*" * i)

Output:

Enter the number of rows: 4

**
***
****

2. Inverted right-angled triangle pattern of stars

rows = int(input("Enter the number of rows: "))

for i in range(rows, 0, -1):

print("*" * i)

Output:

Enter the number of rows: 4

****

***

**

*
3. Right-angled triangle pattern of numbers

rows = int(input("Enter the number of rows: "))


for i in range(1, rows + 1):

print(" ".join(str(j) for j in range(1, i + 1)))

Output:

Enter the number of rows: 4


1

12

123

1234

4. Pyramid pattern of stars

rows = int(input("Enter the number of rows: "))

for i in range(1, rows + 1):

print(" " * (rows - i) + "*" * (2 * i - 1))

Output:

Enter the number of rows: 4

***

*****
*******

5. Diamond pattern of stars

rows = int(input("Enter the number of rows: "))

# Upper part of the diamond

for i in range(1, rows + 1):

print(" " * (rows - i) + "*" * (2 * i - 1))


# Lower part of the diamond

for i in range(rows - 1, 0, -1):

print(" " * (rows - i) + "*" * (2 * i - 1))


Output:

Enter the number of rows: 4

*
***

*****

*******

*****

***

You might also like