In the last chapter you wrote your first print() program. Now it's time to learn Python's alphabet and grammar! ๐ค Just as English has letters, words and sentences, Python has a character set, tokens and statements. This chapter answers the BIG questions: What are the smallest pieces of a Python program? How do we name things correctly? What is a variable and how does it store a value? How do we take input from the user and print neat output? Let's build the foundation! ๐งฑ
The most tested topics are Tokens (types and examples), valid and invalid identifiers, l-value and r-value, input() always returns a string, and print() with sep and end. Type every example in the Python Lab and change the values to see what happens โ that's how Python "clicks"!
3.1 ๐ Introduction
Every language is built in layers. Python is too!
graph LR
A["๐ค Characters\n(letters, digits,\nsymbols)"]
B["๐งฉ Tokens\n(smallest meaningful\nunits)"]
C["๐ Statements\n(one complete\ninstruction)"]
D["๐ Program\n(many statements\ntogether)"]
A --> B --> C --> D
style A fill:#9E9E9E,color:#fff
style B fill:#2196F3,color:#fff
style C fill:#FF9800,color:#fff
style D fill:#4CAF50,color:#fff
Analogy: In English, letters make words, words make sentences, and sentences make an essay. โ๏ธ In Python, characters make tokens, tokens make statements, and statements make a program!
3.2 ๐ค Python Character Set
The character set is the list of all characters that Python recognises and allows in a program.
Letters
Capital A to Z and small a to z
AโZaโzDigits
0 to 9
0โ9Special Symbols
Symbols such as + - * / ( ) [ ] { } = < > # @ and quotes
SymbolsWhitespaces
Blank space, tab, and the Enter (new line)
SpaceTabNewlineOther Characters
Python 3 also accepts Unicode characters โ Hindi, emoji and more inside text
Unicode3.3 ๐งฉ Tokens โ The Building Blocks
A token is the smallest individual unit of a program โ like a single word or punctuation mark in a sentence.
graph TD
T["๐งฉ TOKENS"]
K["๐ Keywords\n(if, for, True)"]
I["๐ท๏ธ Identifiers\n(names like marks, total)"]
L["๐ Literals\n(fixed values: 10, 'Hi')"]
O["โ Operators\n(+, -, *, ==)"]
P["๐ Punctuators\n(brackets, comma,\ncolon, #)"]
T --> K
T --> I
T --> L
T --> O
T --> P
style T fill:#9C27B0,color:#fff
style K fill:#F44336,color:#fff
style I fill:#2196F3,color:#fff
style L fill:#4CAF50,color:#fff
style O fill:#FF9800,color:#fff
style P fill:#795548,color:#fff
Look at this one line and spot all five types of tokens:
total = marks + 5 # add grace marks
โโโโโ โ โโโโโ โ โ โโโโโโโโโโโโโโโโโ
โ โ โ โ โ โ
โ โ โ โ โ โโ comment (# is a punctuator)
โ โ โ โ โโ Literal (5)
โ โ โ โโ Operator (+)
โ โ โโ Identifier (marks)
โ โโ Operator (=)
โโ Identifier (total)
The five types of tokens are Keywords, Identifiers, Literals, Operators, Punctuators โ just think of a KILO of Potatoes! ๐ฅ
3.3.1 Keywords ๐
Keywords are reserved words that have a special meaning in Python. You cannot use them as names for variables.
False |
None |
True |
and |
as |
assert |
async |
await |
break |
class |
continue |
def |
del |
elif |
else |
except |
finally |
for |
from |
global |
if |
import |
in |
is |
lambda |
nonlocal |
not |
or |
pass |
raise |
return |
try |
while |
with |
yield |
That's 35 keywords. You can see them yourself:
import keyword
print(keyword.kwlist)
print(len(keyword.kwlist))
True, False, NoneAll other keywords are in small letters. Writing true or none is NOT a keyword โ Python will treat it as an unknown name and give a NameError.
Analogy: Keywords are like reserved seats ๐บ in a bus โ "For Ladies", "For Senior Citizens". They are set aside for a special purpose, so you can't use them for anything else!
3.3.2 Identifiers ๐ท๏ธ
Identifiers are the names we give to variables, functions and other things in a program โ like marks, total, student_name.
- It can contain letters (AโZ, aโz), digits (0โ9) and underscore ( _ ) only.
- It must not start with a digit.
- It must not be a keyword.
- No spaces and no special symbols like
@ # $ % - .are allowed. - Python is case sensitive โ
Marks,marksandMARKSare three different identifiers. - It can be of any length.
Valid or invalid? Let's check!
| Identifier | Valid? | Reason |
|---|---|---|
marks |
โ Valid | Only letters |
total_marks |
โ Valid | Underscore is allowed |
_count |
โ Valid | Can start with an underscore |
class11 |
โ Valid | Digit is fine โ just not at the start |
If |
โ Valid | If is not a keyword (if is!) |
11class |
โ Invalid | Starts with a digit |
total marks |
โ Invalid | Contains a space |
roll-no |
โ Invalid | Hyphen ( - ) is not allowed |
price$ |
โ Invalid | $ is not allowed |
for |
โ Invalid | It is a keyword |
Choose meaningful names: marks is better than m, and total_price is better than tp. Your program becomes easy to read โ for you AND your teacher!
"Which of the following are valid identifiers? My_Name, 2ndPlace, while, roll no, _amount" โ 2 marks
Answer: Valid: My_Name, _amount. Invalid: 2ndPlace (starts with a digit), while (keyword), roll no (contains a space).
3.3.3 Literals ๐
Literals are fixed values written directly in the program โ like 25, 3.14 or "Hello". They are also called constant values.
String Literals
Text inside single, double or triple quotes
'Hi'"Python"'''Hello'''Numeric Literals
Numbers โ whole numbers (int), decimals (float) and complex numbers
253.142+3jBoolean Literals
Only two values โ used for yes/no answers
TrueFalseSpecial Literal
`None` โ means "no value" or "nothing yet"
Nonename = "Riya" # string literal
age = 16 # integer literal
height = 5.4 # float literal
passed = True # Boolean literal
result = None # special literal None
print(name, age, height, passed, result)
Output:
Riya 16 5.4 True None
Triple quotes let a string go over several lines:
poem = """Twinkle twinkle
little star"""
print(poem)
Output:
Twinkle twinkle
little star
3.3.4 Operators โ
Operators are symbols that perform an operation on values. The values they work on are called operands.
10 + 5
โโ โ โ
โ โ โโ operand
โ โโ operator
โโ operand
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + - * / // % ** |
7 + 2 gives 9 |
| Relational (comparison) | < > <= >= == != |
7 > 2 gives True |
| Logical | and or not |
True and False gives False |
| Assignment | = += -= *= /= |
x = 10 |
| Membership | in not in |
'a' in 'cat' gives True |
You will study each operator in detail in the Data Handling chapter.
3.3.5 Punctuators ๐
Punctuators are symbols used to organise the program โ like commas and full stops in English.
' " # \ ( ) [ ] { } @ , : . =
Example: In
print("Hi", name), the ( ) brackets, the " " quotes and the , comma are all punctuators.
"Identify the tokens in the statement: price = 50 * qty" โ 2 marks
Answer: price, qty โ Identifiers; =, * โ Operators; 50 โ Literal.
3.4 ๐ Barebones of a Python Program
A Python program is made of a few basic parts. Let's look at a small program:
Code Example: area.py
# Program to find the area of a rectangle
length = 12
breadth = 5
area = length * breadth
if area > 50:
print("Big rectangle")
print("Area =", area)
Output:
Big rectangle
Area = 60
Comments
Lines or parts starting with # โ ignored by Python, written to explain the code
# My programExpressions
Any combination of values, variables and operators that gives a value
length * breadthStatements
One complete instruction that Python executes
area = length * breadthBlocks and Indentation
A group of statements pushed right by the same spaces โ they belong together
4 spaces3.4.1 Comments ๐ฌ
- Single-line comment: starts with
#. - Multi-line comment: use
#on each line, or write a triple-quoted string (''' ... ''') that is not stored anywhere โ Python simply skips it.
# This is a single-line comment
'''
This is a multi-line comment
written with triple quotes
'''
print("Comments are ignored!") # inline comment
Output:
Comments are ignored!
3.4.2 Indentation ๐ฆ
Indentation means the spaces at the beginning of a line. In Python, indentation is compulsory to show which statements belong to a block (for example, the statements under an if).
if area > 50: โ line ending with a colon ( : )
print("Big rectangle") โ indented โ inside the if-block
print("Area =", area) โ not indented โ outside the block
Adding a space before a normal statement, or forgetting to indent after a colon, gives an IndentationError. The standard is 4 spaces for each level.
Analogy: Indentation is like sub-points in your notebook. ๐ Points written a little to the right belong to the heading above them!
3.5 ๐ฆ Variables and Assignment
A variable is a named location in memory that stores a value. The value can change while the program runs โ that's why it's called a variable!
marks = 85
print(marks)
marks = 92 # value changed
print(marks)
Output:
85
92
Analogy: A variable is like a labelled tiffin box ๐ฑ. The label (
marks) is the variable's name, and the food inside (85) is its value. You can empty the box and put in something new (92) โ the label stays the same!
3.5.1 How Python Stores a Variable ๐ง
In Python, a variable is a name that points to a value stored in memory:
marks = 85 marks = 92
marks โโโโโโโบ โโโโโโ marks โโ โโโโโโ
โ 85 โ โ โ 85 โ (no longer used)
โโโโโโ โ โโโโโโ
โ โโโโโโ
โโโโบโ 92 โ
โโโโโโ
When we give a new value, Python does not change the old box โ the name simply points to the new value.
3.5.2 l-value and r-value โฌ ๏ธ
In an assignment statement, the = sign does not mean "equal to". It means "store the value on the right into the name on the left".
total = marks + 5
โโโโโ โโโโโโโโโ
l-value r-value
(left side: (right side: a value
a name that or expression that
can store) gives a value)
| l-value | r-value |
|---|---|
Appears on the left of = |
Appears on the right of = |
| Must be a variable name | Can be a literal, variable or expression |
e.g. x in x = 10 |
e.g. 10, a + b, y * 2 |
10 = x gives a SyntaxError โ you can't store anything "into" the number 10. Always write x = 10.
3.5.3 Multiple Assignments ๐
1. Same value to many variables:
a = b = c = 0
print(a, b, c)
Output:
0 0 0
2. Different values to many variables in one line:
name, age, city = "Aman", 16, "Kolkata"
print(name, age, city)
Output:
Aman 16 Kolkata
3. Swapping two values โ Python can swap in one line!
x = 5
y = 10
x, y = y, x
print("x =", x, "and y =", y)
Output:
x = 10 and y = 5
Python first works out the whole right side (10, 5), and only then stores the values into x and y. So nothing gets lost in between!
3.5.4 Dynamic Typing ๐
In Python, the same variable can hold a value of any type, and the type can change later. This is called dynamic typing. The type() function tells us the type of a value.
x = 10
print(type(x))
x = "ten"
print(type(x))
x = 10.5
print(type(x))
Output:
<class 'int'>
<class 'str'>
<class 'float'>
print(score) before writing score = ... gives NameError: name 'score' is not defined.
"What are l-value and r-value? Give an example." โ 2 marks
Answer: In an assignment statement, the l-value is the variable on the left side of = that receives the value, and the r-value is the value or expression on the right side that is evaluated and stored. For example, in total = a + b, total is the l-value and a + b is the r-value.
3.6 โจ๏ธ Taking Input โ the input() Function
The input() function lets the user type a value while the program is running. The message inside the brackets is shown as a prompt.
name = input("Enter your name: ")
print("Hello", name)
Sample run (the user types Priya):
Enter your name: Priya
Hello Priya
3.6.1 input() ALWAYS Gives a String! โ ๏ธ
Whatever the user types โ even a number โ input() returns it as a string (text).
a = input("Enter first number: ")
b = input("Enter second number: ")
print("Sum =", a + b)
Sample run (the user types 10 and 20):
Enter first number: 10
Enter second number: 20
Sum = 1020
๐ฒ 1020, not 30! Because "10" + "20" joins two pieces of text.
Analogy:
input()is like a postman ๐ฎ who always brings you a letter. Even if someone writes the number "10" on it, it is still a piece of paper with writing โ you have to convert it before you can do maths with it!
3.6.2 Converting Input with int() and float() ๐
| Function | Converts to | Example |
|---|---|---|
int() |
Whole number (integer) | int("25") โ 25 |
float() |
Decimal number | float("25.5") โ 25.5 |
str() |
String (text) | str(25) โ "25" |
Code Example: add_numbers.py
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
Sample run (the user types 10 and 20):
Enter first number: 10
Enter second number: 20
Sum = 30
Code Example: simple_interest.py
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time in years: "))
si = p * r * t / 100
print("Simple Interest =", si)
Sample run (the user types 5000, 8 and 2):
Enter principal: 5000
Enter rate: 8
Enter time in years: 2
Simple Interest = 800.0
int("12.5") gives a ValueError. For numbers that may have a decimal point, use float(). Also, int("ten") gives a ValueError โ the text must look like a number.
"Write a program to input the length and breadth of a rectangle and print its area and perimeter." โ 3 marks Answer:
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
print("Area =", l * b)
print("Perimeter =", 2 * (l + b))3.7 ๐จ๏ธ More About print() โ sep and end
When you print many items separated by commas, Python puts a space between them and moves to a new line at the end. We can change both!
sep
Separator โ what goes BETWEEN the items. Default is a single space
sep=' 'end
What goes at the END of the line. Default is a newline
end='\n'Using sep:
print("10", "05", "2026", sep="-")
print("A", "B", "C", sep="")
print("Name", "Riya", sep=" : ")
Output:
10-05-2026
ABC
Name : Riya
Using end:
print("Hello", end=" ")
print("World")
print("Loading", end="...")
print("Done!")
Output:
Hello World
Loading...Done!
Using both together:
print(1, 2, 3, sep="+", end=" = 6\n")
Output:
1+2+3 = 6
sep = the gap BETWEEN friends standing in a line. ๐งโโ๏ธโ๏ธ๐งโโ๏ธ end = what you say at the END of your sentence.
print() with nothing inside prints an empty line.This is useful to leave a blank line between two parts of your output.
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
true = 1 thinking true is a keyword |
Keywords are case sensitive | The keyword is True (capital T) |
2nd_name = "A" |
Identifier starts with a digit | Write name2 or second_name |
roll no = 5 |
Space in an identifier | Write roll_no = 5 |
10 = x |
A literal cannot be an l-value | Write x = 10 |
= means "equal to" |
= is assignment |
= stores a value; == compares |
Adding two input() values directly |
input() returns strings |
Convert with int() or float() first |
int(input()) for 7.5 |
int() can't convert a decimal string | Use float(input()) |
| Extra space before a statement | Unexpected indentation | Start top-level statements at the left edge |
| Using a variable before giving it a value | Name not defined yet | Assign a value first |
print("a", "b", sep=",") gives a , b |
sep replaces the space completely | It gives a,b |
๐ Quick Revision โ Exam Ready!
- Character set โ letters, digits, special symbols, whitespaces, Unicode
- Token โ smallest unit of a program; 5 types โ Keywords, Identifiers, Literals, Operators, Punctuators (KILOP)
- Keywords โ 35 reserved words; only
True,False,Nonestart with a capital - Identifier rules โ letters, digits, underscore; not starting with a digit; not a keyword; no spaces or symbols; case sensitive
- Literals โ String, Numeric (int, float, complex), Boolean (
True,False), Special (None) - Operators act on operands; Punctuators organise code (
( ) [ ] { } , : # ' ") - Comments โ
#for one line; triple quotes for many lines - Indentation โ compulsory for blocks; usually 4 spaces
- Variable โ a named memory location whose value can change
- l-value โ left of
=(a name); r-value โ right of=(a value or expression) - Multiple assignment โ
a = b = 0anda, b = 1, 2; swap โa, b = b, a - Dynamic typing โ same variable can hold different types; check with
type() - input() โ always returns a string; convert with
int()orfloat() - print() โ
sep= between items (default space);end= at the end (default newline)
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the smallest individual unit in a Python program called? Answer: Token
b) Which of these is a keyword: Print, none, None, If?
Answer: None
c) What type of value does input() return?
Answer: A string (str)
d) What is the default value of sep in print()?
Answer: A single space ' '
e) Name the function used to find the type of a value.
Answer: type()
f) Is _total_2 a valid identifier?
Answer: Yes
Q2: Short Answer [2 marks]
Identify the type of each token: if, marks, "Delhi", >=, 3.14, :
Answer:
| Token | Type |
|---|---|
if |
Keyword |
marks |
Identifier |
"Delhi" |
Literal (string) |
>= |
Operator |
3.14 |
Literal (float) |
: |
Punctuator |
Q3: Output Based [2 marks]
Write the output:
x, y = 4, 9
x, y = y, x
print(x, y, sep="#")
print("Sum", end=": ")
print(x + y)
Answer:
9#4
Sum: 13
Q4: Output Based [2 marks]
If the user enters 5 and then 7, what will this program print? Why?
a = input("A: ")
b = input("B: ")
print(a + b)
print(int(a) + int(b))
Answer:
A: 5
B: 7
57
12
input() returns strings, so a + b joins "5" and "7" to give 57. After converting with int(), the numbers are added to give 12.
Q5: Error Finding [2 marks]
Find and correct the errors:
1st num = int(input("Enter number: ")
print("Square =" 1st num * 1st num)
Answer:
num1 = int(input("Enter number: "))
print("Square =", num1 * num1)
Errors: the identifier had a digit at the start and a space, the closing bracket of int(...) was missing, and the comma between the items in print() was missing.
Q6: Program [3 marks]
Write a program to input the marks of a student in three subjects and print the total and the average.
Answer:
m1 = float(input("Enter marks 1: "))
m2 = float(input("Enter marks 2: "))
m3 = float(input("Enter marks 3: "))
total = m1 + m2 + m3
print("Total =", total)
print("Average =", total / 3)
Sample run (the user types 80, 90 and 70):
Enter marks 1: 80
Enter marks 2: 90
Enter marks 3: 70
Total = 240.0
Average = 80.0
โ๏ธ Practice Problems
- What is a token? Name its five types with one example of each.
- Which of these are invalid identifiers, and why?
Roll_No,roll-no,rollno1,1rollno,global,_roll - Give one example each of a string, integer, float, Boolean and
Noneliteral. - Write the output:
print("Good", "Morning", sep="***") - Write the output:
print("A", end="")followed byprint("B") - Write a program to input a number and print its square and cube.
- Write a program to input temperature in Celsius and print it in Fahrenheit (F = C ร 9 / 5 + 32).
- Write a program to input two numbers and swap them. Print the values before and after swapping.
- Why does
print(input("A: ") * 2)print55when the user types5? How would you print10instead? - What is indentation? What error do you get if a statement is indented without a reason?
- Explain dynamic typing with a small program that uses
type(). - Write a program to input the price of an item and the quantity bought, and print the bill amount as
Bill amount = Rs <amount>.