Python Fundamentals
Chapter 6 — Complete Study Notes
Computer Science with Python — Class XI (Sumita Arora)
6.1 Introduction
Every computer action follows the IPO cycle: Input → Process → Output. Programs are the
instructions that govern this processing cycle.
In this chapter you will learn about:
• Character set — the valid characters Python understands
• Tokens — the smallest building blocks of a program
• Expressions and Statements
• Variables and Assignments
• Simple Input and Output using input() and print()
6.2 Python Character Set
Definition — Character Set: A set of valid characters that a language can
recognise. Python supports the Unicode encoding standard.
Python's character set includes:
Category Characters
Letters A–Z, a–z
Digits 0–9
Special Symbols + – * / ** \ ( ) [ ] { } // = ! == < > . ' " , ; : % ! & # <= >=
@ _ (underscore)
Whitespaces Blank space, tabs (→), carriage return (↵), newline,
form feed
Other characters All ASCII and Unicode characters as data or literals
6.3 Tokens
Definition — Token (Lexical Unit): The smallest individual unit in a program. Just
as words and punctuation marks are the tokens of a sentence, a Python program's
tokens are its smallest building blocks.
Python has five types of tokens:
• Keywords
• Identifiers (Names)
• Literals (Values)
• Operators
• Punctuators
6.3.1 Keywords
Definition — Keyword: A word that conveys a special meaning to the Python
compiler/interpreter. Keywords are reserved and cannot be used as identifier names.
Python has 35 built-in keywords. Here is the complete list:
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
⚠️ Important Rules about Keywords:
• Keywords are case-sensitive. True is a keyword; true is not.
• Keywords cannot be used as variable names, function names, or any
identifier.
• You can view Python keywords using: import keyword; print([Link])
6.3.2 Identifiers (Names)
Definition — Identifier: The user-defined names given to different parts of a
program such as variables, functions, classes, objects, lists, dictionaries, etc.
Rules for forming valid identifiers:
1. An identifier is an arbitrarily long sequence of letters and digits.
2. The first character must be a letter (A–Z or a–z); the underscore ( _ ) counts as a letter.
3. Upper-case and lower-case letters are treated as different (Python is case-sensitive).
4. Digits 0–9 can be part of an identifier, except as the first character.
5. Identifiers are unlimited in length.
6. An identifier must NOT be a keyword of Python.
7. An identifier cannot contain any special character except the underscore ( _ ).
Identifier Valid / Invalid — Reason
Myfile Valid — starts with a letter
_data Valid — underscore counts as letter
FILE13 Valid — digits allowed after first char
Z2T0Z9 Valid — mix of letters and digits
DATA-REC INVALID — hyphen ( - ) is a special character
29CLCT INVALID — starts with a digit
break INVALID — reserved keyword
[Link] INVALID — dot ( . ) is a special character
📌 Python is CASE-SENSITIVE
age, Age, and AGE are three completely different identifiers!
6.3.3 Literals (Values)
Definition — Literal: A data item that has a fixed value. Also called constants.
Python supports five kinds of literals.
Python allows the following types of literals:
• String Literals
• Numeric Literals (Integer, Float, Complex)
• Boolean Literals
• Special Literal None
• Literal Collections (Tuples, Lists — covered later)
6.3.3A String Literals
Definition — String Literal: A sequence of characters enclosed within quotes
(single, double, or triple quotes).
String literals can be created using:
• Single quotes: 'hello', 'abc'
• Double quotes: "hello", "abc"
• Triple quotes (multiline): '''...''' or """..."""
Examples of valid string literals:
'Astha' "Rizwan" 'HelloWorld'
'Amy\'s' "129045" '1-x-0-w-25'
'Hello World' "112FBD291"
Escape Sequences
Escape sequences represent non-graphic (non-printable) characters inside strings. Each
escape sequence starts with a backslash (\) and represents one character.
Escape Sequence What it represents
\\ Backslash ( \ )
\' Single quote ( ' )
\" Double quote ( " )
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n Newline character
\r Carriage Return (CR)
\t Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh
String Types — Single-line vs Multiline
(i) Single-line Strings: Created with single or double quotes. Must terminate on the same line.
text1 = 'hello' # Valid
text2 = "world" # Valid
(ii) Multiline Strings: Span across multiple lines. Created in two ways:
Method 1 — Backslash at end of line:
text1 = 'hello\
world'
Method 2 — Triple quotes (most common):
str1 = '''Hello
World.
There I come!!!
'''
str2 = """Hello
World.
This is another multiline string."""
📝 Size of Strings
Python counts the number of characters. Escape sequences count as ONE
character.
'\\' → size 1 'abc' → size 3 "\ab" → size 2 "Seema\'s pen" → size 11
For triple-quoted multiline strings: EOL (Enter key) characters are also counted in the
size.
6.3.3B Numeric Literals
Numeric literals belong to three data types:
Type Description
int (signed integers) Positive or negative whole numbers without a
decimal point. e.g., 5, -17, +41
float (floating point) Real numbers written with a decimal point. e.g.,
3.14, -0.5, 2.0
complex (complex numbers) Of the form a + bJ, where a and b are floats and J =
√(-1). e.g., 3+4j
Integer Literals — Three Forms
Type Description & Examples
Decimal Normal digits 0–9 (no leading zero). e.g., 1234, 41,
+97, -17
Octal Starts with 0o (zero + letter o). e.g., 0o10 (=8 in
decimal), 0o14 (=12 in decimal)
Hexadecimal Starts with 0x or 0X. Contains digits 0–9 and letters
A–F. e.g., 0xABC, 0XFF
Floating Point Literals — Two Forms
Form 1 — Fractional Form: Must have at least one digit before or after the decimal point.
Valid: 2.0, 17.5, -13.0, -0.00625, .3 (means 0.3), 7. (means 7.0)
Invalid: 7 (no decimal), +17/2 (slash not allowed), 17,250.26 (comma not
allowed)
Form 2 — Exponent Form: Has a mantissa and an exponent separated by E or e.
Valid: 152E05, 1.52E07, 0.152E08, -0.172E-3, 172E3
Format: mantissa E exponent e.g., 0.58E1 means 0.58 × 10¹ = 5.8
Invalid: 1.7E (no digit for exponent), 0.17E2.3 (exponent must be integer)
6.3.3C Boolean Literals
Python has only TWO Boolean literal values:
True — represents Boolean true (value = 1)
False — represents Boolean false (value = 0)
None — special literal (absence of value)
Note: True and False start with capital letters. true and false are NOT keywords.
6.3.3D Special Literal None
None is Python's special literal used to indicate the absence of a value. It is also used to
indicate the end of lists.
>>> Value1 = 10
>>> Value2 = None
>>> Value2 # Displays nothing (no output shown)
>>> print(Value2) # Prints: None
6.3.4 Operators
Definition — Operator: A token that triggers some computation/action when applied
to variables and objects in an expression. The variables/objects it operates on are
called operands.
Unary Operators (require one operand):
• + (Unary plus) – (Unary minus) ~ (Bitwise complement) not (Logical
negation)
Binary Operators (require two operands):
Operator Type Operators
Arithmetic + Addition – Subtraction * Multiplication
/ Division % Remainder/Modulus ** Exponent
(power) // Floor division
Relational < Less than > Greater than <= Less than
or equal >= Greater than or equal == Equal to
!= Not equal to
Assignment = Assign += Add and assign -= Subtract
and assign *= Multiply and assign /= Divide and
assign %= Remainder and assign **=
Exponent and assign //= Floor division and
assign
Logical and (Logical AND) or (Logical OR) not
(Logical NOT)
Bitwise & Bitwise AND | Bitwise OR ^ Bitwise XOR
(exclusive OR)
Shift << Shift left >> Shift right
Identity is (same identity?) is not (different identity?)
Membership in (present in sequence?) not in (absent from
sequence?)
6.3.5 Punctuators
Definition — Punctuators: Symbols used in programming languages to organise
the structure of programs, expressions and statements.
Common punctuators in Python:
' " # \ ( ) [ ] { } @ , : . ` =
6.4 Barebones of a Python Program
A Python program can contain the following components:
• Expressions
• Statements
• Comments
• Functions
• Blocks and Indentation
(i) Expressions
Definition — Expression: Any legal combination of symbols (variables, operators,
values) that represents a value. Python evaluates an expression and produces a
value.
Examples:
15 # expression (value only)
2.9 # expression (value only)
a + 5 # complex expression — produces a value when evaluated
(3 + 5) / 4 # complex expression — produces a value when evaluated
(ii) Statements
Definition — Statement: A programming instruction that does something (some
action takes place). Unlike expressions, a statement executes and may or may not
yield a value.
Examples:
a = 15 # assignment statement
b = a - 10 # assignment statement
print(a + 3) # function-call statement
if b > 5: # conditional statement
Key Difference — Expression vs Statement:
An expression is evaluated (produces a value).
A statement is executed (performs an action) and may or may not produce a value.
(iii) Comments
Definition — Comment: Additional readable information added to source code.
Comments are read by programmers but ignored by Python interpreter. In Python,
comments begin with the # (hash/pound) symbol.
Types of Comments:
• Full-line comment — entire line starts with #
• Inline comment — comment begins in the middle of a code line after Python code
• Multi-line comment — either multiple lines starting with # or a triple-quoted string
(docstring)
# This is a full-line comment
a = 15 # This is an inline comment
'''
This is a multi-line comment.
Also called a docstring.
'''
(iv) Functions
Definition — Function: A block of code that has a name and can be reused by
calling (specifying) its name wherever needed in the program.
def SeeYou(): # defining a function
print('Time to say Good Bye!')
SeeYou() # calling the function
(v) Blocks and Indentation
Definition — Block / Suite / Code-Block: A group of one or more statements that
are part of another statement or function, all written at the same indentation level.
Python uses indentation (whitespace at the beginning of lines) to define blocks, unlike other
languages that use curly brackets { }.
if b < 5: # colon marks start of block
print('b is small') # indent = 4 spaces
print('Thank you') # same block
print('Outside block') # no indent = outside the if block
Python Style Rules for Indentation:
• Use 4 spaces per indentation level (not tabs).
• All statements in the same block must have exactly the same indentation.
• Unnecessary indentation causes an IndentationError.
• Statements that require a block (if, for, while, def) must end with a colon (:).
Python Style Rules and Conventions
Convention Rule
Statement Termination No symbol needed. Pressing Enter ends a
statement.
Line Length Maximum 79 characters per line.
Indentation 4 spaces per level (not tabs).
Blank Lines 2 blank lines between top-level definitions; 1
between method definitions.
Multiple Statements Avoid putting multiple statements on one line
(though semicolon ; is allowed).
Case Sensitivity Python is case-sensitive. Age ≠ age ≠ AGE.
Docstrings Use triple double quotes (""" """) for documentation
strings.
Identifier Naming Use underscores: loan_amount OR CamelCase:
LoanAmount
6.5 Variables and Assignments
Definition — Variable: A named label in memory that refers to a value. The value
can be used and processed during program execution. Variables are called symbolic
variables because they are named labels.
Creating a variable is simple — just assign a value to a name:
marks = 70 # numeric variable
student = 'Jacob' # string variable
age = 16 # integer variable
balance = 23456.75 # float variable
Important — Python Variables Are NOT Storage Containers!
In most languages (C, C++, Java), a variable is a fixed memory container that stores
a value.
In Python, a variable is a LABEL that points to a location in memory where the value
is stored. When you reassign a variable, Python does not change the value in the
same location; it makes the label point to a new location.
6.5.1 Lvalues and Rvalues
Term Meaning
Lvalue (left-hand side) Expressions that can appear on the LEFT side of an
assignment. Variable names are lvalues.
Rvalue (right-hand side) Literals and expressions assigned to lvalues. They
appear on the RIGHT side of an assignment.
a = 28 # a is lvalue, 28 is rvalue ✓
b = 10 # b is lvalue, 10 is rvalue ✓
20 = a # ERROR! A literal cannot be on the left side
a * 2 = b # ERROR! An expression cannot be on the left side
6.5.2 Multiple Assignments
Python supports three handy styles of multiple assignment:
Style 1 — Same value to multiple variables:
a = b = c = 10 # all three variables refer to the value 10
Style 2 — Multiple values to multiple variables (in one line):
x, y, z = 10, 20, 30 # x=10, y=20, z=30
Style 3 — Swapping values (no temporary variable needed):
x, y = 25, 50
x, y = y, x # swap! Now x=50, y=25
print(x, y) # Output: 50 25
How Python evaluates multiple assignments:
Python FIRST evaluates all RHS expressions, THEN assigns them to LHS variables
(left to right).
6.5.3 Variable Definition
A variable is created (defined) only when a value is first assigned to it. Using a variable before
assigning a value to it causes a NameError.
print(x) # NameError: name 'x' is not defined
x = 20
print(x) # Output: 20
6.5.4 Dynamic Typing
Definition — Dynamic Typing: Python allows a variable to point to a value of one
type, and later be reassigned to point to a value of a completely different type. No
error is raised.
X = 10
print(X) # Output: 10
X = 'Hello World'
print(X) # Output: Hello World
# Check type with type() function:
type(X) # <class 'str'>
Dynamic Typing vs Static Typing:
Static Typing (C, C++): The data type of a variable is fixed at declaration time and
cannot change.
Dynamic Typing (Python): A variable can hold different types at different times.
Python determines the type at runtime.
⚠️Caution: Even though Python allows dynamic typing, the programmer is
responsible for using the correct type in each operation. Dividing a string is an error!
6.6 Simple Input and Output
6.6.1 Input — the input() Function
Definition — input() function: Built-in Python 3 function used to take input from the
user interactively. It always returns a value of String type.
Syntax:
variable_name = input(<prompt to display>)
Examples:
name = input('What is your name? ')
age = input('Enter your age: ')
⚠️ CRITICAL: input() ALWAYS Returns a String!
Even if the user types a number, input() returns it as a string.
So: age = input('Enter age: ') then age + 1 gives TypeError!
6.6.1A Reading Numbers (int and float conversion)
To read numeric values, wrap input() with int() or float():
# Reading an integer:
age = int(input('Enter your age: '))
# Reading a float:
marks = float(input('Enter marks: '))
# Or in two steps:
marks = input('Enter marks: ')
marks = float(marks)
Possible Errors when reading numbers:
If the user enters '17.5' for int(input()), Python raises ValueError (17.5 is not int-
compatible).
If the user enters 'Seventeen' for int(input()), Python raises ValueError.
Safe float inputs: 73, 73., .73 are all float-compatible and will be accepted.
6.6.2 Output — the print() Function
Definition — print() function: Built-in function used to send output to the standard
output device (usually the monitor/screen).
Syntax:
print(*objects, [sep=' ' or <separator-string>, end='\n' or <end-string>])
Simple examples:
print('hello') # Output: hello
print(17.5) # Output: 17.5
print('Sum of 2 and 3 is', 2+3) # Output: Sum of 2 and 3 is 5
a = 25
print('Double of', a, 'is', a*2) # Output: Double of 25 is 50
Features of the print() Function
Feature Explanation & Example
Auto-converts to string Numeric values are automatically converted to
strings before printing. Expressions are first
evaluated, then printed.
Default sep is space print() inserts a space between items by default.
print('My','name','is','Amit.') → My name is Amit.
Custom sep print('My','name','is', sep='...') → My...name...is
Default end is newline print() appends '\n' at the end, so the next print
starts on a new line.
Custom end print('Hello', end='$') — ends with $ instead of
newline
# Default behaviour (sep=' ', end='\n'):
print('My name is Amit.') # My name is Amit.
print('I am 16 years old') # I am 16 years old
# Custom sep:
print('My','name','is', sep='...') # My...name...is
# Custom end (print on same line):
a, b = 20, 30
print('a =', a, end=' ')
print('b =', b) # a = 20 b = 30 (on one line)
Quick Revision — Key Points
Chapter 6: Python Fundamentals — Summary
• A token is the smallest individual unit in a program.
• Python has 5 types of tokens: Keywords, Identifiers, Literals, Operators,
Punctuators.
• Keywords are reserved words with special meaning; they cannot be used as
identifiers.
• Identifiers are user-defined names; they are case-sensitive and must start with
a letter or underscore.
• Literals are fixed values: String, Numeric (int, float, complex), Boolean
(True/False), None.
• String literals can be single-line or multiline (triple-quoted).
• Escape sequences represent non-graphic characters inside strings (e.g., \n =
newline).
• Operators trigger computation; Punctuators organise program structure.
• An expression represents a value; a statement performs an action.
• Comments (begin with #) are ignored by the interpreter.
• A block/suite is a group of statements at the same indentation level.
• Python uses 4-space indentation to define blocks (not curly braces).
• A variable is a named label pointing to a value in memory.
• Python supports Dynamic Typing — a variable can hold different types at
different times.
• A variable is defined only when a value is first assigned to it.
• input() always returns a String; use int() or float() to convert numeric input.
• print() outputs to the screen; sep controls separator, end controls line ending.
Practice Questions
Section A — Multiple Choice Questions (MCQ)
8. Which of the following is a valid Python identifier?
(a) 2data (b) data_2 (c) data-2 (d) class
Answer: (b) data_2
9. Which of the following is NOT a Python keyword?
(a) True (b) false (c) None (d) pass
Answer: (b) false (Python keywords are case-sensitive; 'false' is not a
keyword)
10. What does the input() function always return?
(a) int (b) float (c) str (d) depends on what user types
Answer: (c) str — input() always returns a String value
11. What is the default value of the 'end' argument in Python's print() function?
(a) '' (empty) (b) ' ' (space) (c) '\n' (newline) (d) None
Answer: (c) '\n' — print() appends a newline at the end by default
12. Which of the following is an invalid octal integer?
(a) 0o17 (b) 0o28 (c) 0o77 (d) 0o10
Answer: (b) 0o28 — octal digits can only be 0–7; 8 and 9 are invalid
Section B — Short Answer Questions
13. What is a token? Name all five types of tokens in Python.
14. Differentiate between a keyword and an identifier. Give two examples of each.
15. What is an escape sequence? Why are escape sequences needed? Give three
examples.
16. What are the two types of string literals in Python? How do you create a multiline string?
17. Differentiate between an expression and a statement with suitable examples.
18. What are comments in Python? How many types of comments can you create?
19. What is a block or suite in Python? How is indentation used to define blocks?
20. What is dynamic typing? How is it different from static typing?
21. What will happen if you use a variable before assigning a value to it?
22. Explain the sep and end arguments of the print() function with examples.
Section C — Programming Questions
23. Write a Python program to input your name and age, then print: Hello <name>, you are
<age> years old.
24. Write a Python program to input two numbers and print their sum, difference, product,
and quotient.
25. Write a Python program to input the radius of a circle and calculate its area. (Area =
3.14159 × r²)
26. Write a Python program to input a person's weight (kg) and height (metres) and
calculate their BMI. (BMI = weight / height²)
27. Write a Python program to input three numbers and swap them: first becomes second,
second becomes third, third becomes first.
28. Write a Python program to input a distance in kilometres and convert it to miles. (1 km =
0.621371 miles)
29. Write a Python program to input a value in tonnes and print its equivalent in quintals and
kilograms. (1 tonne = 10 quintals = 1000 kg)
30. Write a Python program to input a number and print its square and cube.
Section D — True or False
31. Python is a case-sensitive language. (True / False)
32. An identifier can start with a digit. (True / False)
33. The input() function can return an integer directly. (True / False)
34. True and False are Python keywords. (True / False)
35. Comments in Python begin with the @ symbol. (True / False)
36. Python uses curly brackets { } to define blocks of code. (True / False)
37. None is a special literal in Python that represents absence of a value. (True / False)
38. Dynamic typing means a variable can hold values of different types at different times.
(True / False)
Answers (True/False):
1-True 2-False 3-False 4-True 5-False 6-False 7-True 8-True
End of Chapter 6 — Python Fundamentals Study Notes