Python Basics | Variables, Operators, Conditionals, and Loops — Complete Guide

Python Basics | Variables, Operators, Conditionals, and Loops — Complete Guide

이 글의 핵심

A practical guide to Python basics: variables, operators, conditionals, loops, and PEP 8 indentation—with runnable examples.

Introduction: What makes Python syntax different?

“Why does Python feel so simple?”

Python prioritizes readability. Indentation defines blocks, and concise syntax helps you learn quickly.

This article covers:

  • Variables and types
  • Operators (arithmetic, comparison, logical)
  • Conditionals (if / elif / else)
  • Loops (for / while)
  • Indentation rules

Table of contents

  1. Variables and types
  2. Operators
  3. Conditionals
  4. Loops
  5. Indentation rules
  6. Summary

1. Variables and types

Declaring variables: no type keyword required

Python is dynamically typed. You do not declare types when assigning variables.

# Variables (no type declarations)
name = "Alice"        # str
age = 25              # int
height = 175.5        # float
is_student = True     # bool

print(name, age, height, is_student)
# Output: Alice 25 175.5 True

# Type follows the value
x = 10        # int
x = "Hello"   # now str
x = [1, 2, 3] # now list

Compared to other languages:

# Python: no type declaration
age = 25

# Java: type required
# int age = 25;

# C++: type required (or auto)
# int age = 25;
# auto age = 25;

# TypeScript: optional types
# let age: number = 25;
# let age = 25;  // inferred

Checking and converting types

print(type(name))        # <class 'str'>
print(type(age))         # <class 'int'>
print(type(height))      # <class 'float'>
print(type(is_student))  # <class 'bool'>

print(isinstance(age, int))     # True
print(isinstance(name, str))    # True
print(isinstance(height, int))  # False

x = "123"
print(type(x))        # <class 'str'>

y = int(x)
print(type(y))        # <class 'int'>
print(y)              # 123

z = float(x)
print(z)              # 123.0

# int("abc")  # ValueError

def safe_int(value, default=0):
    try:
        return int(value)
    except ValueError:
        return default

print(safe_int("123"))   # 123
print(safe_int("abc"))   # 0

Multiple assignment and unpacking

x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

a = b = c = 0
print(a, b, c)  # 0 0 0

x, y = 10, 20
print(f"before: x={x}, y={y}")

x, y = y, x  # swap in one line
print(f"after: x={x}, y={y}")

numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c)  # 1 2 3

first, *rest = [1, 2, 3, 4, 5]
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

*beginning, last = [1, 2, 3, 4, 5]
print(beginning)  # [1, 2, 3, 4]
print(last)       # 5

Naming conventions (PEP 8)

# Good (snake_case)
user_name = "Alice"
total_count = 100
MAX_SIZE = 1000
_private_var = 42

# Bad
# userName — camelCase is not idiomatic in Python
# TotalCount — PascalCase is for classes
# 2nd_value — syntax error
# my-var — syntax error

import keyword
print(keyword.kwlist)

Type hints (optional)

name: str = "Alice"
age: int = 25
height: float = 175.5
is_student: bool = True

def greet(name: str) -> str:
    return f"Hello, {name}!"

result = greet("Alice")
print(result)

# Hints are not enforced at runtime
result = greet(123)
print(result)

# pip install mypy
# mypy script.py

2. Operators

Arithmetic operators

a, b = 10, 3

print(a + b)   # 13
print(a - b)   # 7
print(a * b)   # 30
print(a / b)   # float division
print(a // b)  # 3 floor division
print(a % b)   # 1
print(a ** b)  # 1000

print(-10 // 3)  # -4
print(-10 % 3)   # 2

x = 10
x += 5
x -= 3
x *= 2
x //= 5
x **= 2
print(x)

Python vs C/Java: / always produces a float in Python 3; use // for integer division. Use ** for exponentiation.

Comparison operators

x, y = 5, 10

print(x == y)
print(x != y)
print(x < y)
print(x > y)
print(x <= y)
print(x >= y)

x = 5
print(1 < x < 10)   # chained comparison
print(x == 5 == 5)

Logical operators

a, b = True, False

print(a and b)
print(a or b)
print(not a)

age = 25
is_student = True

if age >= 18 and is_student:
    print("Adult student")

# Short-circuit
x = 0
y = 10
result = (x != 0) and (y / x > 5)
print(result)

result = (x == 0) or (y / x > 5)
print(result)

name = ""
display_name = name or "Anonymous"
print(display_name)

Membership (in, not in)

fruits = ["apple", "banana", "cherry"]

print("apple" in fruits)
print("grape" not in fruits)

text = "Hello, Python!"
print("Python" in text)

user = {"name": "Alice", "age": 25}
print("name" in user)
print("Alice" in user.values())

print(5 in range(10))

Bitwise operators

a, b = 5, 3

print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 1)
print(a >> 1)

READ = 1
WRITE = 2
EXECUTE = 4

permission = READ | WRITE
print(permission & READ)
print(permission & EXECUTE)

3. Conditionals

if

age = 20

if age >= 18:
    print("Adult")

if / else

age = 15

if age >= 18:
    print("Adult")
else:
    print("Minor")

if / elif / else

score = 85

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

print(f"Grade: {grade}")

Nested if

age = 25
has_license = True

if age >= 18:
    if has_license:
        print("Can drive")
    else:
        print("Need a license")
else:
    print("Too young")

Conditional expression (ternary)

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)

score = 85
grade = (
    "A" if score >= 90 else
    "B" if score >= 80 else
    "C" if score >= 70 else
    "F"
)

numbers = [1, 2, 3, 4, 5]
doubled = [x * 2 if x % 2 == 0 else x for x in numbers]
print(doubled)

Truthy and falsy

# Falsy: False, None, 0, 0.0, "", [], {}, ()
# Truthy: everything else

if "":
    print("won't run")

if "Hello":
    print("runs")

data = []
if not data:
    print("empty")

value = None
if value is None:
    print("None")

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True
print(a is b)  # False

4. Loops

for over iterables

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

for i in range(5):
    print(i, end=" ")
print()

for i in range(1, 11, 2):
    print(i, end=" ")
print()

for i in range(10, 0, -1):
    print(i, end=" ")
print()

for char in "Python":
    print(char, end=" ")
print()

user = {"name": "Alice", "age": 25, "city": "Seoul"}

for key in user:
    print(key, end=" ")
print()

for key, value in user.items():
    print(f"{key}: {value}")

while

count = 0
while count < 5:
    print(count, end=" ")
    count += 1
print()

while True:
    user_input = input("Type q to quit: ")
    if user_input == 'q':
        break
    print(f"You typed: {user_input}")

while True:
    age = input("Age (1-120): ")
    if age.isdigit() and 1 <= int(age) <= 120:
        age = int(age)
        break
    print("Invalid age")

print(f"Age: {age}")

break and continue

for i in range(10):
    if i == 5:
        break
    print(i, end=" ")
print()

for i in range(10):
    if i % 2 == 0:
        continue
    print(i, end=" ")
print()

for num in range(2, 20):
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num, end=" ")
print()

for/while + else (runs if no break)

for i in range(5):
    print(i, end=" ")
else:
    print("\nloop finished normally")

for i in range(5):
    if i == 3:
        break
    print(i, end=" ")
else:
    print("\nwon't run")
# 0 1 2

numbers = [1, 3, 5, 7, 9]
target = 4

for num in numbers:
    if num == target:
        print(f"found {target}")
        break
else:
    print(f"{target} not found")

Nested loops

for i in range(2, 10):
    for j in range(1, 10):
        print(f"{i} x {j} = {i*j}")
    print()

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for num in row:
        print(num, end=" ")
    print()

Breaking out of nested loops (no labels)

found = False
for i in range(5):
    for j in range(5):
        if i * j > 10:
            found = True
            break
    if found:
        break

def find_pair():
    for i in range(5):
        for j in range(5):
            if i * j > 10:
                return (i, j)
    return None

print(find_pair())

5. Indentation rules

Python uses indentation to define blocks:

if True:
    print("Hello")
    print("World")

# Wrong:
# if True:
# print("Hello")  # IndentationError

PEP 8: use 4 spaces per level; do not mix tabs and spaces.


Practice examples

Even / odd

number = int(input("Enter a number: "))

if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")

Sum 1..n

n = 10
total = 0

for i in range(1, n + 1):
    total += i

print(f"Sum 1..{n}: {total}")

Multiplication table

dan = int(input("Enter a table (1-9): "))

for i in range(1, 10):
    print(f"{dan} x {i} = {dan * i}")

Find maximum

numbers = [3, 7, 2, 9, 1, 5]
max_num = numbers[0]

for num in numbers:
    if num > max_num:
        max_num = num

print(f"Max: {max_num}")

Common mistakes

  • IndentationError: body must be indented under if/for/def.
  • range(10) is 0..9, not 1..10 — use range(1, 11) for 1..10.
  • Infinite while True: always provide a break or exit condition.
  • Concatenating str + int: use str(age) or an f-string.
  • List index: valid indices are 0 .. len-1.

Exercises

FizzBuzz (1–30)

Show answer
for i in range(1, 31):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Prime check

Show answer
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(7))
print(is_prime(10))

Reverse a list (no reversed())

Show answer
numbers = [1, 2, 3, 4, 5]

for i in range(len(numbers) - 1, -1, -1):
    print(numbers[i], end=" ")

for num in numbers[::-1]:
    print(num, end=" ")

Summary

Key takeaways

  1. Variables: assign without types; types are dynamic.
  2. Operators: arithmetic, comparison, logical, membership, bitwise.
  3. Conditionals: if / elif / else, ternary expressions.
  4. Loops: for over iterables, while for conditions, break / continue, optional else.
  5. Indentation: four spaces (PEP 8).
  6. Python idioms: truthy/falsy, chained comparisons, for-else.

Next steps