6 min read
Python Basics & Syntax
Learn how to write Python code step by step
What You'll Learn
- How Python code works
- Print messages on screen
- Do basic math
- Understanding errors
Your First Line of Code
Let's print text on the screen:
code.py
print("Hello World")Try it: Type this and run it. You should see:
Hello World
Printing Different Things
Text (use quotes):
code.py
print("I love Python")
print('Python is fun')Numbers (no quotes):
code.py
print(42)
print(3.14)Multiple things at once:
code.py
print("My age is", 25)
print("I scored", 95, "points")Basic Math in Python
Python can work like a calculator:
code.py
# Addition
print(5 + 3) # 8
# Subtraction
print(10 - 4) # 6
# Multiplication
print(6 * 7) # 42
# Division
print(20 / 4) # 5.0
# Power
print(2 ** 3) # 8 (2 × 2 × 2)Comments (Notes to Yourself)
Comments are ignored by Python. They're just notes for humans:
code.py
# This is a comment
print("This runs") # Comment after code
# Use comments to explain your code
# or temporarily disable codeStoring Values in Variables
Variables are like boxes that hold information:
code.py
name = "Sarah"
age = 25
height = 5.6
print(name)
print(age)
print(height)Using variables:
code.py
price = 100
quantity = 3
total = price * quantity
print("Total cost:", total)
# Output: Total cost: 300Variable Naming Rules
Good names:
code.py
user_name = "John"
total_price = 500
age = 30Bad names (will cause errors):
code.py
user-name = "John" # No dashes!
2fast = 100 # Can't start with number!
my name = "Sarah" # No spaces!Tips:
- Use lowercase letters
- Use underscores for spaces
- Make names meaningful
total_priceis better thantp
Working with Text
code.py
# Store text
greeting = "Hello"
name = "World"
# Combine text
message = greeting + " " + name
print(message)
# Output: Hello World
# Repeat text
laugh = "ha" * 3
print(laugh)
# Output: hahahaSimple Input from User
Ask the user for information:
code.py
name = input("What is your name? ")
print("Hello", name)When you run this:
- Python asks: "What is your name?"
- You type your name
- Python says hello to you
Understanding Errors
Errors are normal! Everyone gets them.
Common error:
code.py
print("Hello)Error message:
SyntaxError: unterminated string
What it means: You forgot the closing quote!
Fixed:
code.py
print("Hello")Practice Examples
Example 1: Simple calculator
code.py
num1 = 10
num2 = 5
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)Example 2: Personal intro
code.py
name = "Alex"
age = 28
city = "New York"
print("My name is", name)
print("I am", age, "years old")
print("I live in", city)Quick Reference
Print:
code.py
print("text")
print(number)Math:
code.py
+ # Add
- # Subtract
* # Multiply
/ # Divide
** # PowerVariables:
code.py
variable_name = valueComments:
code.py
# This is a commentWhat's Next?
Great job! You know the basics. Next, we'll learn about different types of data in Python.