Jump to content

PyAnWin/Python Control Flow and Iteration

From Wikibooks, open books for an open world

Python Control Flow and Iteration

[edit | edit source]

Python utilizes common control flow statements and iteration tools to execute code conditionally and repetitively.

if Statements

[edit | edit source]

The basic if statement checks a condition and executes code if the condition is True:

 if x > 0: print("x is positive")

You can add an else block that executes when the condition is False:

 if x > 0: print("x is positive") else: print("x is negative or zero")

Exercise: Write an if/else statement that prints "Even" if a number is even and "Odd" if a number is odd.

elif Statements

[edit | edit source]

The elif statement allows you to check multiple conditions. Code is executed on the first condition that evaluates to True:

 if x > 0: 
    print("x is positive")
elif x < 0:
        print("x is negative")
else:
    print("x is zero")

You can chain together as many elif blocks as you need.

Exercise: Write an if/elif/else chain that prints "Positive" for numbers > 0, "Negative" for numbers < 0 and "Zero" for 0.

for Loops

[edit | edit source]

for loops iterate over sequences like lists, tuples and strings:

 fruits = ["apple", "banana", "orange"] 
for fruit in fruits:
    print(fruit)

The loop variable takes on the value of each element in the sequence in turn. You can also loop over ranges of numbers:

 for i in range(5): print(i)

This will print 0 through 4.

Exercise: Write a for loop to print the numbers 1 to 10.

while Loops

[edit | edit source]

while loops execute as long as a condition remains True:

 count = 0 while count < 5: print(count) count += 1

The condition is checked each iteration. count += 1 prevents an infinite loop by incrementing count each time.

Here are some exercises without assessments for control flow and iteration in Python:

Exercise 1:

Write an if/else statement that prints "Even" if a number is even and "Odd" if a number is odd.

Exercise 2:

Write an if/elif/else chain that prints "Positive" for numbers > 0, "Negative" for numbers < 0 and "Zero" for 0.

Exercise 3:

Write a for loop to print the numbers 1 to 10.

Exercise 4:

Write a while loop that prints the numbers from 1 to 20 that are divisible by 3.

Exercise 5:

Given a list of integers, use a for loop to print only the even numbers in the list.

Exercise 6:

Use a while loop to print a countdown from 10 to 1.

Exercise 7:

Write a for loop that iterates over a string and prints each character.

Exercise 8:

Use break and continue statements inside a for loop that iterates from 1 to 10. break on the iteration for 5 and continue on the iteration for 7.

Let me know if you need me to provide sample solutions for these exercises without assessments. I can also come up with more exercises to help reinforce these concepts.