What is Python Basics
Learn the basics of Python in this lesson: explore what Python is, how to understand its core concepts, and apply them in a hands-on exercise. Designed for developers starting step by step.
Focus: what is python? understanding the basics
Have you ever felt overwhelmed by the sheer number of programming languages, each promising to be the next big thing? You're building a solid foundation, and you need a language that is both powerful and easy to read. That's exactly why Python exists — it was designed to be clear, concise, and readable, letting you focus on solving the problem, not on deciphering cryptic syntax.
The problem this lesson solves
Many new developers jump straight into writing code without first understanding what makes a language tick. When you start with Python, you might wonder: is it a scripting language? A compiled one? Why does it feel different from C or Java? Without a clear mental model, you end up confused about indentation, variable types, and how your Python code actually gets executed. This confusion leads to frustration, subtle bugs, and the feeling that you're memorizing rules instead of thinking like a programmer.
This lesson cuts through that noise. You will learn what Python fundamentally is — a high-level, interpreted, dynamically-typed language — and how that shapes the way you write and run your programs. By the end, you'll understand why Python enforces indentation, why you don't declare variable types, and how your .py file becomes a running program.
Core concept / mental model
Think of Python as a translator between you and your computer. You write instructions in a human-friendly language (Python code), and a program called the interpreter reads your instructions line by line and translates them into machine code on the fly. This is different from compiled languages like C++ where a compiler translates the entire program before execution.
- High-level means Python abstracts away most of the complex hardware details (like memory management). You don't manage pointers or allocate memory — Python handles that for you.
- Interpreted means you can run code immediately, without an explicit compilation step. This makes Python interactive and great for experimentation.
- Dynamically-typed means you don't have to declare the data type of a variable — Python infers it at runtime based on the value you assign.
Think of the interpreter as a chef who reads your recipe (Python code) and cooks the dish step by step, checking each ingredient as it goes. If something is wrong, the chef stops at that step — you get an error right where the problem is.
Defining "variable" in Python
A variable is a named container that stores a value. You create a variable simply by assigning it a value with =. Python figures out the type automatically.
# Example of variable assignment in Python
message = "Hello, Python Learner!"
pi = 3.14159
count = 100
This code creates three variables: message (a string), pi (a float), and count (an integer). You can verify their types with the type() function.
How it works step by step
-
Write the code. You create a file with the
.pyextension (e.g.,hello.py) using any text editor. -
Run the interpreter. You pass your file to the Python interpreter by typing
python hello.pyin your terminal (orpython3 hello.pyon some systems). -
Lexing & Parsing. The interpreter reads every character, groups them into tokens (words, numbers, operators), and checks the grammar. If you miss a colon or have wrong indentation, the interpreter stops here and reports a
SyntaxError. -
Compilation to bytecode. Python compiles your code into a lower-level intermediate representation called bytecode (stored in
.pycfiles inside__pycache__). This step makes execution faster. -
Execution by the Python Virtual Machine (PVM). The PVM reads the bytecode and executes instructions one by one. This is where variables are created, loops run, and functions called.
-
Output or Error. If everything works, you see the result. If the PVM encounters a runtime error (like dividing by zero), it stops and shows a traceback.
# Step-by-step mental flow
# 1. Write this in a file named 'my_first.py'
print("Welcome to Python!")
result = 10 + 5
print(f"The answer is {result}")
You run: python my_first.py
The interpreter reads line 1, sees print(...) is a function call, executes it (prints "Welcome to Python!"). Then line 2, sees assignment, creates variable result with value 15. Then line 3, executes the f-string interpolation and prints the result.
Hands-on walkthrough
Let's put this into practice. You'll write, run, and debug a simple Python script. This will cement the mental model of how Python goes from code to output.
Exercise 1: Your first Python script
Create a file called welcome_message.py in your project folder and paste the following code:
# File: welcome_message.py
# This script prints a greeting and does some calculation
name = "Jane"
year = 2025
print(f"Hello, {name}! Welcome to the year {year}.")
print("Next year will be", year + 1)
Run it:
$ python welcome_message.py
Expected output:
Hello, Jane! Welcome to the year 2025.
Next year will be 2026
Notice how we used dynamic typing: we assigned a string to name and an integer to year without declaring types. Python handled it automatically.
Exercise 2: Understand dynamic typing
Variables can even change type! This is perfectly legal in Python (though often not recommended for readability).
# dynamic_typing_demo.py
value = 10 # value is an integer
type(value) # returns <class 'int'>
value = "ten" # value is now a string
type(value) # returns <class 'str'>
print(value) # prints "ten"
Exercise 3: Encounter a syntax error
Try this intentionally broken code to see how Python's interpreter catches issues:
# broken.py
print("Hello")
print("Indented incorrectly") # extra space at start
Run it: python broken.py
Output (common error):
File "broken.py", line 2
print("Indented incorrectly")
IndentationError: unexpected indent
The interpreter stopped during parsing, before executing any code. Python uses indentation to define code blocks — you cannot add arbitrary spaces or tabs. This is a key characteristic of the language.
Compare options / when to choose what
How does Python compare to other beginner-friendly languages? This table summarizes the most relevant differences.
| Feature | Python | JavaScript | Java |
|---|---|---|---|
| Typing | Dynamic | Dynamic | Static |
| Execution | Interpreted (with bytecode) | Interpreted in browser | Compiled to bytecode (JVM) |
| Readability | Significant whitespace (indentation) | Curly braces + semicolons optional | Curly braces + semicolons required |
| Learning curve | Gentle — reads like pseudocode | Moderate — many quirks | Steeper — lots of boilerplate |
| Role | General-purpose scripting, data science, backend | Web frontend, Node.js backend | Enterprise, Android, large systems |
When to choose Python: - When you want to prototype quickly or experiment without heavy setup. - For data analysis, machine learning, or automation tasks. - For web backend (Django, Flask) or scripting. - When you need code that is easy for non-programmers to read.
When to avoid Python: - For mobile app development (though frameworks exist). - For high-performance graphics or system-level tasks where C/C++ is necessary. - When strict typing is essential for large team projects (Java, TypeScript).
Troubleshooting & edge cases
Even with Python's simplicity, beginners hit common roadblocks. Here's how to handle them.
1. "command not found: python"
This means Python isn't in your system's PATH. On macOS/Linux, try python3 instead. On Windows, you may need to reinstall and check "Add Python to PATH". Verify installation with:
python --version
# or
python3 --version
2. IndentationError: unexpected indent
Python is strict about consistent indentation. Use 4 spaces per level — never mix tabs and spaces. Most modern editors (VS Code, PyCharm) will convert tabs to spaces automatically. Keep your file consistent.
3. NameError: name 'variable' is not defined
This happens when you try to use a variable before assigning it, or you misspelled the name. Check the variable name and ensure it's assigned before use.
# WRONG
print(total) # NameError: name 'total' is not defined
total = 42
# CORRECT
total = 42
print(total) # prints 42
4. Dynamic typing gotchas
Because types can change, you might accidentally overwrite a variable with a different type, causing confusing behavior. Be mindful of variable reuse.
# Tricky dynamic typing
count = 10
count = "ten" # now count is a string — any arithmetic will fail
# count + 5 would raise TypeError: can only concatenate str (not "int") to str
Pro tip: Use descriptive variable names and avoid reusing the same variable for different purposes.
What you learned & what's next
You now understand the core nature of Python: a high-level, interpreted, dynamically-typed language that uses indentation to define code blocks. You have seen how the Python interpreter processes your .py file through parsing, bytecode compilation, and execution by the PVM. You've written and run a script, observed dynamic typing in action, and learned to diagnose syntax errors.
You met all learning objectives for this lesson: - ✅ Explain the core idea behind What is Python? Understanding the basics - ✅ Complete a practical exercise for What is Python? Understanding the basics
This foundation is critical because in the next lesson you'll dive deeper into Python syntax and data types — variables, numbers, strings, lists, and conditionals. You'll build on what you just learned to write more complex, interactive programs.
Key points to remember: - Python is interpreted and dynamically typed — code runs immediately and types are inferred. - Indentation matters: it's part of the syntax, not just formatting. - Variables are created by assignment; no declaration needed. - The interpreter stops at the first error — fix errors from top to bottom. - Python bytecode is an intermediate step that speeds up execution.
Keep experimenting: open your editor, write a short script that prints your favorite quote using a variable for the author and another for the quote. See how Python handles different types together.
Practice recap
Now it's your turn. Create a new Python file called hello_you.py that asks the user for their name using input() and prints a personalized greeting. Experiment with changing the variable to hold a number and see if Python complains. This will reinforce dynamic typing and input handling before the next lesson on data types.
Common mistakes
- Mixing tabs and spaces for indentation leads to an 'unexpected indent' error — always use 4 spaces.
- Forgetting to use
print()(or usingprintwith parenthesis incorrectly) will cause a SyntaxError becauseprintis a function in Python 3. - Assuming variable types are fixed — reassigning a string to a variable that was a number is allowed but can cause later runtime errors.
- Running
pythoncommand when onlypython3is available (common on macOS/Linux). Always check your alias or usepython3explicitly. - Writing code in a file that isn't saved with a
.pyextension — the interpreter expects a.pyfile but will work with any file that contains valid Python code.
Variations
- Instead of the standard CPython interpreter, you can use PyPy (a JIT-compiled Python implementation) for performance-critical scripting.
- For interactive learning, many beginners start with Jupyter Notebook (.ipynb) which runs Python in a cell-based environment — ideal for data exploration.
- While this lesson focuses on Python 3, Python 2 is still legacy in some systems — never write new code in Python 2.
Real-world use cases
- Automating file renaming and data extraction — write a short Python script to move and rename hundreds of files based on date or content.
- Creating a simple web server or API prototype — Flask/Django apps start as one
.pyfile then grow. - Data analysis — use Python scripts to clean CSV files, compute statistics, and output reports for business decisions.
Key takeaways
- Python is high-level, interpreted, and dynamically-typed — meaning you write less code and get instant feedback.
- Indentation defines code blocks; 4 spaces per level is the standard.
- Variables are created upon assignment and can change type over time.
- The Python pipeline: source code → lex/parse → bytecode → PVM execution → output.
- SyntaxErrors stop execution before any code runs; NameErrors stop the program mid-execution.
- Always save files with .py and ensure your terminal uses
pythonorpython3correctly.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.