Python has several built‑in data types. Some common ones:
5, -33.14, -0.001"hello", 'Python'True, False[1, 2, 3](1, 2, 3){'name':'Alice', 'age':30}{1,2,3}# Examples of data types
a = 10
b = 3.1415
c = "Hello, world!"
d = True
e = [1, 2, 3, 4]
f = (5, 6, 7)
g = {'name': 'Bob', 'age': 25}
h = {1, 2, 2, 3, 3, 3}
print(type(a), type(b), type(c), type(d))
print(e, f, g, h)
Variables are names that refer to values. Python is dynamically typed, so no need to declare types.
x = 5
y = "Python"
z = 3.5
print("x is", x)
print("y is", y)
print("z * x =", z * x)
x = 20
print("x is now", x)
Used to execute different code depending on conditions.
num = 0
if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")
age = 25
if age < 13:
print("Child")
elif 13 <= age < 20:
print("Teenager")
elif 20 <= age < 65:
print("Adult")
else:
print("Senior")
Functions help organize reusable blocks of code.
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
msg = greet("Alice")
print(msg)
s = add(5, 7)
print("Sum is", s)
def power(base, exponent=2):
return base ** exponent
print(power(4))
print(power(4, 3))
Classes define blueprints; objects are instances of them.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hi, I'm {self.name}, and I'm {self.age} years old.")
def have_birthday(self):
self.age += 1
print(f"Happy birthday! I’m now {self.age}.")
p = Person("Charlie", 30)
p.greet()
p.have_birthday()
p.have_birthday()
Combining variables, conditionals, functions, and classes.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")
else:
print("Deposit must be positive.")
def withdraw(self, amount):
if amount <= 0:
print("Withdrawal amount must be positive.")
elif amount > self.balance:
print("Insufficient funds.")
else:
self.balance -= amount
print(f"Withdrew {amount}. New balance: {self.balance}")
acct = BankAccount("Dana", 100)
acct.deposit(50)
acct.withdraw(30)
acct.withdraw(150)