0% found this document useful (0 votes)
8 views

Program 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Program 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

else:

print("x is less than 5")

**********************************************************************
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()

You might also like