Try the IDLE Shell — Types & Expressions
Type an expression, a print(...) call, or a type(...) call at the prompt below and press Enter. Try type(5), type(3.5), type("hello"), or an arithmetic expression like num1 ** num2.
IDLE Shell 3.10.12
● liveCharacter Set
A character set is the collection of valid characters a programming language can recognise and use for writing programs. Every instruction or statement in Python must be composed of these characters.
Letters
All uppercase (A–Z) and lowercase (a–z) letters of the English language.
Digits
All numeric digits, 0 through 9.
Special Symbols
A wide range of symbols such as " ' ; : ! ~ @ # $ % ^ & * ( ) _ + - = { } [ ] \
Whitespace Characters
Blank spaces, tabs, newline and carriage return.
Other Characters
All other ASCII and Unicode characters supported by Python.
Tokens
A Python instruction consists of tokens, where each token is a collection of one or more characters — the smallest individual unit in a Python program. Python has five types of tokens: Keywords, Identifiers, Literals, Operators and Punctuators.
5.2.1 Keywords
A keyword is a special reserved word with predefined meaning, recognised by the interpreter and used only for its defined purpose. Python is case-sensitive, so keywords must be written exactly as specified — True is a valid keyword, but true is not.
| Keyword | Keyword | Keyword | Keyword | Keyword | Keyword |
|---|---|---|---|---|---|
| as | def | finally | in | or | while |
| and | del | for | is | pass | with |
| assert | elif | from | lambda | raise | yield |
| break | else | global | nonlocal | return | |
| class | except | if | None | True | |
| continue | False | import | not | try |
5.2.2 Identifiers
Identifiers are user-defined words used to name program elements — variables, functions, objects, classes. An identifier is an arbitrary long sequence of letters, digits and underscores ( _ ) that must satisfy the following conditions.
First Character Rule
The first character must be a letter or an underscore.
No Whitespace/Symbols
Whitespace and special characters are not allowed anywhere in an identifier.
No Keywords
Keywords cannot be used as identifiers. There's no length limit, but short and meaningful names are best.
Valid examples: count, avg_marks, FOR, _1stRank.
5.2.3 Literals
A token that indicates a constant value is called a literal — literals are often called constants. Python supports string, numeric, and Boolean literals, plus the special literal None. Each literal an interpreter processes gets its own memory space, called an object.
1. String Literals
A sequence of characters within single/double/triple quotes — e.g. "Computer Science", 'Python', '''#number2'''. Triple quotes can also hold multiline strings.
2. Numeric Literals
Integer — binary (0b1111), decimal (15), octal (0o17), hex (0xF). Float — real numbers with a fractional part, e.g. -3.14, 0.5. Complex — form a+bj, e.g. 5+3j, 2-5j.
3. Boolean Literals
Two Boolean literals — True and False — represent logical conditions and comparison/logical results.
4. Special Literal — None
None denotes nothing, no value, or the absence of a value.
Escape Sequences
| Escape Sequence | Character |
|---|---|
| '\t' or "\t" | Tab |
| '\n' or "\n" | New line |
| '\'' or "\'" | Single quote |
| '\"' or "\"" | Double quote |
| '\\' or "\\" | Backslash |
Literal Collections
Built-in ways to group multiple literals into a single unit — list, tuple, dictionary, or set.
List
Comma-separated elements within square brackets. Values can be of any type and can be changed. my_list = [25, "Python", 95.5, 'A+']
Tuple
Comma-separated values within round brackets. Any type allowed, but values cannot be changed. my_tup = (23, "Computer Science", 'A', 35.8)
Dictionary
An unordered set of key-value pairs within curly braces. my_dict = {1: 'one', 2: 'two', 3: 'three'}
Set
An unordered collection in curly braces — no duplicates allowed, unlike list and tuple. my_set = {'sat', 'sun', 20, 3.14}
Ordered collections (list, tuple) preserve the sequence elements were added in, and each item has a fixed index. Unordered collections (dictionary, set) don't guarantee a fixed position, so items aren't accessed by index number.
5.2.4 Operators & 5.2.5 Punctuators
Operators
A token or symbol that tells the interpreter about a specific operation, applied on operands. Examples: + * // > !=. Detailed in section 5.5.
Punctuators
Special symbols that help organise the structure of a program — much as punctuation marks structure a sentence. Examples: [ , @ { )
Variables & Data Types
Every value in a Python program must be stored somewhere in memory. Python creates this memory as needed and lets us refer to it using identifiers called variables.
What Is a Variable?
The statement x = 3 associates the variable x with an object holding the integer literal 3. A variable carries three aspects of that object: its identity (memory address), data type, and value.
No Explicit Declaration
Unlike some languages, Python variables need no type declaration. Assigning a value creates an object with that value, and the variable's data type matches the object it refers to.
Python Data Type Classes
Numeric
int, float, complex
Sequence
str, list, tuple
Dictionary
dict
Boolean
bool
Set
set, frozenset
Python treats both simple data types and their aggregates as classes — the terminology used in Object Oriented Programming, covered in Class XII.
The variable's data type changes whenever it is reassigned a value of a different type — e.g. after num = 10 (int), the statement num = 3.5 makes num a float.
5.4.1 Mutable and Immutable Data Types
Mutable types allow their value to be modified after creation; immutable types do not — updating them creates a brand-new object instead.
Mutable Types
Lists, dictionaries, and sets. Updating them changes the value inside the same memory object — the variable keeps referring to it.
Immutable Types
int, float, str, tuple. Updating them makes Python create a new memory object; the variable is redirected to it, and the old object survives only if some other variable still refers to it.
Operators
Operators are special symbols or keywords used to perform operations on operands. Python offers arithmetic, relational, logical, assignment, identity and membership operators. Those needing one operand are unary; those needing two are binary.
5.5.1 Arithmetic Operators
Assume num1 = 5 and num2 = 2.
| Operator | Operation | Description | Example |
|---|---|---|---|
| + | Addition & Concatenation | Adds two numeric values; joins two strings | num1+num2 → 7 "Hello"+"Guys" → HelloGuys |
| - | Subtraction | Subtracts right operand from left | num1-num2 → 3 |
| * | Multiplication & Repetition | Multiplies values; repeats a string if the second operand is an int | num1*num2 → 10 "Hello"*2 → HelloHello |
| / | Division | Divides left by right; always returns a float | num1/num2 → 2.5 |
| % | Modulus | Returns the remainder of division | num1%num2 → 1 |
| // | Floor Division | Divides and rounds down to the nearest integer | num1//num2 → 2 5.0//2.0 → 2.0 |
| ** | Exponent | Raises the left operand to the power of the right | num1**num2 → 25 |
The + and - symbols can also act as unary plus/minus. Used with strings, + concatenates; used with a string and an integer, * repeats.
How Operand Type Affects the Result (using +)
| Operand 1 | Operand 2 | Result Type | Example |
|---|---|---|---|
| int | int | int | 7 + 5 → 12 |
| int | float | float | 7 + 2.5 → 9.5 |
| float | int | float | 7.5 + 5 → 12.5 |
| float | float | float | 7.5 + 2.5 → 10.0 |
5.5.2 Relational Operators
Binary operators that compare two operands and return a Boolean. Assume num1=5, num2=2, num3=5, str1="Good", str2="Bad".
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | num1==num2 → False str1=="Good" → True |
| != | Not equal to | str1!=str2 → True |
| > | Greater than | num1>num3 → False str1>str2 → True |
| >= | Greater than or equal to | num1>=num3 → True |
| < | Less than | num1<num2 → False |
| <= | Less than or equal to | num1<=num3 → True |
Strings compare by Unicode/alphabetical precedence — "Good" < "good" is True, since uppercase letters have smaller Unicode values. Comparing a number with a string using operators other than ==/!= raises a Type Error — e.g. 3<"3" — although 3.0<4 works since 4 is implicitly converted to float.
5.5.3 Logical Operators
and
True only if both operands are True.
or
True if either operand is True.
not
Unary — reverses the logical state of its operand.
| Operation | First Operand | Second Operand | Result |
|---|---|---|---|
| and | True | X | X |
| and | False | X | False |
| or | True | X | True |
| or | False | X | X |
Values like None, False, 0, "", (), [], {} are treated as False; everything else counts as True. So 3 and 0 evaluates to 0, and "Hello" or "" evaluates to "Hello".
5.5.4 Assignment Operators
The = operator associates a variable with the object holding the value of the right-hand expression. Python also provides compound assignment operators that combine assignment with an arithmetic operation.
| Compound Operator | Equivalent To |
|---|---|
| a += b | a = a + b |
| a -= b | a = a - b |
| a *= b | a = a * b |
| a /= b | a = a / b |
| a %= b | a = a % b |
| a //= b | a = a // b |
| a **= b | a = a ** b |
5.5.5 Identity Operators
Check whether two variables refer to the same object in memory — useful along with the built-in id() function.
| Operator | Description | Example |
|---|---|---|
| is | True if both operands refer to the same memory object | num2=num1; num1 is num2 → True |
| is not | True if they do NOT refer to the same object | num1 is not num2 → False |
5.5.6 Membership Operators
Check whether a value belongs to a sequence (string, list, or tuple).
| Operator | Description | Example |
|---|---|---|
| in | True if the value is found in the sequence | a=[10,15,100]; 10 in a → True |
| not in | True if the value is NOT found in the sequence | '15' not in a → True |
Expressions & Operator Precedence
An expression combines operands and operators and is evaluated to produce a result — the expression's return value. When several operator types appear together, Python resolves the order using operator precedence.
| Order | Operators | Description |
|---|---|---|
| 1 | ** | Exponentiation |
| 2 | + - | Unary plus, unary minus |
| 3 | * / % // | Multiplication, division, modulus, floor division |
| 4 | + - | Addition, subtraction |
| 5 | < <= > >= == != | Relational / comparison operators |
| 6 | = %= /= //= -= += *= **= | Assignment & compound assignment |
| 7 | is is not | Identity operators |
| 8 | in not in | Membership operators |
| 9 | not | Logical NOT |
| 10 | and | Logical AND |
| 11 | or | Logical OR |
Parentheses override the usual order — operations inside them are evaluated first. Operators of equal precedence are evaluated left to right.
Step Through an Evaluation
● live—
Statements & Python Programs
A statement is an instruction to perform a task — assignment, input, output, or control flow. Python executes statements one by one in order, called sequential flow.
5.7.1 Assignment Statement
Multiple Assignment
a = b = c = 10 — all three variables refer to the same object holding 10.
Multiple Values, Multiple Variables
a, b, c = 10, 15, 20 — assigns values in order; expressions can be used instead of literals too.
5.7.2 Input Statement
The input([prompt]) function displays an optional prompt, waits for the user to type a value and press Enter, then returns it — always as a string, even if the input looks numeric.
To use numeric input in calculations, convert it with int() or float() — e.g. num1 = int(input("Enter first number: ")).
5.7.3 Output Statement
The print(value [, …, sep=char1, end=char2]) function displays text, numbers, or calculation results. sep sets the separator between values (default: a space); end sets what follows the last value (default: a new line).
5.8.1 Program — Greet the User
Algorithm
Step 1: Start Step 2: Input Name Step 3: Print "Hello", Name, "Welcome" Step 4: Stop
Program & Output
name = input("Enter your name: ") print("Hello", name, "Welcome!") Enter your name: Niketh Hello Niketh Welcome!
5.8.2 Program — Sum of Two Numbers
Since input() always returns a string, int() converts each entered value to an integer before addition — otherwise Python would concatenate "12" and "43" as text instead of adding them.
5.8.3 Comments in Programs
Single-line Comments
Begin with the # symbol. The interpreter ignores everything from # to the end of that line.
Multi-line Comments
Enclosed in a pair of triple quotes (""" or '''). Comments document code for anyone reading it later — part of the documentation phase of programming.
Quick Recap
Tap a question to reveal the answer.
Which of these are invalid identifiers — Data_rec, Num#, 2ab, try, My File, _num1, Sum2Num, false, True, File.py?
Num# (special symbol #), 2ab (starts with a digit), try (a keyword), My File (contains a space), and File.py (contains a period) are all invalid. Data_rec, _num1, Sum2Num, false (lowercase, not the keyword), and True (a keyword itself, so actually invalid as an identifier) — note only Data_rec, _num1, Sum2Num and false are valid identifiers.
Classify these literals: 12, 'Num#', '''2ab''', 25.6, -5, "123", {1, 'Ardra', 95}, (2, "Niketh", 'Science'), ["Nived", 20, 'A'].
12 and -5 — Integer. 25.6 — Float. 'Num#', '''2ab''', and "123" — String. {1, 'Ardra', 95} — Set. (2, "Niketh", 'Science') — Tuple. ["Nived", 20, 'A'] — List.
What is the data type of each: n=25, PI=3.14, name="Guido", flag=True?
n is int, PI is float, name is str, and flag is bool.
If a=5, b=10, c=2.5, d="hello", what does a/b return, and what type?
a/b evaluates to 0.5, of type float — the standard division operator / always returns a float, regardless of operand types.
If ans=25 initially, what is ans after ans //= 10?
ans //= 10 means ans = ans // 10, so ans becomes 25 // 10 = 2.
Why does 5 + 7 - 2 * 4 evaluate to 4, while 5 + (7 - 2) * 4 evaluates to 25?
Without parentheses, * (precedence 3) runs before +/- (precedence 4): 2*4=8, then 5+7-8=4. With parentheses, (7-2) is forced to evaluate first regardless of normal precedence: 7-2=5, then 5*4=20, then 5+20=25.
Why must int() be used when adding two numbers entered with input()?
Because input() always returns a string, even for numeric-looking entries. Without converting with int() (or float()), the + operator would concatenate the strings instead of adding numbers.
What's the difference between a mutable and an immutable data type, with an example of each?
A mutable type's value can be changed after creation without creating a new object — e.g. a list. An immutable type cannot be changed in place; any update creates a brand-new object — e.g. an int, float, str, or tuple.