Python Programming
Learn the basics of Python, a versatile and beginner-friendly programming language used in web development, data science, AI, and more.
Python Basics
Getting Started
Python is known for its clean syntax and readability. Here's a simple "Hello, World!" program:
To run this code, save it in a file with a .py extension (e.g., hello.py) and run it with the Python interpreter.
Variables and Data Types
Python has several built-in data types:
x = 10 # Integer
y = 3.14 # Float
# Strings
name = "Python"
# Boolean
is_fun = True
# Lists (ordered, mutable)
fruits = ["apple", "banana", "cherry"]
# Tuples (ordered, immutable)
coordinates = (10, 20)
# Dictionaries (key-value pairs)
person = {"name": "John", "age": 30}
Control Flow
Python uses indentation to define code blocks:
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# For loop
for fruit in fruits:
print(fruit)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Functions
Functions are defined using the 'def' keyword:
def greet(name):
return f"Hello, {name}!"
# Call the function
message = greet("World")
print(message) # Output: Hello, World!
# Function with default parameter
def power(base, exponent=2):
return base ** exponent
print(power(5)) # Output: 25
print(power(2, 3)) # Output: 8
The Most Important Codes in Python
age = 30 # Integer
height = 5.9 # Float
is_student = True # Boolean
my_list = [1, 2, 3] # List
my_dict = {"name": "Bob", "city": "New York"} # Dictionary
my_tuple = (4, 5, 6) # Tuple
my_set = {7, 8, 9} # Set
Explanation
Python supports various data types to store different kinds of information:
- Strings: Text data enclosed in quotes
- Integers: Whole numbers without decimal points
- Floats: Numbers with decimal points
- Booleans: True or False values
- Lists: Ordered, mutable collections of items
- Dictionaries: Key-value pairs for efficient data lookup
- Tuples: Ordered, immutable collections of items
- Sets: Unordered collections of unique items
print("Adult")
elif age >=13:
print("Teenager")
else:
print("Child")
Explanation
Conditional statements let your program make decisions based on conditions. The if statement checks a condition; if true, it executes the indented code block. If false, it checks the elif (else if) condition. If all conditions are false, the else block executes. This example categorizes a person as an adult, teenager, or child based on their age.
print(item)
Explanation
The for loop iterates over each item in a sequence (like a list, tuple, or string). In this example, it prints each number in my_list one by one. For loops are essential for processing collections of data without writing repetitive code.
while count < 3:
print(count)
count += 1
Explanation
The while loop executes a block of code as long as a condition remains true. This example prints numbers from 0 to 2. The counter variable must be updated within the loop (using count += 1) to eventually make the condition false; otherwise, you'll create an infinite loop.
return a + b
result = add_numbers(5, 3)
print(result)
Explanation
Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs more modular. This example defines a function that adds two numbers and returns the result. The function is then called with arguments 5 and 3, and the result (8) is printed.
try:
with open("my_file.txt", "w") as f:
f.write("Hello, world!")
except FileNotFoundError:
print("File not found")
# Reading from a file
try:
with open("my_file.txt", "r") as f:
content = f.read()
print(content)
except FileNotFoundError:
print("File not found")
Explanation
Python makes it easy to work with files. The with statement ensures proper file handling (automatically closing files). The first example writes text to a file, while the second reads from a file. The try/except blocks handle potential errors, like when a file doesn't exist.
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Explanation
Error handling with try/except blocks allows your program to gracefully handle exceptions instead of crashing. This example attempts to divide by zero (which would normally cause an error), but the except block catches the ZeroDivisionError and displays a friendly message instead.
print("Your name is:", user_name)
Explanation
The input() function gets text input from the user, while print() displays output. This example prompts the user to enter their name, stores it in a variable, and then displays it back. These functions are fundamental for creating interactive programs.
print(math.sqrt(16))
import os
print(os.getcwd()) #Print current working directory.
Explanation
Python's power comes from its extensive standard library and third-party packages. The import statement lets you use code from other modules. This example imports the math module to calculate a square root and the os module to get the current working directory. Imports extend Python's capabilities without reinventing the wheel.
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name)
my_dog.bark()
Explanation
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to model real-world entities. This example defines a Dog class with attributes (name, breed) and a method (bark). The __init__ method is a special constructor that initializes a new object. After creating a dog object, you can access its attributes and call its methods. OOP helps organize code, especially for complex applications.
Common Python Tasks
# Add an item
numbers.append(6)
# Insert at position
numbers.insert(0, 0)
# Remove an item
numbers.remove(3)
# List comprehension
squares = [x**2 for x in numbers]
# String methods
print(text.upper())
print(text.lower())
print(text.replace("P", "J"))
# String formatting
name = "Alice"
age = 25
print(f"{name} is {age} years old")
with open("example.txt", "w") as file:
file.write("Hello, Python!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"{e}")
finally:
print("This always executes")
Popular Python Libraries
Python's strength comes from its vast ecosystem of libraries:
NumPy
For numerical computing and working with arrays
Pandas
For data analysis and manipulation
Matplotlib
For creating visualizations and plots
Django & Flask
For web development
TensorFlow & PyTorch
For machine learning and AI
Learning Resources
Continue your Python journey with these resources:
- A full YouTube course to learn Python
- Official Python Documentation: docs.python.org
- Python for Everybody: py4e.com
- Real Python: realpython.com
- Automate the Boring Stuff with Python: automatetheboringstuff.com