Python Basics: Getting Started with Python Programming
On this page
On this page
Python is one of the most popular programming languages today, known for its simplicity, readability, and versatility. Whether you're a complete beginner or coming from another language, this comprehensive guide will help you master Python fundamentals with practical examples and real-world applications.
What is Python?
Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability and allows developers to express concepts in fewer lines of code than languages like C++ or Java.
Python is used in various domains including web development (Django, Flask), data science (Pandas, NumPy), artificial intelligence (TensorFlow, PyTorch), automation, and more. Its simple syntax makes it perfect for beginners.
Key Features:
- Easy to learn and read
- Interpreted language (no compilation needed)
- Dynamically typed
- Extensive standard library
- Large community and ecosystem
Installing Python
To get started with Python, you need to install it on your system. Python 3.x is the current version (Python 2 is deprecated since 2020).
Check Python version:
# In terminal/command prompt
python --version
# or
python3 --version
# Expected output: Python 3.x.xInstallation Steps:
- Download Python from python.org
- For Mac: Use Homebrew:
brew install python3 - For Linux:
sudo apt-get install python3 - Verify installation:
python3 --version
Recommended Learning Resource: W3Schools Python Tutorial
Basic Syntax and Data Types
Python has a clean and simple syntax. Unlike many languages, Python uses indentation to define code blocks instead of curly braces. Let's explore the fundamental data types:
Basic data types and variables:
# Numbers - Integers and Floats
age = 25 # Integer
price = 19.99 # Float
temperature = -5 # Negative integer
pi = 3.14159 # Float
# Strings - Text data
name = "Python" # Double quotes
greeting = 'Hello, World!' # Single quotes
message = """Multi-line
string example""" # Triple quotes for multi-line
# String formatting (f-strings - Python 3.6+)
name = "Alice"
age = 30
info = f"My name is {name} and I'm {age} years old"
print(info) # Output: My name is Alice and I'm 30 years old
# Booleans - True or False
is_active = True
is_complete = False
is_authenticated = True
# Lists - Ordered, mutable collections
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True] # Can contain different types
# Accessing list elements
print(fruits[0]) # "apple" (first element)
print(fruits[-1]) # "orange" (last element)
print(fruits[0:2]) # ["apple", "banana"] (slicing)
# Dictionaries - Key-value pairs
person = {
"name": "John",
"age": 30,
"city": "New York",
"email": "john@example.com"
}
# Accessing dictionary values
print(person["name"]) # "John"
print(person.get("age")) # 30 (safer method)
print(person.get("phone", "N/A")) # "N/A" (default if key doesn't exist)
# Tuples - Ordered, immutable collections
coordinates = (10, 20)
colors = ("red", "green", "blue")
# Sets - Unordered, unique elements
unique_numbers = {1, 2, 3, 4, 5}
fruits_set = {"apple", "banana", "orange"}Type Checking: You can check the type of a variable using the type() function:
Checking variable types:
x = 42
y = "Hello"
z = [1, 2, 3]
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'list'>Control Structures
Control structures allow you to control the flow of your program. Python supports if-else statements, loops, and more.
If-else statements:
# Basic if statement
age = 18
if age >= 18:
print("You are an adult")
print("You can vote!")
# If-else statement
temperature = 25
if temperature > 30:
print("It's hot outside")
else:
print("It's not too hot")
# If-elif-else (multiple conditions)
score = 85
if score >= 90:
grade = "A"
print("Excellent!")
elif score >= 80:
grade = "B"
print("Good job!")
elif score >= 70:
grade = "C"
print("Not bad")
else:
grade = "F"
print("Need improvement")
# Nested if statements
age = 20
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license first")
else:
print("You're too young to drive")For loops:
# Basic for loop with range
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# For loop with range(start, stop, step)
for i in range(1, 10, 2):
print(i) # Prints 1, 3, 5, 7, 9
# Iterating over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")
# Iterating with index using enumerate
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Iterating over a dictionary
person = {"name": "John", "age": 30, "city": "NYC"}
for key, value in person.items():
print(f"{key}: {value}")
# Nested loops
for i in range(3):
for j in range(2):
print(f"({i}, {j})") # Prints (0,0), (0,1), (1,0), (1,1), (2,0), (2,1)While loops:
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1 # Important: increment to avoid infinite loop
# While loop with break
number = 0
while True:
number += 1
if number > 10:
break # Exit the loop
print(number)
# While loop with continue
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue # Skip even numbers
print(number) # Only prints odd numbers: 1, 3, 5, 7, 9
# Practical example: User input validation
while True:
age = input("Enter your age (or 'quit' to exit): ")
if age.lower() == 'quit':
break
try:
age_int = int(age)
if age_int >= 0:
print(f"Your age is {age_int}")
break
else:
print("Age must be positive")
except ValueError:
print("Please enter a valid number")Functions
Functions allow you to organize and reuse code. They help break down complex problems into smaller, manageable pieces.
Defining and calling functions:
# Simple function
def greet(name):
"""This function greets a person by name."""
return f"Hello, {name}!"
# Call the function
message = greet("Python")
print(message) # Output: Hello, Python!
# Function with multiple parameters
def calculate_area(length, width):
"""Calculate the area of a rectangle."""
return length * width
area = calculate_area(5, 3)
print(f"Area: {area}") # Output: Area: 15
# Function with default parameters
def power(base, exponent=2):
"""Calculate base raised to exponent. Default exponent is 2."""
return base ** exponent
print(power(3)) # 9 (uses default exponent=2)
print(power(3, 3)) # 27 (uses provided exponent=3)
# Function with multiple return values
def get_name_and_age():
"""Return multiple values as a tuple."""
return "Alice", 30
name, age = get_name_and_age()
print(f"{name} is {age} years old")
# Function with keyword arguments
def create_user(name, age, email, city="Unknown"):
"""Create a user with optional city parameter."""
return {
"name": name,
"age": age,
"email": email,
"city": city
}
# Call with keyword arguments (order doesn't matter)
user1 = create_user(name="John", email="john@example.com", age=25)
user2 = create_user("Jane", 30, "jane@example.com", "NYC")Lambda functions (anonymous functions):
# Lambda function - simple one-liner functions
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple parameters
add = lambda x, y: x + y
print(add(3, 4)) # 7
# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Filter with lambda
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]Working with Lists
Lists are one of Python's most powerful data structures. Here are common operations:
List operations:
# Creating and modifying lists
fruits = ["apple", "banana"]
fruits.append("orange") # Add to end
fruits.insert(0, "grape") # Insert at index 0
fruits.remove("banana") # Remove by value
fruits.pop() # Remove and return last item
fruits.pop(0) # Remove item at index 0
# List comprehension (Pythonic way)
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers] # [1, 4, 9, 16, 25]
evens = [x for x in numbers if x % 2 == 0] # [2, 4]
# List methods
numbers = [3, 1, 4, 1, 5]
numbers.sort() # Sort in place: [1, 1, 3, 4, 5]
numbers.reverse() # Reverse: [5, 4, 3, 1, 1]
count = numbers.count(1) # Count occurrences: 2
index = numbers.index(4) # Find index: 1Error Handling
Python uses try-except blocks to handle errors gracefully:
Try-except blocks:
# Basic error handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
# Try-except-else-finally
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
else:
print("File read successfully")
finally:
print("This always executes")
# Close file if it was openedPractical Example: Simple Calculator
Let's build a simple calculator to practice what we've learned:
Simple calculator program:
def calculator():
"""A simple calculator program."""
print("Welcome to Python Calculator!")
print("Operations: +, -, *, /")
try:
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("Error: Division by zero!")
return
result = num1 / num2
else:
print("Invalid operator!")
return
print(f"{num1} {operator} {num2} = {result}")
except ValueError:
print("Error: Please enter valid numbers!")
# Run the calculator
calculator()Learning Resources
Here are excellent resources to continue your Python learning journey:
- W3Schools Python Tutorial: Comprehensive Python guide with examples
- FreeCodeCamp Python Course: Free interactive Python course
- Python.org Official Docs: Official Python tutorial
- Practice: HackerRank Python challenges
Next Steps
Now that you understand Python basics, you can:
- Practice with coding exercises on platforms like HackerRank or LeetCode
- Learn about Python best practices and PEP 8 (our next article!)
- Explore Python libraries like NumPy, Pandas, or Requests
- Build your first Python project (calculator, to-do list, or simple game)
- Join Python communities on Reddit (r/learnpython) or Discord
Continue your learning journey with our next article on Python Best Practices and PEP 8 Guidelines to write professional, maintainable code.
Share Your Feedback
Your thoughts help me improve my content.