Loops in Python

What are loops (cycles)

Loops are control statements which allows a block of code to be executed multiple times.
This repetition of a code can be fixed number of times (for loop) or while some condition is fulfilled (while loop).
Each execution of the code, during the loop, is called an iteration!

while loop

Syntax


			while condition :
				block
		
The block will be executed while the condition is True!
Inside the block we have to change the variable used in condition to prevent an endless loop. Or we can use break statement (discussed further)

Flow

Simple example


			i = 1
			while i<=5 :
				print(i)
				i += 1
		

			1
			2
			3
			4
			5
		

Example: endless loop (find the problem)

If you run next code, your Python will run an endless loop. Use CTRL+C or CTRL+Z to stop it


			# print the numbers from 10 to 1:
			i = 10
			while i>=1 :
				print(i)
				i = 1
		

Example: sum all numbers in [1..100]


			i = 1
			sum = 0
			while i <= 100:
				sum += i
				i += 1
			print("sum = ", sum)
		

			sum =  5050
		

Task: sum even numbers in [1..100]

Modify the previous example, but calculate the sum only of the even numbers in the given interval [1..100]

			sum =  2550
		

for loop

Syntax


			for item in sequence :
				#do something with item
		
Python for statement is different than the "C-based" for in other popular languages (C#, Java, PHP, JavaScript)
In Python, for statement iterates over the items of any sequence.
This is common to foreach loop concept in above-mentioned languages

Flow

Simple example 1

Iterate over symbols in string:


			for s in "ada":
				print(s.capitalize())
		

			A
			D
			A
		

Simple example 2

Iterate over list of numbers:


			for num in [1,2,3,4]:
				print(num)
		

			1
			2
			3
			4
		

Nested for loops


			for i in [1,2,3]:
				for j in "abv":
					print(j)
				print("\n") #prints new line
		
More examples and real-world usage of the for statement will be shown in Sequence data types theme!

break statement

Syntax in while loop


			while condition:
				block 1
				if break_cond:
					break  # loop is terminated, block 2 is skipped
				block 2
		

Syntax in for loop


			for item in sequence :
				block 1
				if break_cond:
					break  # loop is terminated, block 2 is skipped
				block 2
		

Flow

Example - Output letters in a string, until 'i' letter is reached


			str = "alibaba"
			for s in str:
			    if s == "i": break
			    print(s)
		

			a
			l
		

Example - do-while emulation with break


			while True:
			  user_number = int(input("Enter a positive number: "))
			  if user_number > 0:
			    break

			print("Nice, your number is: ", user_number
		

Example - do-while emulation without break


			user_number = int(input("Enter a positive number: "))
			while user_number <= 0:
			  user_number = int(input("Enter a positive number: "))

			print("Nice, your number is: ", user_number)
		

Can you imagine how the code would look like, if the "do" block was more than 1 line long?

Task: prompt user to enter at least 3 symbols long user name

Implement a program, which will asks the user for a user name with at least 3 symbols in it.
Bellow is the desired output

			Enter your user name (at least 3 symbols):
			*** At least 3 symbols, please! Try again.

			Enter your user name (at least 3 symbols): iv
			*** At least 3 symbols, please! Try again.

			Enter your user name (at least 3 symbols): iva
			Nice, your user_name is:  iva
		

continue statement

Returns the control to the beginning of the loop.
code after continue will be skipped.
Usually, continue statement is dependent on some condition.

Syntax in while loop


			while condition:
				block 1
				if continue_cond:
					continue  # go to while condition
				block 2
		

Flow

Example - print all numbers in [1..5], but skip 3


			for i in [1,2,3,4,5]:
			  if i == 3:
			     continue
			  print(i)
		

			1
			2
			4
			5
		

Example - print symbols in a string, excluding vowels:


			str = "alabala"
			for s in str:
			  if s in ["a", "e", "i", "o", "u", "y"]:
			      continue
			  print(s)
		

			l
			b
			l
		

HW

"Guess the number" - full version

Write the full version of the "Guess the number" game, implementing the same rules as given in Guess the number game - the beginning, but giving the user the chance to try more than once.
The user now will have 5 tries to guess.
If he/she could not manage to guess the number for 5 tries, the game stops, with a message:
"You lost! My number was X"
where X is the machine number

These slides are based on

customised version of

Hakimel's reveal.js

framework