Python Basic Syntax and Variables

Basic Syntax and Variables

Now it's time to start writing real Python code. Let's cover the most fundamental rules: indentation, comments, and variables.

Indentation Rules

Python's most distinctive feature — it uses indentation to define code blocks instead of curly braces {}.

PYTHON
# ✅ Correct: consistent indentation within a block
if 3 > 1:
    print("3 is greater than 1")
    print("This line is also inside the if block")

# ❌ Error: inconsistent indentation
if 3 > 1:
    print("3 is greater than 1")
  print("Wrong indentation!")  # IndentationError
⚠️ Golden rule: Always use 4 spaces for indentation, never tabs. Most editors (VS Code, PyCharm) will automatically convert a Tab press to 4 spaces.

Indentation applies not just to if statements, but to all code blocks — loops, functions, classes, and more:

PYTHON
# Indentation in a for loop
for i in range(3):
    print(i)          # This line is inside the loop
    print("---")      # This line is also inside the loop
print("Done")         # This line is NOT inside the loop

Comments

Comments are for human readers — Python ignores them completely.

Single-line Comments: #

PYTHON
# This is a single-line comment
print("Hello")  # Comment after code

# Multi-line comments use multiple # symbols
# This is line two
# This is line three

Multi-line String Comments: """ """ or ''' '''

Technically these are strings, but they're commonly used as multi-line comments:

PYTHON
"""
This is a multi-line comment
Useful for writing function descriptions
Or temporarily blocking out large blocks of code
"""
print("The multi-line string above won't execute")

Variables

Python variables don't need type declarations — just assign a value and you're good to go:

PYTHON
name = "Alice"    # str
age = 25          # int
height = 1.75     # float
is_student = True  # bool

Variable Naming Rules

Rule Correct ✅ Incorrect ❌
Letters, digits, underscores only my_name my-name
Cannot start with a digit var1 1var
Case-sensitive name and Name are different -
Cannot be a keyword - if, for, class

Naming Conventions (PEP 8)

PYTHON
# ✅ Variables: lowercase with underscores (snake_case)
user_name = "Alice"
total_price = 99.9
max_value = 100

# ✅ Constants: ALL_CAPS with underscores
PI = 3.14159
MAX_SIZE = 1024

# ❌ Not recommended
userName = "Alice"     # CamelCase (Java style)
UserName = "Alice"     # Looks like a class name

Multiple Variable Assignment

Python lets you assign multiple variables in one line:

PYTHON
# Assign multiple values at once
a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# Swap two variables (other languages need a temporary variable)
x, y = 10, 20
x, y = y, x
print(x, y)  # 20 10

# Assign the same value to multiple variables
m = n = p = 0
print(m, n, p)  # 0 0 0

The type() Function

Use type() to check a variable's type:

PYTHON
print(type(10))       # <class 'int'>
print(type(3.14))     # <class 'float'>
print(type("Hello"))  # <class 'str'>
print(type(True))     # <class 'bool'>

# Variables can change type when reassigned (dynamic typing)
x = 10
print(type(x))  # <class 'int'>
x = "Hello"
print(type(x))  # <class 'str'>  ← type changed

Common Errors

PYTHON
# IndentationError: wrong indentation
print("Too much indentation")
  print("This line has an extra space")  # ❌

# NameError: variable not defined
print(z)  # ❌ z was never assigned

# SyntaxError: invalid syntax
print("Hello)  # ❌ quotes not closed

📖 Section Summary

📝 Homework

  1. Write code that defines three variables: city (city name), year (year), score (score 88.5), and print them using print()
  2. Swap two variables a = 5 and b = 10 so that a becomes 10 and b becomes 5
  3. Use type() to check the types of True, "123", and 3.0
  4. Intentionally write code with an indentation error, see what error Python throws, and take a screenshot of the error message
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏