Iteration
An iteration is essentially one complete cycle through a loop. Think of it as a single pass where
the loop performs its actions. Here's a simple way to understand it:
Imagine you have a loop that runs multiple times. Each time the loop runs through its code
block, it’s considered an iteration. For example:
```python
for i in range(3):
print(i)
```
In this case, the loop iterates 3 times:
- **First Iteration**: `i` is `0`
- **Second Iteration**: `i` is `1`
- **Third Iteration**: `i` is `2`
Each iteration executes the code inside the loop once. So, an iteration is one complete
execution of the loop's body.
Menu-Based programs
A menu-based program in Python typically involves presenting a list of options to the user and
allowing them to select one of the options to perform a specific action. Here's a basic example
of how you can implement a menu-based program in Python:
```python
def print_menu():
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero!"
def main():
while True:
print_menu()
choice = input("Enter your choice: ")
if choice == '1':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {add(a, b)}")
elif choice == '2':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {subtract(a, b)}")
elif choice == '3':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {multiply(a, b)}")
elif choice == '4':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {divide(a, b)}")
elif choice == '5':
print("Exiting the program...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
```
In this example, the program displays a menu of options to the user and prompts them to enter
a choice. Depending on the choice, it performs the corresponding arithmetic operation or exits
the program. The `main()` function contains a loop that keeps displaying the menu and
processing user input until the user chooses to exit.
def Keyword
The `def` keyword in Python is used to define a function. Functions are reusable blocks of code
that perform a specific task. Here's a basic example:
```python
def greet():
print("Hello, world!")
```
In this example:
- `def` tells Python that you're about to define a function.
- `greet` is the name of the function.
- The parentheses `()` can hold parameters if needed.
- The colon `:` indicates the start of the function body.
- The indented lines after the colon are the function's code block.
`print_menu` Function
In the context of the menu-based program we discussed, `print_menu` is a user-defined
function that prints the menu options. Here's the function:
```python
def print_menu():
custom_print("1. Add")
custom_print("2. Subtract")
custom_print("3. Multiply")
custom_print("4. Divide")
custom_print("5. Exit")
```
In this example:
- `def print_menu():` defines a new function called `print_menu`.
- The function body contains several calls to `custom_print`, which is another user-defined
function that outputs text.
### Putting It Together
The `print_menu` function is a convenient way to group together all the menu-printing
instructions, so you can call it whenever you need to display the menu to the user. Instead of
writing the same print statements multiple times, you just call `print_menu()` in your code:
```python
def main():
while True:
print_menu()
choice = custom_input("Enter your choice: ")
# Rest of the code...
```
By using `def` to define functions, your code becomes more organized, readable, and
maintainable.
while True:
The `while True:` statement in Python is used to create an infinite loop that will keep running
until explicitly broken with a `break` statement or the program is terminated. It's a way to
continuously execute a block of code.
Here's a simple explanation with an example:
### Explanation:
- **`while`**: This is the loop keyword. It tells Python to repeat the indented block of code
below it.
- **`True`**: This is a condition that always evaluates to `True`. Since the condition is always
`True`, the loop will keep running indefinitely.
- **`:`**: This colon indicates that what follows is the block of code to be repeated.
### Example:
```python
while True:
user_input = input("Enter something (type 'exit' to stop): ")
if user_input.lower() == 'exit':
print("Exiting the loop...")
break
else:
print(f"You entered: {user_input}")
```
### Breakdown:
- **`while True:`**: This starts an infinite loop.
- **`user_input = input("Enter something (type 'exit' to stop): ")`**: Prompts the user to
enter something.
- **`if user_input.lower() == 'exit':`**: Checks if the user input is "exit" (in any case, thanks
to `.lower()`).
- **`print("Exiting the loop...")`**: If the input is "exit," it prints a message.
- **`break`**: This breaks out of the loop, stopping it.
- **`else:`**: If the input is not "exit," it prints what the user entered and the loop continues.
So, using `while True:` allows the program to continuously prompt the user for input until they
decide to exit by typing "exit." This is a common way to create interactive programs that keep
running until the user decides to quit.