Python Basics: A Complete Beginner's Guide
Python Basics: A Complete Beginner's Guide
Welcome to the wonderful world of Python programming! This guide will teach you everything you need to know to start coding in Python, even if you've never written a line of code before.
What is Python?
Python is a high-level programming language that's easy to read and learn. It's used for:
- Website development
- Data analysis
- Artificial intelligence
- Automation
- Game development
- And much more!
Python is called "high-level" because it's designed to be human-readable, similar to English.
Setting Up Your Environment
Before we start coding, you'll need Python installed on your computer:
Installing Python:
- Go to python.org
- Click "Downloads"
- Download the latest Python version for your operating system
- Run the installer (make sure to check "Add Python to PATH")
Testing Your Installation:
Open Command Prompt (Windows) or Terminal (Mac/Linux) and type:
python --version
If you see a version number, you're ready to go!
Running Your First Python Program
Let's start with the classic "Hello, World!" program:
- Open your code editor (Notepad, VS Code, or any text editor)
- Type this code:
print("Hello, World!")
- Save the file as
hello.py - In terminal/command prompt, navigate to your file's location and run:
python hello.py
You should see: Hello, World! printed on screen!
Python Basics: Variables
Variables are like containers that store information.
Creating Variables:
# Simple variable assignment
name = "Alice"
age = 25
height = 5.7
# Print the variables
print(name)
print(age)
print(height)
Variable Rules:
- Variable names can contain letters, numbers, and underscores
- They cannot start with a number
- They are case-sensitive (
myName≠myname) - Use descriptive names (like
user_ageinstead ofa)
Python Data Types
Python has several basic data types:
1. Strings (Text)
message = "Hello"
greeting = 'Hi there!'
multiline = """This is a
multi-line string"""
2. Numbers
# Integers (whole numbers)
age = 25
count = -10
# Floats (decimal numbers)
price = 19.99
temperature = 98.6
3. Booleans (True/False)
is_student = True
is_raining = False
Working with Strings
Strings are very useful in Python:
first_name = "John"
last_name = "Doe"
# String concatenation (joining strings)
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
# Using variables in strings (f-strings)
message = f"Hello, {first_name}!"
print(message) # Output: Hello, John!
# Common string methods
text = "Hello World"
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(len(text)) # 11 (length of string)
Getting User Input
Python makes it easy to get input from users:
name = input("What's your name? ")
age = int(input("How old are you? ")) # Convert to integer
print(f"Hello {name}, you are {age} years old!")
Basic Math Operations
Python can do math for you:
# Addition, subtraction, multiplication, division
a = 10
b = 5
sum_result = a + b # 15
difference = a - b # 5
product = a * b # 50
quotient = a / b # 2.0 (float)
# More operations
remainder = a % b # 0 (modulo)
power = a ** b # 100000 (10 to the power of 5)
Conditional Statements
Control your program's flow with if/else statements:
age = int(input("How old are you? "))
if age >= 18:
print("You can vote!")
elif age >= 16:
print("You can drive!")
else:
print("You're too young!")
# Simple comparison operators
# == (equal to)
# != (not equal to)
# >, <, >=, <= (greater than, less than)
Loops
Loops let you repeat actions:
For Loop - Repeat a specific number of times:
# Print numbers 1 to 5
for i in range(1, 6):
print(i)
# Or loop through items
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")
While Loop - Repeat while a condition is true:
count = 1
while count <= 5:
print(count)
count += 1 # Same as count = count + 1
Functions
Functions are reusable blocks of code:
# Define a simple function
def greet(name):
return f"Hello, {name}!"
# Call the function
message = greet("Alice")
print(message) # Output: Hello, Alice!
# Function with multiple parameters
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
Lists (Arrays)
Lists are collections of items:
# Create a list
colors = ["red", "blue", "green"]
# Access items by index (starting at 0)
print(colors[0]) # red
print(colors[1]) # blue
# Add items to the end
colors.append("yellow")
# Change an item
colors[0] = "purple"
# Loop through a list
for color in colors:
print(color)
# Get list length
print(len(colors)) # Number of items
Working with Lists (Advanced)
numbers = [1, 2, 3, 4, 5]
# Add to the beginning
numbers.insert(0, 0)
# Remove specific item
numbers.remove(3)
# Remove by index
removed_item = numbers.pop(1) # Removes and returns item at index 1
# Sort a list
numbers.sort()
print(numbers) # [0, 1, 2, 4, 5]
Simple Project: Personal Quiz App
Here's how to put everything together in a small project:
def run_quiz():
questions = [
{"question": "What is the capital of France?", "answer": "Paris"},
{"question": "How many letters are in 'Python'?", "answer": "6"}
]
score = 0
for q in questions:
user_answer = input(q["question"] + " ")
if user_answer.lower() == q["answer"].lower():
print("Correct!")
score += 1
else:
print(f"Wrong! The answer was {q['answer']}")
print(f"You scored {score}/{len(questions)}")
run_quiz()
Tips for Learning Python
1. Practice Daily
- Try writing code every day, even if it's just 10 minutes
- Experiment with different examples
2. Use Online Resources
- Python.org - Official documentation
- Codecademy, freeCodeCamp, or Coursera for interactive learning
3. Common Mistakes to Avoid:
# Wrong way (this will cause an error)
age = input("How old are you? ")
total_age = age + 10 # Error: can't add string and number!
# Correct way
age = int(input("How old are you? "))
total_age = age + 10 # Now works correctly
# Remember to check variable names - case matters!
Name = "Alice" # Different from name = "Bob"
print(name) # Won't print anything (name is not defined)
Getting Help in Python
Using the help() function:
help(print) # Shows information about print function
help(len) # Shows information about len function
Common Error Messages:
- IndentationError: Missing or incorrect spaces/tabs
- NameError: Variable name misspelled
- TypeError: Wrong data type used
- IndexError: Accessing list index that doesn't exist
Next Steps
Now you know the basics of Python! Here's what to learn next:
- Dictionaries - Key-value pairs for more complex data storage
- File handling - Reading and writing files
- Modules - Using pre-built code libraries
- Object-oriented programming - More advanced concepts
Practice Exercises
Try these simple exercises to practice what you've learned:
- Write a program that asks for your name, age, and favorite color, then prints a personalized message.
- Create a list of 5 things you like, then loop through and print each item with "I like...".
- Make a simple calculator that adds two numbers together.
Remember: Every expert was once a beginner! Keep practicing, and don't be afraid to make mistakes - they're part of the learning process!
Happy coding!