Python syntax is the set of rules for writing Python programs so the computer can understand them. This cheat sheet covers the core commands and patterns students use when starting to code in Python. It is useful for quickly checking how to write variables, loops, functions, lists, dictionaries, and basic input or output.
Students in grades 7-12 can use it while practicing coding, debugging, or preparing for class projects.
Key Facts
- Use a variable name, an equals sign, and a value to store data, such as score = 10.
- Common Python data types include int for whole numbers, float for decimals, str for text, and bool for True or False values.
- Use print(value) to display output and input("Prompt: ") to collect text input from the user.
- Use if, elif, and else with indented code blocks to make decisions, such as if score >= 90: print("A").
- Use a for loop to repeat over a sequence, such as for i in range(5): print(i).
- Use a while loop to repeat while a condition is True, such as while count < 3: count += 1.
- Define a function with def name(parameters): and return a value with return result.
- Access list items by index starting at 0, such as items[0], and add an item with items.append(value).
Vocabulary
- Variable
- A named storage location that holds a value, such as age = 14.
- Data Type
- A category of value in Python, such as int, float, str, bool, list, or dict.
- Condition
- An expression that evaluates to True or False and controls decisions in code.
- Loop
- A structure that repeats a block of code multiple times.
- Function
- A reusable block of code defined with def that can take inputs and return an output.
- Indentation
- Spaces at the start of a line that show which statements belong inside a code block.
Common Mistakes to Avoid
- Forgetting the colon after if, elif, else, for, while, or def is wrong because Python uses the colon to begin an indented code block.
- Mixing tabs and spaces for indentation is wrong because Python may not recognize the block structure correctly and can raise an IndentationError.
- Using = instead of == in a condition is wrong because = assigns a value, while == compares two values.
- Trying to add a string and a number directly, such as "Score: " + 10, is wrong because Python needs the number converted with str(10).
- Using the wrong list index is wrong because Python starts counting at 0, so the first item is list_name[0], not list_name[1].
Practice Questions
- 1 Write Python code that stores the number 25 in a variable named temperature and prints it.
- 2 What is printed by this code: total = 3 + 4 * 2; print(total)?
- 3 Write a for loop that prints the numbers 1 through 5.
- 4 Explain why indentation matters in Python when writing an if statement or a loop.
Understanding Python Syntax Quick Reference
Python runs a program from top to bottom unless a decision, loop, or function call changes that path. This order matters when one line depends on a value created earlier. A variable is better understood as a label connected to data than as a physical box.
When a later assignment uses the same name, the label points to the new value. Clear names such as total_points or player_name make a program easier to read and fix.
Python is case sensitive, so Score and score are two different names. Names cannot begin with a number, and names with spaces will cause an error.
Indentation is one of Python's most important rules. A group of lines inside a condition, loop, or function must line up at the same indentation level. Usually programmers use four spaces for each level.
One misplaced space can change which instructions repeat or run only in a certain case. Conditions produce Boolean results. A comparison can be true or false, and that result controls the next block of code.
Students often meet this idea in games, where a player gains a life after reaching a score, or in school programs that sort marks into grade bands. Test boundary values carefully. A score exactly at a cutoff is often where logic mistakes appear.
Input from the keyboard arrives as text, even when the user types digits. A program that needs to calculate with that input must convert it to a whole number or decimal number first. This is a common source of bugs in calculators, quizzes, and data entry programs.
Lists hold items in a fixed order, which makes them useful for a playlist, a set of quiz answers, or daily temperatures. Their first position is numbered zero, so the final item has a position one less than the list length. Dictionaries store values under meaningful keys.
They suit information like a student's name, age, and house points. Take care when changing a list inside a loop, since removing or adding items can shift positions.
Functions split a large task into smaller named tasks. A well chosen function can calculate a result, check whether input is valid, or display one part of a game. Parameters are names that receive information when the function is called.
A returned value travels back to the line that called the function, where it can be stored or used in another calculation. Variables created inside a function normally stay local to that function, which prevents unrelated parts of a program from changing them by accident. When code fails, read the error message from the bottom upward and locate the named line.
Then check spelling, indentation, data type, and the current values of variables. Small print statements placed temporarily in a program can reveal what the code is doing at each step.