Recommended
Python Basics — Timed Test (3 questions)
No account needed. Answers and explanations arrive when you submit.
What this topic tests
The mix every Python Basics set is built to, and the questions published against it so far. Nothing here is hidden before you start.
| Level | Target share | Published |
|---|---|---|
| Easy | 40% | 1 |
| Medium | 40% | 2 |
| Hard | 20% | 0 |
| Total | 3 |
Python Basics — the theory
Python is a widely used, general-purpose programming language known for readable syntax and broad applicability across web development, data analysis, automation, and more.
Syntax fundamentals. Python uses indentation (whitespace) to define code blocks, rather than curly braces or explicit keywords used by many other languages — a design choice that makes correctly-formatted Python code inherently readable, but also means indentation errors can cause real bugs rather than just style issues. Statements typically don't require a semicolon at the end, and comments are marked with a # symbol.
Variables and data types. Python is dynamically typed, meaning you don't need to declare a variable's type explicitly — the type is determined at runtime based on the value assigned. Core built-in types include integers, floating-point numbers, strings (text), booleans (True/False), and None (representing the absence of a value). Variables are created simply by assignment, like x = 5, with no separate declaration step required.
Control flow. Python supports standard control flow constructs: if/elif/else for conditional branching, for loops for iterating over sequences (like lists or ranges of numbers), and while loops for repeating a block as long as a condition holds. Python's for loop is generally used to iterate directly over the items of a sequence, rather than manually managing an index counter, which is a common source of confusion for people coming from languages where indexed loops are more standard.
Functions. Functions are defined using the def keyword, can accept parameters (including optional parameters with default values), and return values using the return keyword. Functions are first-class objects in Python, meaning they can be assigned to variables, passed as arguments to other functions, and returned from other functions — a flexibility that underlies many common Python patterns.
Common built-in data structures. Beyond the basic types, Python includes several built-in container types covered in more depth elsewhere: lists (ordered, mutable sequences), tuples (ordered, immutable sequences), dictionaries (key-value mappings), and sets (unordered collections of unique items). Choosing the right structure for a given task is a core part of writing idiomatic, efficient Python code.
Error handling. Python uses try/except blocks to handle errors gracefully rather than letting a program crash outright when something unexpected happens — for example, catching an error that occurs when trying to convert invalid text into a number, and handling it with a sensible fallback rather than stopping the program entirely.
Why Python is widely used. Python's combination of readable syntax, a large standard library, and an extensive ecosystem of third-party packages for nearly any task — from web frameworks to data science and machine learning libraries — has made it one of the most widely adopted languages both for beginners learning to program and for production systems at scale. Its emphasis on readability also tends to make Python code easier for teams to maintain and review over time compared to more syntactically dense languages.
Running Python code. Python programs can be run in several ways, and beginners meet all of them early: the interactive interpreter (or REPL), where typing a line of code executes it immediately — useful for experimenting; script files, where code saved in a .py file is executed top to bottom with the python command; and notebook environments popular in data work, which mix runnable code cells with text and output. All three run the same language; they differ in workflow, and knowing which one a tutorial or teammate assumes avoids early confusion.
The standard library. A large part of Python's practicality is what ships with it. The standard library includes ready-made modules for common needs — working with dates and times, reading and writing files in formats like CSV and JSON, mathematics and randomness, interacting with the operating system, and much more — imported with a simple import statement. Reaching for the standard library before installing third-party packages keeps programs simpler and more portable, and knowing roughly what it covers is part of thinking like a Python programmer.
Common beginner mistakes. A few stumbles recur for almost everyone learning Python: confusing = (assignment) with == (comparison); inconsistent indentation, especially when mixing tabs and spaces; forgetting that most type mismatches — like adding a number to a string — must be resolved explicitly with a conversion; and misreading error messages, which in Python are genuinely informative once you learn to read the last line first, where the error type and message live. Treating error output as a description of the problem rather than a wall of noise is one of the fastest habits a beginner can build.
Understanding these fundamentals — syntax, variables, control flow, functions, and basic error handling — forms the foundation for everything else in Python, including the more specific topics of data structures and object-oriented programming covered separately. The encouraging part is how quickly the pieces connect: a beginner who can write a function, loop over a list, and handle one error already has the ingredients of most everyday scripts.
Sample questions
Three questions from this topic, with the answer and the reasoning shown.
Q1EasyHow does Python typically define code blocks?
- Using indentation (whitespace)Correct
- Using curly braces exclusively
- Using the word 'block' before each statement
- Python has no concept of code blocks
Explanation
Where C, Java and JavaScript use braces to mark where a block begins and ends, Python uses the whitespace itself. The language reference is explicit about it: "Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements." Indentation is not a style preference a formatter tidies up later; it is syntax the parser reads, which is why the reference can state flatly that "The clause headers of a particular compound statement are all at the same indentation level."
The consequence you will meet in real code arrives the first time you paste a snippet from a web page into a file your editor indents with tabs. Python raises a TabError, documented as "Raised when indentation contains an inconsistent use of tabs and spaces," because those lines can mean two different things depending on how wide a tab is. Pick one convention, four spaces, and let your editor enforce it. An IndentationError is then rarely mysterious: it is the parser telling you your block boundaries disagree.
Q2MediumHow does Python's `try`/`except` block behave?
- It lets a program handle an error gracefully instead of crashing outrightCorrect
- It permanently disables all error messages
- It only works for syntax errors
- It automatically fixes any bug in the code
Explanation
A try/except block does not make errors disappear; it decides who deals with one when it arrives. The reference puts it plainly: "The try statement specifies exception handlers and/or cleanup code for a group of statements." When something raises inside the guarded code, "If an exception occurs during execution of the try clause, the rest of the clause is skipped" and control jumps to a matching except, so your program keeps running instead of stopping with a traceback.
What matters tomorrow is how narrowly you catch. Catching ValueError around a call to int() handles bad input and nothing else; wrapping the same lines in a bare except also swallows the misspelled variable name three lines down, and you lose an hour to a function that silently returns nothing. The tutorial's guidance is "to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on." Put the code that should run only when nothing raised in an else clause, and cleanup that must happen either way in finally.
Q3MediumWhat does it mean that Python is dynamically typed?
- You don't need to explicitly declare a variable's type; it's determined at runtimeCorrect
- Variable types can never change once a program starts
- All variables must be declared as strings
- Python cannot store numbers
Explanation
Dynamically typed means the name carries no type; the object does. "Names refer to objects. Names are introduced by name binding operations," and "Every object has an identity, a type and a value." So writing count = 5 does not declare count to be an integer. It binds the name count to an integer object, and rebinding count to a string on the next line is perfectly legal, because you are only changing what the name points at.
The mistake worth avoiding is hearing "dynamically typed" as "untyped." Python checks types strictly. It just checks them at runtime, at the moment of the operation, so adding a string to an integer raises TypeError when that line actually executes rather than when you save the file. A type bug can therefore sit undisturbed inside a branch nobody exercises until production traffic finds it. Annotations do not change that: "The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc." Tests and a checker earn their keep here.
Practise all 3 questions
Every published question in Python Basics, with its answer and explanation.