loops in Python with examples and different problems

GulziraIzbassova 68 views 19 slides May 10, 2024
Slide 1
Slide 1 of 19
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19

About This Presentation

Python Loops


Slide Content

Python Loops

Python has two primitive loop commands: while  loops for  loops

The while Loop With the  while  loop we can execute a set of statements as long as a condition is true. Note:  remember to increment i , or else the loop will continue forever.

The  while  loop requires relevant variables to be ready, in this example we need to define an indexing variable,  i , which we set to 1.

The break Statement With the  break  statement we can stop the loop even if the while condition is true:

The continue Statement With the  continue  statement we can stop the current iteration, and continue with the next:

The else Statement With the  else  statement we can run a block of code once when the condition no longer is true:

Assignments Counting Up : Write a program that prints numbers from 1 to 10 using a while loop. Solution

Even Numbers : Create a program that prints all even numbers from 1 to 20 using a while loop. Solution

Countdown : Write a program that counts down from 10 to 1 and then prints "Blast off!" using a while loop.

Square Numbers : Develop a program that prints the square of numbers from 1 to 5 using a while loop. Solution

Character Printing : Create a program that prints each character of a given word entered by the user on a separate line using a while loop. Solution

Letter Counter : Write a program that counts the number of letters in a word entered by the user using a while loop. Solution

Positive Number Sum : Develop a program that asks the user for positive numbers and prints their sum. The program should stop when the user enters a negative number using a while loop. Solution

Power of Two : Create a program that prints the powers of 2 from 2^0 to 2^5 using a while loop. Solution

Vowel Counter : Write a program that counts the number of vowels (a, e, i , o, u) in a word entered by the user using a while loop. Solution

Name Repeater : Develop a program that asks the user for their name and then prints it 10 times using a while loop. Solution