Thuta Learning
Python
BasicProgrammingBeginner

Python Intro

PythonLesson 220 min

What you'll walk away with

  • Say who created Python and how Python 2 and Python 3 differ
  • Describe the path from source code to bytecode to the Python virtual machine
  • Explain dynamic typing: values have types, names do not
  • Recognise why storing a version number as a float goes wrong

Explain it simply

Explain it simply

Python was created by Guido van Rossum and first released in 1991. His goal was code that is easy to read, not just easy to write, because programmers spend far more time reading code than writing it.

"High-level" means you think about your problem instead of managing memory or CPU instructions. Reading a line of text in C means worrying about buffer sizes; in Python you write line = input() and move on.

Problem → Why → Solution

The problem: 3.10 turns into 3.1

You want a report to show a Python version, so you write version = 3.10. Running it prints "Python 3.1", which is a release from 2009. No error appears; the data is simply wrong, which is what makes this kind of bug hard to spot.

report.py
version = 3.10           # looks like a version, but it is a float
print(f"Running on Python {version}")   # Running on Python 3.1

Why does this happen?

Without quotes, Python reads 3.10 as a decimal number (a float), and mathematically 3.10 and 3.1 are the same value, so the trailing zero disappears. In Python the name does not decide the type; the value you write does. Data that must stay exactly as written, like a version, belongs in a string such as "3.10".

Core concept: how a Python program runs

When you type python hello.py, two things happen. First, the interpreter reads the whole file and translates it into bytecode, a list of simple instructions. Grammar mistakes such as a missing bracket or colon are caught here as a SyntaxError, before a single line runs. Second, the Python virtual machine executes that bytecode one instruction at a time. Problems such as using a name that does not exist only show up during this second phase.

The most common interpreter is CPython, the one you download from python.org. For modules you import, it caches the bytecode as .pyc files in a __pycache__ folder so they load faster next time. You never edit that folder, and it does not belong in git.

Python is dynamically typed. After age = 25, the name age refers to an int object; write age = "twenty" later and the same name now refers to a str object. Types belong to values, not to names. Python is still strict about mixing types, though: "Age: " + 25 raises a TypeError instead of quietly converting the number the way JavaScript does. That is why Python is described as dynamically but strongly typed.

Python marks blocks with indentation (leading spaces) instead of braces, and it ships with a large standard library, a philosophy often called "batteries included". Python 3.0 came out in 2008 and is not fully compatible with Python 2, which stopped receiving support in 2020.

The cost of this flexibility is speed. Because the virtual machine executes one instruction at a time, a pure Python loop over millions of numbers is much slower than the same loop in C. In practice, libraries such as NumPy do the heavy number crunching in compiled code, so Python acts as the layer that directs the work and speed is rarely the bottleneck.

Mental model: from source to output
  1. hello.py source code
  2. Compiled to bytecode: syntax check
  3. The virtual machine executes it
  4. Output, or a runtime error

A SyntaxError means no output at all; NameError and TypeError only appear when their line is reached.

General pattern: values, types and a block

python
name = "text"          # str
count = 10             # int
ratio = 0.5            # float
flag = True            # bool

for item in collection:
    print(item)        # indented = inside the loop

There is no declaration step: assigning with = creates the variable, and the value decides its type. Lines indented under a line ending in a colon (:) form a block.

Example: Python's traits in action

Save this program as intro.py and run it. Notice the version stored as a string, a side-by-side comparison with the float version, type() asking each value what it is, and a for loop whose body is marked only by indentation.

intro.py
print("Hello, World!")

name = "Python"
version = "3.13"          # a string keeps the text exactly as written
is_readable = True

print(f"{name} {version} is readable: {is_readable}")
print(3.10, "vs", "3.10")  # the float loses its trailing zero
print(type(version).__name__, type(3.10).__name__)

features = ["Easy to read", "Runs on Windows, macOS, Linux", "Large standard library"]
for feature in features:
    print(f"- {feature}")

Code breakdown

  1. Line 4version = "3.13" # a string keeps the text exactly as written

    The quotes make it a str, so every character is kept exactly. Written without quotes, version = 3.11 would be a float, and a version such as 3.10 would turn into 3.1.

  2. Line 7print(f"{name} {version} is readable: {is_readable}")

    The f-string replaces each {} with the variable's value. True is a bool, and inside the f-string it is shown as the text True.

  3. Line 8print(3.10, "vs", "3.10") # the float loses its trailing zero

    The float 3.10 prints as 3.1 while the string "3.10" is unchanged, which shows the bug from the problem section directly.

  4. Line 9print(type(version).__name__, type(3.10).__name__)

    type() returns a value's type and .__name__ takes its short name, giving str and float. Printing type(version) directly would show <class 'str'>.

  5. Lines 12-13for feature in features:

    The for loop puts each list item into feature in turn and runs the indented print() once per item.

You should see
Hello, World!
Python 3.13 is readable: True
3.1 vs 3.10
str float
- Easy to read
- Runs on Windows, macOS, Linux
- Large standard library

Dynamic, but strongly typed

In the code below the same name, score, is allowed to move from an int to a str. Adding a str and an int with + is refused with a TypeError, though. Converting with str() or using an f-string is the correct fix.

strong_typing.py
score = 90
print(type(score).__name__)      # int
score = "ninety"
print(type(score).__name__)      # str

age = 25
try:
    print("Age: " + age)
except TypeError as err:
    print("TypeError:", err)
print("Age: " + str(age))
print(f"Age: {age}")

How to recognise Python 2 code

Old Stack Overflow answers and older books still contain a lot of Python 2 code. Pasting it into Python 3 either raises an error or, worse, silently gives a different answer. The table lists the differences you will meet most often; if you see the left-hand form, the code is outdated.

Python 2Python 3
print "hi" (a statement)print("hi") (a function)
7 / 2 gives 37 / 2 gives 3.5; 7 // 2 gives 3
raw_input() reads textinput() reads text
Unicode text needs u"..."Every str is Unicode already

In real projects

Where this shows up in real projects

Teams pick Python mainly because it is easy to read: code reviews go faster and new developers understand existing code sooner. The standard library already covers files, JSON, dates, CSV, HTTP and SQLite, so an automation script often needs no extra packages at all.

The price of dynamic typing is that type mistakes surface only when the code runs. Larger projects make up for this with type hints (def total(price: float) -> float), checkers such as mypy, and unit tests. When deploying to a server, teams keep the Python version the same on development machines and in production, checking it with python --version and writing it down in the project's documentation.

Common mistakes

Common mistakes

1. Thinking Python has no types

Not declaring types is not the same as having no types. "5" + 5 raises a TypeError, and "5" * 3 gives "555". What an operator does depends on the value's type, so check uncertain values with type().

2. Mixing up the language and its libraries

pandas.read_csv() and Django's models.Model are not part of Python; they come from separately installed packages with their own versions. When something fails, search the documentation for that package and version, not just "Python".

3. Storing a version as a float

3.10 becomes 3.1, and comparing 3.9 < 3.10 as floats gives False. Keep versions as a string like "3.10" or a tuple like (3, 10), and read the running Python's version from sys.version_info.

Best practices

Best practices

  • Before following a tutorial, check that it targets Python 3 by looking for print() with parentheses.
  • When unsure of a value's type, ask with print(type(value)) instead of guessing.
  • Use an f-string rather than + to print text mixed with numbers; no conversion is needed.
  • Record the Python version each project uses in its README.

Mini challenge

Mini challenge: a language fact card

Write a program that prints a fact card about Python. Store each value with the right type and include one calculation.

  • Store the language name (str), the first release year 1991 (int) and the current year (int)
  • Store the version "3.13" as a string
  • Calculate how many years Python has existed
  • Print a list of three use cases with a for loop
fact_card.py
language = "Python"
# TODO: first_release (int) and this_year (int)
# TODO: version as a string, so "3.10"-style values stay intact
# TODO: a list with three things Python is used for

# TODO: print "<language> <version>"
# TODO: print how many years have passed since the first release
# TODO: loop over the list and print each use case with "- " in front

Expected: With this_year = 2026: Python 3.13 First released 35 years ago, in 1991. Used for: - web back ends - data analysis - automation scripts

Show hint

The number of years is this_year - first_release. Remember to indent the loop body by four spaces.

Show solution
fact_card.py
language = "Python"
first_release = 1991
this_year = 2026
version = "3.13"
uses = ["web back ends", "data analysis", "automation scripts"]

print(f"{language} {version}")
age = this_year - first_release
print(f"First released {age} years ago, in {first_release}.")
print("Used for:")
for use in uses:
    print(f"- {use}")

Quick quiz 1 / 3

What does print(3.10) print?

Quick quiz 2 / 3

Line 5 of a file has a missing closing bracket (a SyntaxError). Line 1 is print("start"). What happens when you run it?

Quick quiz 3 / 3

You write x = 5 and later x = "five". Which statement is true?

What to remember

  • Python was first released by Guido van Rossum in 1991; today you use Python 3.
  • The interpreter compiles source to bytecode and the virtual machine runs it: SyntaxError comes before running, NameError and TypeError during.
  • Types belong to values, not names, yet Python refuses to mix incompatible types silently.
  • Keep data such as version numbers in strings, not floats.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Intro | Thuta Learning