Python has become one of the world's most popular programming languages for good reason: it's powerful yet easy to learn, with clean syntax that reads almost like English. This guide will take you from complete beginner to writing your first functional Python programs in a single sitting.
Setting Up Your Environment
Before you start coding, you need a few tools:
-
Install Python: Visit python.org and download the latest version (3.11+ recommended). The installer will guide you through the process.
-
Choose an Editor: While you can use any text editor, a dedicated code editor makes learning easier:
- VS Code: Free, lightweight, and works on all platforms
- PyCharm: More robust features, with a free Community Edition
- Thonny: Designed specifically for beginners
-
Verify Installation: Open a command prompt or terminal and type:
python --version
You should see the version number displayed.
Your First Python Program
Let's start with the classic "Hello, World!" program:
- Open your code editor
- Create a new file named hello.py
- Type the following code:
print("Hello, World!")
- Save the file
- Run it (in VS Code, press F5 or right-click and select "Run Python File")
You should see "Hello, World!" appear in your console. Congratulations—you've written your first Python program!
Python Fundamentals
Variables and Data Types
Variables store data. In Python, you don't need to declare the type:
name = "Alice" # String (text) age = 25 # Integer (whole number) height = 5.7 # Float (decimal number) is_student = True # Boolean (True/False)
Basic Operations
Python supports all standard arithmetic operations:
addition = 5 + 3 # 8 subtraction = 10 - 4 # 6 multiplication = 6 * 7 # 42 division = 20 / 4 # 5.0 (always returns a float) integer_division = 20 // 4 # 5 (returns an integer) remainder = 20 % 3 # 2 (modulo - returns the remainder) exponent = 2 ** 3 # 8 (2 raised to the power of 3)
Strings
Text in Python is handled as strings:
# Creating strings first_name = "John" last_name = 'Doe' # Single or double quotes work # Concatenation (joining strings) full_name = first_name + " " + last_name # "John Doe" # String methods uppercase = full_name.upper() # "JOHN DOE" lowercase = full_name.lower() # "john doe"
User Input
Getting input from the user:
name = input("What is your name? ") print("Hello, " + name + "!")
Control Flow
If Statements
Decision-making in code:
age = 18 if age < 13: print("Child") elif age < 18: print("Teenager") else: print("Adult")
Loops
Repeating code:
# For loop (iterate a specific number of times) for i in range(5): # range(5) gives 0, 1, 2, 3, 4 print(i) # While loop (continue until a condition is met) count = 0 while count < 5: print(count) count += 1 # Shorthand for count = count + 1
Lists
Lists store collections of items:
# Creating a list fruits = ["apple", "banana", "cherry"] # Accessing items (indexing starts at 0) first_fruit = fruits[0] # "apple" # Modifying items fruits[1] = "blueberry" # Changes "banana" to "blueberry" # Adding items fruits.append("dragonfruit") # Adds to the end # List length num_fruits = len(fruits) # 4
Your First Practical Program
Let's create a simple calculator:
# Simple calculator # Get user input num1 = float(input("Enter first number: ")) operation = input("Enter operation (+, -, *, /): ") num2 = float(input("Enter second number: ")) # Perform calculation result = 0 if operation == "+": result = num1 + num2 elif operation == "-": result = num1 - num2 elif operation == "*": result = num1 * num2 elif operation == "/": if num2 != 0: # Avoid division by zero result = num1 / num2 else: print("Error: Cannot divide by zero") exit() else: print("Invalid operation") exit() # Display result print(f"{num1} {operation} {num2} = {result}")
Save this as calculator.py and run it. You've just created a functional calculator program!
Functions
Functions allow you to reuse code:
def greet(name): """This function displays a greeting message.""" return "Hello, " + name + "!" # Calling the function message = greet("Python Beginner") print(message) # "Hello, Python Beginner!"
Putting It All Together: A Number Guessing Game
Let's create a more complex program using what you've learned:
import random def number_guessing_game(): """Simple number guessing game""" # Generate a random number between 1 and 100 secret_number = random.randint(1, 100) attempts = 0 max_attempts = 10 print("Welcome to the Number Guessing Game!") print(f"I'm thinking of a number between 1 and 100. You have {max_attempts} attempts.") while attempts < max_attempts: # Get user's guess try: guess = int(input("Enter your guess: ")) except ValueError: print("Please enter a valid number.") continue attempts += 1 # Check the guess if guess < secret_number: print("Too low!") elif guess > secret_number: print("Too high!") else: print(f"Congratulations! You guessed the number in {attempts} attempts!") return # Show remaining attempts remaining = max_attempts - attempts if remaining > 0: print(f"You have {remaining} attempts left.") print(f"Game over! The number was {secret_number}.") # Run the game number_guessing_game()
Save this as guess_game.py and run it to play!
Next Steps
Congratulations! You've learned the core concepts of Python programming. To continue your journey:
- Practice: The best way to learn is by writing code. Try modifying the programs you've created.
- Explore Python Libraries: Python's strength comes from its vast ecosystem of libraries.
- Take on Projects: Start with simple projects like a to-do list or a quiz application.
- Join Communities: Websites like Stack Overflow, Reddit's r/learnpython, and GitHub have active Python communities.
Remember that programming is a skill that improves with practice. Even experienced developers constantly learn new techniques and approaches. Enjoy your coding journey!