Python Learning Guide
This guide provides a structured introduction to Python programming,
designed for beginners. Each chapter covers fundamental topics with examples and exercises.
1. Introduction to Python
Python is a popular programming language known for its simplicity and versatility.
It is used in web development, data analysis, artificial intelligence, and more.
Key features:
- Easy to learn
- Open source
- Wide range of libraries
Examples:
print("Hello, World!")
a=5
b = 10
print(a + b)
2. Variables and Data Types
Variables are used to store data. Python supports different data types:
- int: whole numbers (e.g., 5)
- float: decimal numbers (e.g., 3.14)
- str: text (e.g., "hello")
- bool: true/false (e.g., True, False)
Examples:
name = "Alice"
age = 25
height = 5.6
is_student = True
print(type(name), type(age), type(height), type(is_student))
3. Input and Output
Python uses the input() function to get user input and print() to display output.
Examples:
name = input("Enter your name: ")
print("Hello, " + name + "!")
You can use type casting to convert input types:
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
4. Operators in Python
Python supports arithmetic, comparison, logical, and bitwise operators.
Examples:
a = 10
b=3
print(a + b, a - b, a * b, a / b, a % b)
Comparison:
print(a > b, a == b, a != b)
Logical:
print(a > b and a > 5)
5. Conditional Statements
Python supports if, elif, and else for decision-making.
Examples:
age = int(input("Enter your age: "))
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 60:
print("You are an adult.")
else:
print("You are a senior.")
6. Loops in Python
Python supports for and while loops for iteration.
Examples:
for i in range(5):
print(i)
n=5
while n > 0:
print(n)
n -= 1
7. Functions
Functions allow you to reuse code. Use def to define a function.
Examples:
def greet(name):
print("Hello, " + name)
greet("Alice")
8. Lists and Tuples
Lists are mutable, while tuples are immutable.
Examples:
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
numbers = (1, 2, 3)
print(numbers[1])
9. Dictionaries
Dictionaries store key-value pairs.
Examples:
person = {"name": "Alice", "age": 25}
print(person["name"], person.get("age"))
10. Exception Handling
Use try, except to handle errors.
Examples:
try:
x = int(input("Enter a number: "))
print(x / 0)
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")