Introduction
Python is a high-level programming language widely used in science, engineering, and many other fields. It is user-friendly and allows users to interact with a computer using simple, readable syntax instead of complex assembly or binary commands.
This guide covers loops (for and while) and conditionals (if, elif, else), which are fundamental for controlling the flow of your programs.
Loops
Loops allow you to repeat a block of code multiple times. Python provides two primary types of loops: for and while.
For Loops
A **for loop** is used to iterate over a sequence (e.g., a list, tuple, string, or range). The range() function is commonly used to generate a sequence of numbers.
The range() Function
The range() function generates a sequence of numbers. It can take up to three arguments:
range(stop): Generates numbers from0tostop-1.range(start, stop): Generates numbers fromstarttostop-1.range(start, stop, step): Generates numbers fromstarttostop-1, incrementing bystep.
Examples
Print numbers from 0 to 4:
| |
Output:
| |
Print numbers from 3 to 5:
| |
Output:
| |
Print numbers from 3 to 7, stepping by 2:
| |
Output:
| |
Iterating Over Sequences
You can also iterate directly over sequences like lists, tuples, or strings.
| |
Output:
| |
While Loops
A **while loop** repeats a block of code **as long as a condition is True**. It is often used for infinite loops or loops where the number of iterations is not known in advance.
Example
Print numbers from 0 to 4:
| |
Output:
| |
Infinite Loop Example
A while loop with a condition that is always True will run indefinitely unless broken.
| |
Break and Continue
**break**: Exits the loop immediately.**continue**: Skips the current iteration and moves to the next one.
Example with break
Exit the loop when count reaches 5:
| |
Output:
| |
Example with continue
Skip even numbers:
| |
Output:
| |
The else Clause in Loops
In Python, loops can have an **else clause** that executes after the loop completes normally (i.e., not terminated by a break statement).
Example with for and else
Print a message after the loop completes:
| |
Output:
| |
Example with while and else
Print a message when count reaches 5:
| |
Output:
| |
Example with break and else
The else block is skipped if the loop is terminated by break:
| |
Output:
| |
Conditionals
Conditionals allow you to **execute different blocks of code based on whether a condition is True or False**. Python uses the keywords if, elif (short for “else if”), and else for conditionals.
If, Elif, and Else
**if**: Executes a block of code if a condition isTrue.**elif**: Checks another condition if the previousiforelifcondition wasFalse.**else**: Executes a block of code if all previous conditions wereFalse.
Example
Assign a grade based on a score:
| |
Output:
| |
Boolean Logic in Conditionals
You can use boolean operators (and, or, not) to build complex conditions.
Example
Check if a number is between 10 and 20:
| |
Output:
| |
The in Operator
The in operator checks if a value exists in a sequence (e.g., list, tuple, string, set, dictionary).
Example
Check if a fruit is in a list:
| |
Output:
| |
The is Operator
The is operator checks if two variables refer to the same object in memory, not just if their values are equal.
Example
Compare two variables:
| |
Output:
| |
Indentation in Python
Python uses indentation (whitespace at the beginning of a line) to define code blocks, instead of brackets or braces. The standard indentation is 4 spaces, but you can use tabs or any consistent number of spaces.
Example
Correct indentation:
| |
Output:
| |
Nested Loops and Conditionals
You can nest loops and conditionals to create more complex logic.
Example
Print even numbers from 0 to 9:
| |
Output:
| |
Conclusion
Loops (for and while) and conditionals (if, elif, else) are essential for controlling the flow of your Python programs. They allow you to:
- Repeat actions with loops.
- Make decisions with conditionals.
- Combine them for complex logic.
Understanding these concepts is key to writing efficient and readable Python code.