Home Python Complete Python Tutorial for Beginners 2025

Complete Python Tutorial for Beginners 2025

06/01/2026
Complete Python Tutorial for Beginners 2025

Complete Python Tutorial for Beginners 2025: Learn Python Programming from Scratch

Introduction to Python Programming Language

Python has emerged as one of the most popular and versatile programming languages in the world, powering everything from web applications and data analysis to artificial intelligence and automation. Its clean syntax, extensive libraries, and beginner-friendly nature make Python the ideal first programming language for aspiring developers, data scientists, and software engineers.

This comprehensive Python tutorial guides you from fundamental concepts to practical programming skills, providing hands-on code examples you can run immediately. Whether you're pursuing a career in software development, data science, machine learning, or web development, mastering Python opens countless opportunities in today's technology-driven economy.

Why Learn Python Programming?

Python's popularity stems from multiple factors that make it exceptionally valuable for both beginners and experienced programmers. The language emphasizes code readability through its use of significant whitespace and intuitive syntax, allowing developers to express complex concepts with fewer lines of code compared to languages like Java or C++.

Career Opportunities: Python developers earn competitive salaries averaging between seventy thousand to one hundred thirty thousand dollars annually in the United States, with senior positions and specialized roles commanding even higher compensation. Demand for Python skills continues growing across industries including technology, finance, healthcare, education, and scientific research.

Versatility: Python excels in diverse domains including web development with frameworks like Django and Flask, data science and machine learning with libraries like NumPy, Pandas, and TensorFlow, automation and scripting for repetitive tasks, scientific computing and research, game development, cybersecurity, and Internet of Things applications.

Community and Resources: Python boasts one of the largest and most supportive programming communities, providing extensive documentation, tutorials, forums, and open-source libraries. This ecosystem accelerates learning and problem-solving, making Python development efficient and enjoyable.

Installing Python and Setting Up Your Environment

Downloading and Installing Python

Visit python.org and download the latest Python version for your operating system. During installation on Windows, ensure you check the "Add Python to PATH" option, which enables running Python from the command line without specifying the full installation path.

Verifying Installation: Open your terminal or command prompt and type:

python --version

This command displays your installed Python version, confirming successful installation. On some systems, you might need to use python3 instead of python.

Choosing a Python Development Environment

IDLE: Python includes IDLE, a simple integrated development environment perfect for beginners. It provides an interactive shell for testing code snippets and a text editor for writing complete programs.

Visual Studio Code: This free, powerful code editor offers excellent Python support through extensions. Install the Python extension from Microsoft for features including syntax highlighting, code completion, debugging, and integrated terminal.

PyCharm: JetBrains develops PyCharm, a professional Python IDE offering comprehensive features including intelligent code completion, project navigation, debugging tools, and testing frameworks. The free Community Edition provides everything beginners need.

Jupyter Notebook: Popular among data scientists, Jupyter Notebook combines code, visualizations, and narrative text in interactive documents. Install it using pip install jupyter and launch it with jupyter notebook command.

For beginners, start with IDLE or Visual Studio Code to learn fundamentals before exploring specialized IDEs.

Python Basics: Your First Program

Hello World Program

Every programming journey begins with the classic "Hello World" program. Python makes this remarkably simple:

print("Hello, World!")

Save this code in a file named hello.py and run it from terminal using python hello.py. The print() function displays output to the screen, forming the foundation for understanding program execution.

Variables and Data Types

Variables store information that programs can manipulate. Python dynamically determines variable types, eliminating explicit type declarations:

# String variables
name = "John Doe"
message = 'Welcome to Python'

# Integer variables
age = 25
year = 2025

# Float variables
price = 19.99
temperature = 98.6

# Boolean variables
is_student = True
has_license = False

# Printing variables
print("Name:", name)
print("Age:", age)
print("Price: $" + str(price))

Variable Naming Rules:

  • Must start with letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive (age and Age are different variables)
  • Cannot use Python keywords (if, for, while, etc.)
  • Use descriptive names (student_grade instead of sg)

Python Comments

Comments document code without affecting execution:

# This is a single-line comment

"""
This is a multi-line comment
useful for longer explanations
or temporarily disabling code blocks
"""

x = 10  # Inline comment explaining the variable

Python Data Types and Type Conversion

Basic Data Types

# Strings
first_name = "Python"
last_name = "Programming"
full_name = first_name + " " + last_name  # String concatenation
print(full_name)

# Numbers - Integers
students = 100
score = -15
large_number = 1000000

# Numbers - Floats
pi = 3.14159
discount = 0.25
temperature = -40.5

# Boolean
is_active = True
is_deleted = False

# Checking data type
print(type(first_name))  # <class 'str'>
print(type(students))    # <class 'int'>
print(type(pi))          # <class 'float'>
print(type(is_active))   # <class 'bool'>

Type Conversion

Converting between data types enables flexible data manipulation:

# String to integer
age_str = "25"
age_int = int(age_str)
print(age_int + 5)  # Outputs: 30

# Integer to string
score = 95
score_str = str(score)
print("Your score is: " + score_str)

# String to float
price_str = "19.99"
price_float = float(price_str)
print(price_float * 2)  # Outputs: 39.98

# Float to integer (truncates decimal)
value = 19.99
value_int = int(value)
print(value_int)  # Outputs: 19

Python Operators

Arithmetic Operators

# Basic arithmetic
a = 10
b = 3

print(a + b)   # Addition: 13
print(a - b)   # Subtraction: 7
print(a * b)   # Multiplication: 30
print(a / b)   # Division: 3.3333...
print(a // b)  # Floor division: 3
print(a % b)   # Modulus (remainder): 1
print(a ** b)  # Exponentiation: 1000

# Practical examples
price = 49.99
quantity = 3
total = price * quantity
print(f"Total cost: ${total}")

# Calculate average
num1 = 85
num2 = 92
num3 = 78
average = (num1 + num2 + num3) / 3
print(f"Average score: {average:.2f}")

Comparison Operators

x = 10
y = 20

print(x == y)  # Equal to: False
print(x != y)  # Not equal to: True
print(x > y)   # Greater than: False
print(x < y)   # Less than: True
print(x >= y)  # Greater than or equal to: False
print(x <= y)  # Less than or equal to: True

# Comparing strings
name1 = "Alice"
name2 = "Bob"
print(name1 == name2)  # False
print(name1 < name2)   # True (alphabetical comparison)

Logical Operators

# and operator - both conditions must be True
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(can_drive)  # True

# or operator - at least one condition must be True
is_weekend = True
is_holiday = False
can_relax = is_weekend or is_holiday
print(can_relax)  # True

# not operator - reverses boolean value
is_raining = False
can_go_outside = not is_raining
print(can_go_outside)  # True

# Complex conditions
score = 85
attendance = 90
passed = score >= 70 and attendance >= 80
print(f"Student passed: {passed}")

Python Strings and String Methods

String Operations

# String creation
message = "Python Programming"
quote = 'Learning is fun'
multiline = """This is a
multi-line string
in Python"""

# String indexing (zero-based)
text = "Python"
print(text[0])   # P
print(text[1])   # y
print(text[-1])  # n (last character)
print(text[-2])  # o (second from last)

# String slicing
print(text[0:3])   # Pyt
print(text[2:])    # thon
print(text[:4])    # Pyth
print(text[1:5])   # ytho

# String length
print(len(text))   # 6

Common String Methods

text = "python programming"

# Case conversion
print(text.upper())        # PYTHON PROGRAMMING
print(text.lower())        # python programming
print(text.capitalize())   # Python programming
print(text.title())        # Python Programming

# String manipulation
print(text.replace("python", "Java"))  # Java programming
print(text.strip())        # Remove whitespace
print(text.split())        # ['python', 'programming']

# String checking methods
email = "user@example.com"
print(email.startswith("user"))   # True
print(email.endswith(".com"))     # True
print(text.isalpha())             # False (has space)
print("12345".isdigit())          # True

# Finding substrings
sentence = "Python is easy to learn"
print(sentence.find("easy"))      # 10 (index position)
print(sentence.count("e"))        # 3 (occurrences)

# String formatting
name = "Alice"
age = 30
# f-strings (Python 3.6+)
message = f"My name is {name} and I am {age} years old"
print(message)

# format() method
message = "My name is {} and I am {} years old".format(name, age)
print(message)

Python Lists and List Operations

Lists store multiple items in a single variable, forming one of Python's most versatile data structures:

# Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty_list = []

# Accessing list elements
print(fruits[0])    # apple
print(fruits[-1])   # orange
print(fruits[1:3])  # ['banana', 'orange']

# Modifying lists
fruits[1] = "grape"
print(fruits)  # ['apple', 'grape', 'orange']

# List methods
fruits.append("mango")        # Add to end
fruits.insert(1, "kiwi")      # Insert at position
fruits.remove("orange")       # Remove specific item
last_fruit = fruits.pop()     # Remove and return last item
fruits.sort()                 # Sort alphabetically
fruits.reverse()              # Reverse order
print(len(fruits))            # Get list length

# List operations
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2      # [1, 2, 3, 4, 5, 6]
repeated = list1 * 3          # [1, 2, 3, 1, 2, 3, 1, 2, 3]

# Checking membership
print("apple" in fruits)      # True or False
print("grape" not in fruits)  # True or False

# List comprehension (advanced)
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Python Tuples and Sets

Tuples - Immutable Sequences

# Creating tuples
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (42,)  # Comma required for single item

# Accessing tuple elements
print(coordinates[0])  # 10
print(colors[1:3])     # ('green', 'blue')

# Tuples are immutable
# coordinates[0] = 15  # This would cause an error

# Tuple unpacking
x, y = coordinates
print(f"X: {x}, Y: {y}")

# Multiple return values from functions
def get_user_info():
    return ("John", 25, "USA")

name, age, country = get_user_info()
print(name, age, country)

Sets - Unique Collections

# Creating sets
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}
empty_set = set()  # Not {} which creates empty dict

# Adding and removing
fruits.add("mango")
fruits.remove("banana")
fruits.discard("grape")  # Won't error if item doesn't exist

# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1.union(set2))        # {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2)) # {3, 4}
print(set1.difference(set2))   # {1, 2}

# Removing duplicates from list
numbers_list = [1, 2, 2, 3, 3, 3, 4]
unique_numbers = list(set(numbers_list))
print(unique_numbers)  # [1, 2, 3, 4]

Python Dictionaries

Dictionaries store key-value pairs, providing efficient data lookup:

# Creating dictionaries
student = {
    "name": "Alice",
    "age": 20,
    "grade": "A",
    "courses": ["Math", "Science"]
}

# Accessing values
print(student["name"])           # Alice
print(student.get("age"))        # 20
print(student.get("email", "N/A"))  # N/A (default value)

# Modifying dictionaries
student["age"] = 21              # Update value
student["email"] = "alice@email.com"  # Add new key
del student["grade"]             # Delete key

# Dictionary methods
print(student.keys())            # Get all keys
print(student.values())          # Get all values
print(student.items())           # Get key-value pairs

# Looping through dictionaries
for key, value in student.items():
    print(f"{key}: {value}")

# Nested dictionaries
users = {
    "user1": {"name": "John", "age": 25},
    "user2": {"name": "Jane", "age": 30}
}

print(users["user1"]["name"])  # John

# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Conditional Statements in Python

If-Else Statements

# Simple if statement
age = 18
if age >= 18:
    print("You are an adult")

# If-else statement
temperature = 25
if temperature > 30:
    print("It's hot outside")
else:
    print("Weather is pleasant")

# If-elif-else statement
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is: {grade}")

# Nested conditions
age = 20
has_license = True

if age >= 18:
    if has_license:
        print("You can drive")
    else:
        print("You need a license")
else:
    print("You are too young to drive")

# Multiple conditions
username = "admin"
password = "12345"

if username == "admin" and password == "12345":
    print("Login successful")
else:
    print("Invalid credentials")

Python Loops

For Loops

# Looping through lists
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"I like {fruit}")

# Using range()
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

for i in range(1, 6):
    print(i)  # 1, 2, 3, 4, 5

for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# Looping with index
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(f"Index {index}: {color}")

# Nested loops
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")

While Loops

# Basic while loop
count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1

# User input validation
password = ""
while password != "secret":
    password = input("Enter password: ")
    if password != "secret":
        print("Incorrect password, try again")
print("Access granted!")

# Break statement
number = 1
while True:
    print(number)
    if number >= 5:
        break
    number += 1

# Continue statement
number = 0
while number < 10:
    number += 1
    if number % 2 == 0:
        continue
    print(number)  # Only prints odd numbers

Python Functions

Functions organize reusable code blocks:

# Basic function
def greet():
    print("Hello, World!")

greet()  # Call the function

# Function with parameters
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Alice")
greet_person("Bob")

# Function with multiple parameters
def add_numbers(a, b):
    result = a + b
    print(f"{a} + {b} = {result}")

add_numbers(5, 3)

# Function with return value
def multiply(x, y):
    return x * y

result = multiply(4, 5)
print(f"Result: {result}")

# Function with default parameters
def power(base, exponent=2):
    return base ** exponent

print(power(5))      # 25 (uses default exponent=2)
print(power(5, 3))   # 125 (uses provided exponent=3)

# Function with multiple return values
def calculate(a, b):
    sum_result = a + b
    difference = a - b
    product = a * b
    return sum_result, difference, product

s, d, p = calculate(10, 5)
print(f"Sum: {s}, Difference: {d}, Product: {p}")

# Docstrings
def celsius_to_fahrenheit(celsius):
    """
    Convert temperature from Celsius to Fahrenheit
    
    Args:
        celsius: Temperature in Celsius
    
    Returns:
        Temperature in Fahrenheit
    """
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

print(celsius_to_fahrenheit(25))

Working with Files in Python

Reading Files

# Reading entire file
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

# Better practice using with statement
with open("data.txt", "r") as file:
    content = file.read()
    print(content)

# Reading line by line
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

# Reading all lines into list
with open("data.txt", "r") as file:
    lines = file.readlines()
    print(lines)

Writing Files

# Writing to file (overwrites existing content)
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Python is awesome!")

# Appending to file
with open("output.txt", "a") as file:
    file.write("\nNew line appended")

# Writing multiple lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
    file.writelines(lines)

Exception Handling

Handle errors gracefully to prevent program crashes:

# Basic try-except
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Please enter a number")

# Multiple exceptions
try:
    file = open("nonexistent.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("No permission to read file")

# Try-except-else-finally
try:
    number = int(input("Enter number: "))
    result = 100 / number
except ValueError:
    print("Invalid input")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print(f"Result: {result}")
finally:
    print("Execution completed")

Object-Oriented Programming in Python

Creating Classes and Objects

# Define a class
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def bark(self):
        print(f"{self.name} says Woof!")
    
    def get_info(self):
        return f"{self.name} is {self.age} years old"

# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# Access attributes and methods
print(dog1.name)
dog1.bark()
print(dog2.get_info())

# Class with more complex example
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited ${amount}. New balance: ${self.balance}")
    
    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds")
        else:
            self.balance -= amount
            print(f"Withdrew ${amount}. New balance: ${self.balance}")
    
    def get_balance(self):
        return f"{self.owner}'s balance: ${self.balance}"

# Using the class
account = BankAccount("John Doe", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())

Conclusion and Next Steps

You've learned Python fundamentals including variables, data types, operators, control structures, functions, file handling, and object-oriented programming. These concepts form the foundation for all Python development, from web applications to data science projects.

Continue Learning:

  • Explore Python libraries like NumPy for numerical computing, Pandas for data analysis, Matplotlib for visualization
  • Learn web development with Django or Flask frameworks
  • Study machine learning with scikit-learn and TensorFlow
  • Practice with projects: build calculators, games, web scrapers, data analysis tools
  • Join Python communities on Reddit, Stack Overflow, and GitHub

Python's versatility and extensive ecosystem provide endless learning opportunities. Start building real projects to solidify your understanding and develop practical skills that employers value. The journey from beginner to proficient Python developer requires practice, persistence, and continuous learning.

Tags: