#7 Python Tutorial for Beginners

Hello Guys,

   In previous tutorial you learned about if statement , if-else statement , Nested if-else statement , elif statement and pass statement.

   In this tutorial you will learn below points:

  • While loop
  • list value with while loop
  • for loop
  • Range function
  • Break statement
  • Continue statement

Let's get started.

While loop

  • while loop allows code to be repeated an number of times as long as condition is being met.
  • while loop the condition is checked first before the code run. If condition is true then body of the loop executed otherwise not.
  • If the loop is entered , the process is continued until the condition become false.
Example :

'''
 In While loop condition is checked first 
 if condition is true then loop of the body executed
 otherwise not
'''

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

Output :

Hello 1
Hello 2
Hello 3
Hello 4     


list value with while loop

  • we can use list with while loop for executed list values.
Example :

'''
  We can use list with while loop  
  for executed list values
'''


number = ["23" , "45" , "12" , "5" , "89"]

i = 0
while i < len(number):
      print(number[i])
      i = i + 1

Output :

23
45
12
5
89


for loop

  • for loop allows python to keep repeating code a set number of times. It sometimes known as a counting loop.
Example :

fruits = ["Grapes" , "Mango" , "Orange" , "Banana" , "Watermelon"]

for i in fruits:
    print(i)

'''
  We are using list with for loop  
  for executed list values
'''

Output :

Grapes
Mango
Orange
Banana
Watermelon


Range function

  • The range function in python is used to generate a sequence of numbers.
  • we can also specify the start  , stop  and step-size.
Example :


for i in range(1 ,102):
    print(i)
     

Output :

1
3
5
7
9     


Break Statement

  • break statement is used to exit from the loop when encountered. It instruct the program to exit from the loop.
Example :

for i in range(10):
    
    if i == 5:
         break 
    
    print(i)
    

Output :

0
1
2
3
4


Continue Statement

  • continue statement is used to stop the current iteration of the loop and continue with next one.It instruct the program to skip the iteration.
Example :

for i in range(10):
    
    if i == 5:
        continue 
    
    print(i)
    
 
Output :

0
1
2
3
4
6
7
8
9    



I hope you like post. If you liked this post do comment ,share and promote the post 🙏 . Please stay with us and support.  🙏   

Post a Comment

1 Comments