Show List
Control Flow
In Python, control flow statements are used to control the flow of execution of code. Here are some common control flow statements in Python, along with examples:
- If-Else Statements: The if-else statement allows you to execute a block of code if a certain condition is true, and another block of code if the condition is false. The basic syntax is:
vbnetCopy codeif condition: # code to be executed if condition is true else: # code to be executed if condition is false
For example:
pythonCopy codex = 10 if x > 5: print("x is greater than 5") else: print("x is less than or equal to 5")
This code will print "x is greater than 5" because the value of x is 10, which is greater than 5.
- For Loops: The for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The basic syntax is:
yamlCopy codefor item in sequence: # code to be executed for each item in the sequence
For example:
cssCopy codefruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)
This code will print each fruit in the list of fruits, one per line:
Copy codeapple banana cherry
- While Loops: The while loop is used to repeat a block of code as long as a certain condition is true. The basic syntax is:
vbnetCopy codewhile condition: # code to be executed as long as condition is true
For example:
pythonCopy codex = 0 while x < 5: print(x) x = x + 1
This code will print the numbers 0 through 4 because the condition x < 5
is true for each iteration of the loop.
These are the basic control flow statements in Python. By using these statements, you can control the flow of execution of your code, making it more flexible and powerful.
Leave a Comment