Program 2
Program 2
**********************************************************************
b) Loops
For Loop:
********************************************************************
for i in range(1, 6):
print(i) # Prints numbers from 1 to 5
*******************************************************************
While Loop:
*********************************************************************
count = 0
while count < 5:
print(count)
count += 1 # Increment
*********************************************************************
7. Functions
Functions are reusable blocks of code.
********************************************************************
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
********************************************************************
Built-in Functions: len(), max(), min(), type(), range().
User-Defined Functions: Created with the def keyword.
*****************************************************************
8. Lists and Loops
Lists are used to store multiple items in a single variable.
***************************************************************************
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
*****************************************************************************
# Start with an empty list
fruits = []
# Add items to the list using .append()
fruits.append("apple")
fruits.append("banana")
fruits.append("cherry")
# Print the list
print(fruits)
**********************************************************************************
9. Error Handling
Use try and except to handle errors.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input. Please enter a number.")
****************************************************************
10. Practical Example: Calculator
def calculator():
print("Simple Calculator")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == '+':
print("Result:", num1 + num2)
elif operation == '-':
print("Result:", num1 - num2)
elif operation == '*':
print("Result:", num1 * num2)
elif operation == '/':
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Error: Division by zero")
else:
print("Invalid operation")
calculator()