C
Python/Intro/Lesson 02

Introduction to Python

30 min·theory
This chapter
1/7
Python

Introduction to Python

🎯 By the end of this lesson

After reading this lesson, you will be able to confidently do the following three things.

  • ✅ Explain why Python became the standard language for AI and data
  • ✅ Set up a venv + requirements.txt environment for Python 3.x
  • ✅ Use the four built-in functions: print / input / type / dir

Keep the learning goals as a checklist and close the lesson once you can answer all of them.

Python Syntax — A 5-Minute Summary

Python is a highly readable programming language. The key idea is that it is 'almost as concise as natural language.'

For each example, follow this order: code → output → explanation.



0. Python Basic Data Types — One Table

Every Python program is built from 'values'. Memorize these six most common types first.

TypeNotationExampleWhen to use
intinteger28, -3, 0The default for numbers. Used almost everywhere.
floatreal number3.14, 175.5Numbers with decimal points.
strstring"Hong", 'hi'Text. Quotes are required.
booltrue/falseTrue, FalseThe result of a condition. Note the capital letter.
listlist[1, 2, 3]An ordered collection. Mutable.
dictdictionary{"name": "Hong"}key→value mapping. Look up by name.

Bottom line: At first, you only need to know these four: int, float, str, and bool. list and dict are covered in the data structures section.

The key difference from Java — Python has no type declarations:

java
// Java — type declaration required
int age = 28;
String name = "Hong";
python
# Python — type is inferred from the value
age = 28        # automatically recognized as int
name = "Hong"   # automatically recognized as str

This is secret #1 behind 'Python being concise.'


1. Variables — Storing a Value Under a Name

python
name = "Hong Gil-dong"  # wrapped in quotes → string
age = 28                # no quotes → integer (int)
height = 175.5          # decimal point → float
student = True          # true/false → bool

= means 'assign the right-hand value to the left-hand variable.' It is not a mathematical equals sign.
Difference from Java: No type declaration like String name — Python figures it out automatically.


2. Output print() — Displaying to the Screen

python
print("Hello!")
print("Name:", name)
print(f"{name} is {age} years old")

Output:

code
Hello!
Name: Hong Gil-dong
Hong Gil-dong is 28 years old

f"..." is an f-string — a modern way to embed variables inside {} (Python 3.6+).


3. Input input() — Receiving Input from the User

python
name = input("Your name? ")  # user types and presses Enter
print(f"Nice to meet you, {name}!")

Terminal interaction:

code
Your name? Hong Gil-dong      ← user input
Nice to meet you, Hong Gil-dong!  ← program output

⚠️ input() always returns a string. If you need a number, convert it: int(input(...)).


4. Colon : + Indentation — Python's 'Block' Syntax

Before diving into conditionals, loops, and functions, you need to understand Python's unique block syntax.

Java uses curly braces { }, Python uses a colon : + 4 spaces of indentation:

java
// Java
if (condition) {
    System.out.println("true");
}
python
# Python
if condition:         # ← colon required
    print("true")     # ← 4-space indent = inside the block

A colon is required after these keywords:

python
if condition:          # if / elif / else
for i in range(5):     # for / while
def greet():           # def (function)
class Person:          # class
try:                   # try / except / finally

Forgetting the colon causes a SyntaxError:

python
if score >= 90    # ❌ missing colon → SyntaxError: expected ':'
    print("A")

The colon is also used to denote 'left:right pairs':

python
person = {"name": "Hong"}   # dict — key:value
numbers[1:4]                 # slicing — start:end
def add(a: int) -> int:      # type hint — variable:type

→ A colon signals either 'block starts on the next line' or 'a left:right pair.'


5. Conditionals if·elif·else — Branching

python
score = 85

if score >= 90:
    print("A")
elif score >= 80:        # else if = elif (shortened)
    print("B")
else:
    print("C")

Output: B (85 is ≥ 80, so the second branch is taken)

Key rules:

  • No curly braces { } — blocks are defined by 4-space indentation
  • A : colon is required at the end of the if line
  • == (equals) / != (not equals) / >= (greater than or equal) / <= (less than or equal)

6. Loops for·while

python
# range — iterate over numbers
for i in range(1, 6):    # 1, 2, 3, 4, 5 (6 is excluded!)
    print(i)

Output: 1

2

3

4

5 (one per line)

python
# iterating over a list
fruits = ["apple", "pear", "persimmon"]
for fruit in fruits:
    print(f"one bite of {fruit}")

Output:

code
one bite of apple
one bite of pear
one bite of persimmon

⚠️ range(1, 6) goes from 1 up to but not including 6 (i.e., up to 5). This is a common Python gotcha.


7. Functions def — Reusing Code

python
def greet(name):               # def function_name(parameter):
    return f"Hello {name}"     # return the result

# calling the function
message = greet("Hong Gil-dong")
print(message)

Output: Hello Hong Gil-dong

Syntax breakdown:

  • def = short for 'define'
  • (name) = the value to receive (parameter). Multiple: (name, age)
  • return = sends the result back to the caller. If omitted, returns None
  • Call a function with function_name(value) — forgetting () refers to the function itself

8. Four Data Structures

python
# ─ list — ordered, mutable
numbers = [1, 2, 3]
numbers.append(4)        # add to the end
print(numbers)

Output: [1, 2, 3, 4]

python
# ─ tuple — ordered, immutable (locked)
coords = (37.5, 127.0)
print(coords[0])          # first element = 37.5

Output: 37.5

python
# ─ dictionary (dict) — key:value
person = {"name": "Hong Gil-dong", "age": 28}
print(person["name"])
person["job"] = "developer"  # add a new key
print(person)

Output:

code
Hong Gil-dong
{'name': 'Hong Gil-dong', 'age': 28, 'job': 'developer'}
python
# ─ set — duplicates removed automatically
tags = {"python", "ai", "python"}
print(tags)

Output: {'python', 'ai'} (duplicate 'python' removed)

When to use what:

  • Order matters + mutable → list
  • Order matters + immutable → tuple
  • Look up by name → dict
  • Remove duplicates → set

9. Classes class — Creating Objects

python
class Person:
    def __init__(self, name, age):    # constructor — called when the object is created
        self.name = name               # self = the object itself
        self.age = age

    def greet(self):
        print(f"Hi, I'm {self.name} ({self.age} years old)")

# create an object and call a method
hong = Person("Hong Gil-dong", 28)
hong.greet()

Output: Hi, I'm Hong Gil-dong (28 years old)

Key concepts:

  • __init__ = called automatically when the object is first created (like a constructor in Java)
  • self = the object itself (like this in Java). Required as the first parameter of every method
  • Calling Person("Hong Gil-dong", 28) automatically runs __init__

One-Line Summary

PatternKeyword
Variable= (no type)
Outputprint()
Inputinput() (strings only)
Branchingif·elif·else (indentation + :)
Loopfor in range() / for in list
Functiondef name(param): return value
Datalist·tuple·dict·set
Objectclass + __init__ + self

These 8 patterns cover 90% of Python.

🐍 Try It Out — Python Introduction

Try running the concepts above as actual code. The fastest way to learn is to change values and observe the behavior yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Prompting Your AI Like This

Once you understand the concepts in this lesson, you can give your AI specific instructions. Instead of a vague 'fix this,' use vocabulary-driven requests — that is the starting point for saving tokens.

  • 'Apply the Python introduction concepts to this Python code'
  • 'Add type hints and pytest unit tests to this code'
  • 'Check this code for PEP 8 violations related to Python introduction concepts'

Why This Reduces Tokens

Without knowing the concepts, you have to ask 'what does that mean?' after each AI response. Those follow-up questions consume tokens. Master the concepts once and the conversation ends in one round.

Read this first: Mastering Python
Up next: Data Types
What is Python? - Python