Python

Comparison between "for" , "while" and "if" statements

Click for All Topics

Comparison between "for" , "while" and "if" statements - Python

 

FeatureFor LoopWhile LoopIf Statement
PurposeRepeats actions a fixed number of times, iterating over a sequence.Repeats actions based on a condition, as long as the condition is true.Executes code only if a specific condition is true.
UsageUseful when you know the number of iterations beforehand.Useful when you’re not sure about the number of iterations, relying on a condition.Useful for making decisions and choosing between alternatives.
StructureTypically involves specifying a range or sequence to iterate over.Involves setting a condition that controls whether the loop runs or not.Involves checking a condition and executing code based on whether it’s true or false.
Examplefor num in range(5): <br>   print(num)while temperature > 0: <br>   cool_down()if age >= 18: <br>   print("You can vote!")
ContinuationIterates a predefined number of times.Repeats as long as the condition remains true.Executes only if the condition is met.
Typical Use CasesProcessing elements in lists, sequences.Repeated tasks like game loops or user input validation.Making decisions based on conditions, executing different code paths.

 

Example 1-

				
					my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set)

# Output - 
# {1,2,3}
				
			
  • In the above example first, we create an empty set using the set function and store it on the my_set variable.
  • After creating an empty set first we add 1 in my_set using the .add() method.
  • After adding 1 we also add 2 and 3 in my_set.
  • After that print my_set using the print() function.

Example 2-

				
					my_set2={10,20,30}
my_set2.add(40)
my_set2.add(20)
print(my_set2)

# Output-
# {40, 10, 20, 30}
				
			
  • In the above example, we see that we couldn’t add 20 in my_set2 because 20 is already present in my_set2.

Example 3-

				
					my_set3={'this','is','edSlash'}
my_set3.add('Hello')
print(my_set3)
my_set3.add('anurag','dubey')  #will give an error think about it.

# Output - 
# {'Hello','this','is','edSlash'} # may be your output in a different order
# Traceback (most recent call last):
  # File "/home/main.py", line 4, in <module>
    # my_set3.add('anurag','dubey')  
# TypeError: set.add() takes exactly one argument (2 given)
				
			
  • In the above example, line 4 gives an error because we give two arguments to the add method.
  • You can use the update method to add multiple elements in a set at one time.

Example 4-

				
					my_set4={'a','b','c','d'}
my_set4.add(('e','f','g'))
print(my_set4)

# Output -
# {'a', ('e', 'f', 'g'), 'c', 'd', 'b'}
				
			

Example 5-

				
					my_set5 = set()
for i in range(1, 6):
    my_set5.add(i)
print(my_set5) 

# Output -
# {1,2,3,4,5}
				
			
  • In the above example, we see that we can add elements in a set using the for loop by add method.