How unit 1 is examined
This unit covers Python's basics: syntax, literals, numbers, variables, strings, operators, indentation, input, output, functions and comments. No past questions are tagged, so every topic is a short, complete definition with key points.
Introduction to python language
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Python is a high-level, interpreted, general-purpose, dynamically typed programming language created by Guido van Rossum and released in 1991.</mark>
Key points.
- Python is interpreted, so code runs line by line without a separate compile step.
- It is dynamically typed, so a variable's type is decided at run time and needs no declaration.
- Its syntax is short and readable, and blocks are marked by indentation instead of braces.
- It is free, open source and portable across Windows, Linux and macOS.
- It supports procedural, object-oriented and functional styles and has a large standard library.
Basic syntax
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Syntax is the set of rules that decide how a valid Python statement is written.</mark>
Key points.
- Each statement normally ends at the end of the line; no semicolon is needed.
- Python is case-sensitive, so
Totalandtotalare different names. - Identifiers may contain letters, digits and underscore, and cannot start with a digit or be a keyword such as
if,fororclass. - A long statement can continue on the next line with a backslash
\or inside brackets. - Blocks are defined by indentation, and a line ending with a colon opens a block.
Literal Constants
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A literal is a fixed value written directly in the source code, such as 10, 3.5, 'hi' or True.</mark>
Key points.
- Numeric literals are integers (
25,0b101,0o17,0xFF), floats (3.14,1e3) and complex numbers (2+3j). - String literals are text in single, double or triple quotes.
- Boolean literals are
TrueandFalse. - The special literal
Nonemeans "no value". - Collection literals include list
[1,2], tuple(1,2), dictionary{'a':1}and set{1,2}.
Numbers
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Python has three numeric types: int for whole numbers, float for real numbers with a decimal point, and complex for numbers of the form a+bj.</mark>
Key points.
- An
inthas unlimited size, so very large integers never overflow. - A
floatis stored in binary, so0.1 + 0.2gives0.30000000000000004. - A complex number has a real and an imaginary part, for example
3+2j. type()shows the type of a value, andint(),float()andcomplex()convert between types.boolis a subtype ofint, withTrueequal to 1 andFalseequal to 0.
Variable and Basic data types
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. ==A variable is a named memory location that refers to a value; it is created by assignment, for example x = 5.==
Key points.
- No type declaration is needed; the type comes from the value, and the same name can later refer to a value of another type.
- Basic types are
int,float,complex,str,boolandNoneType. - Multiple assignment is allowed, for example
a, b = 1, 2anda = b = 0. type(x)gives the type andid(x)gives the identity of the object.- Variable names should be meaningful, lowercase and follow the identifier rules.
x = 5 # int
x = "five" # now str
print(type(x)) # <class 'str'>
String
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A string is an immutable sequence of characters written inside single, double or triple quotes.</mark>
Key points.
- Triple quotes allow a string to span several lines.
- Indexing starts at 0, and negative indexes count from the end, so
'hello'[1:3]is'el'and'hello'[::-1]is'olleh'. - Strings are immutable, so a character cannot be changed in place.
+joins strings,*repeats them, andlen()gives the length.- Common methods are
upper(),lower(),strip(),split(),replace()andfind().
Escape Sequences
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>An escape sequence is a backslash followed by a character that stands for a special character inside a string.</mark>
Key points.
| Sequence | Meaning |
|---|---|
\n |
new line |
\t |
tab |
\\ |
backslash |
\' and \" |
quote characters |
- A raw string such as
r"C:\new"turns off escape processing. - Without escaping,
\nin a path would be read as a new line.
Operators and Expressions
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>An operator is a symbol that acts on operands, and an expression is a combination of operands and operators that evaluates to a value.</mark>
Key points.
- Arithmetic operators are
+ - * / // % **, where/gives a float,//floors, so7//2is 3 and-7//2is -4, and**is power. - Relational operators
== != < > <= >=returnTrueorFalse, and chaining such as10>5>3is allowed. - Logical operators are
and,orandnot. - Assignment operators include
=,+=,-=and*=. - Other operators are bitwise
& | ^ ~ << >>, membershipin,not in, and identityis,is not.
Evaluation Order
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Operator precedence decides which operator is evaluated first in an expression, and associativity decides the order among operators of equal precedence.</mark>
Key points.
- The order from highest to lowest is: brackets,
**, unary-,* / // %,+ -, comparisons,not,and,or. - Most operators associate left to right, but
**associates right to left, so2**3**2is 512. **binds tighter than unary minus, so-3**2is -9.- For example
2+3*4**2is2+3*16=2+48= 50. - Brackets override precedence and make the order clear.
Indentation
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Indentation is the leading whitespace at the start of a line, and Python uses it to define blocks of code.</mark>
Key points.
- All statements in one block must have the same indentation, and four spaces is the standard.
- A block starts after a colon in
if,for,while,defandclass. - Wrong indentation raises
IndentationError. - Mixing tabs and spaces should be avoided.
if 5 > 3:
print("yes") # inside the block
Input
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>input() reads a line typed by the user and returns it as a string.</mark>
Key points.
- An optional prompt can be given, as in
input("Enter: "). - The result is always a
str, soint()orfloat()is needed for numbers. - Example:
n = int(input("Enter n: ")). - Several values can be read with
a, b = map(int, input().split()).
Output
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>print() displays values on the screen.</mark>
Key points.
- Multiple values are separated by a space by default, and
sepchanges the separator. endchanges the ending, which is a new line by default, soprint('a','b',sep='-',end='!')showsa-b!.- Formatting can use f-strings such as
f"x = {x}",format()or%. print()accepts any object and converts it to text.
Functions
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A function is a named, reusable block of code defined with def that runs when it is called and may return a value.</mark>
Key points.
- The syntax is
def name(parameters):followed by an indented body. returnsends a value back; without it the function returnsNone.- Arguments can be positional, keyword or default, as in
def f(a, b=2). - Functions give reuse and modularity, and built-in ones include
len(),print()andtype().
def add(a, b=2):
return a + b
print(add(3)) # 5
Comments
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A comment is text ignored by the interpreter that explains the code to the reader.</mark>
Key points.
- A single-line comment starts with
#and runs to the end of the line. - Python has no true multi-line comment; a triple-quoted string is used as a docstring or a block note.
- Comments make code readable and can temporarily disable a line.
Last-minute revision
- Python is high-level, interpreted, dynamically typed, created by Guido van Rossum in 1991.
- Blocks are marked by indentation after a colon; wrong indentation raises
IndentationError. - Numeric types are
int,floatandcomplex;inthas unlimited size. - Strings are immutable;
'hello'[1:3]is'el'. /gives a float,//floors (-7//2is -4),**is power.2**3**2is 512 and-3**2is -9.input()always returns a string.print(sep=, end=)control separator and ending.defdefines a function; noreturnmeansNone.#starts a comment.- Escape sequences:
\n,\t,\\.
Memory hooks
- PEMDAS-like: brackets, power, times/divide, plus/minus, compare, not, and, or.
- "input() is always a string": convert before adding.
- Colon opens a block, indentation fills it.
//floors toward minus infinity.
Coverage checklist
- Introduction to python language: definition and features.
- Basic syntax: statements, case sensitivity, identifiers.
- Literal Constants: numeric, string, boolean, None.
- Numbers: int, float, complex.
- Variable and Basic data types: assignment, dynamic typing.
- String: quotes, slicing, immutability.
- Escape Sequences:
\n,\t, raw strings. - Operators and Expressions: all operator groups.
- Evaluation Order: precedence and associativity.
- Indentation: blocks and IndentationError.
- Input:
input()and conversion. - Output:
print()with sep and end. - Functions:
def,return, arguments. - Comments:
#and docstrings.