Python while and for loops examples

The while loop executes a code block as long as the condition is true. The while loop can be used along with an else condition if you didn't break out of the loop. Here are a few examples

While loop with else statement

>>> x = 1
>>> while x <= 5:
 print("hello " + str(x))
 x += 1
else:
 print("the end")

 
hello 1
hello 2
hello 3
hello 4
hello 5
the end

While loop based on Input value

>>> name = ''
>>> while not name:
 name = raw_input("Please input your name: ")
 print("hello " + name)
else:
 print("the end")

 
Please input your name: 
hello 
Please input your name: 
hello 
Please input your name: world
hello world
the end

While loop with break and continue statements

>>> name = ''
>>> while name != "world":
 name = raw_input("Please input your name: ")
 if name == "one":
  continue
 print("hello " + name)
 if name == "three":
  break
else:
 print("the end")

 
Please input your name: one
Please input your name: two
hello two
Please input your name: three
hello three
The for loop executes a code block over elements in an iterable object. The for loop can be used along with an else condition if you didn't break out of the loop. Here are a few examples

For loop with else statement

>>> myCars = ['BMW','Lexus','Rolls Royce','Ford','Honda','Toyota']
>>> for car in myCars:
 if car == 'Rolls Royce':
  print('nice', end=' ')
 print(car)
else:
 print('the end!')

 
BMW
Lexus
nice Rolls Royce
Ford
Honda
Toyota
the end!

For loop with break and continue statements

>>> myCars = ['BMW','Lexus','Rolls Royce','Ford','Honda','Toyota']
>>> for car in myCars:
 if car == 'Rolls Royce':
  continue
 if car == 'Honda':
  break
 print(car)
else:
 print('the end!')

 
BMW
Lexus
Ford

For loop dictionary example with key and value

>>> myEmployees = {'John':{'age':25,'salary':10000},'Ed':{'age':55,'salary':50000}}
>>> for key in myEmployees:
 print(key + ':')
 print(' Age: ' + str(myEmployees[key]['age']))
 print(' Salary: ' + str(myEmployees[key]['salary']))

 
Ed:
 Age: 55
 Salary: 50000
John:
 Age: 25
 Salary: 10000
>>> for key,value in myEmployees.items():
 print(key + ':')
 print(' Age: ' + str(value['age']))
 print(' Salary: ' + str(value['salary']))

 
Ed:
 Age: 55
 Salary: 50000
John:
 Age: 25
 Salary: 10000

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.