1. Basic Data Types, Operators, Expressions, and Input/Output
# Basic Data Types
a = 10 # integer
b = 3.5 # float
c = "Hello" # string
d = True # boolean
# Operators and Expressions
sum_result = a + b
product = a * b
# Input and Output
name = input("Enter your name: ")
print("Hello,", name)
print("Sum is:", sum_result)
print("Product is:", product)
2. Strings and Conditional Statements
# Strings
text = "Python is fun"
print(text.upper()) # converts to uppercase
print(text.lower()) # converts to lowercase
# Conditional Statements
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
3. Lists and Tuples Using Built-in Functions
# List
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # adding an element
print(fruits)
print(len(fruits)) # number of elements
# Tuple
colors = ("red", "green", "blue")
print(colors)
print(colors.index("green")) # find index of element
4. Looping Concepts
# For loop
for i in range(5):
print("Number:", i)
# While loop
count = 0
while count < 3:
print("Count:", count)
count += 1
5. Object-Oriented Programming (OOP) Concepts
# Class and Object Example
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def display(self):
print("Name:", self.name)
print("Roll Number:", self.roll)
# Creating object
s1 = Student("Niraj", 101)
s1.display()
10. Exception Handling (Different Types and Statements)
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")
except Exception as e:
print("An error occurred:", e)
finally:
print("Execution completed.")
Comments
Post a Comment