Variables are used to store information in Python.
name = "Daniel"age = 25height = 1.75is_student = True
Common Python data types:
int → Integer numbersfloat → Decimal numbersstr → Textbool → True or Falselist → Ordered collectiondict → Key-value collectionPrograms become interactive when users can provide input.
name = input("Enter your name: ")print("Hello", name)
input() receives user data.
print() displays output.
Conditional statements allow programs to make decisions.
age = 18if age >= 18:print("Adult")else:print("Child")
Important keywords:
ifelifelseLoops repeat actions automatically.
for i in range(5):print(i)
count = 0while count < 5:print(count)count += 1
Functions help organize reusable code.
def greet(name):return f"Hello {name}"print(greet("Daniel"))
Benefits of functions:
Python collections help store multiple values.
fruits = ["apple", "banana", "orange"]print(fruits[0])
user = {"name": "Daniel","age": 25}print(user["name"])
OOP organizes code using classes and objects.
class Dog:def __init__(self, name):self.name = namedef bark(self):print("Woof!")dog = Dog("Buddy")dog.bark()
Key OOP concepts:
Programs should handle errors gracefully.
try:num = int(input("Enter number: "))print(num)except:print("Invalid input")
Python provides many built-in and external libraries.
import mathprint(math.sqrt(16))
Install packages using pip:
pip install requests
Popular beginner libraries:
Python can read and write files.
with open("test.txt", "w") as file:file.write("Hello Python")
File handling is useful for:
The with … as statement is used for safe resource management in Python.
It is commonly used with:
with open("test.txt", "r") as file:content = file.read()print(content)