Python Fundamentals Chapter - 6
Python Character Set
Letters A-Z, a-z
Digits 0-9
Special symbols space + - * / ** \ ( ) [ ] { } // = != == < , > . ‘ “ ‘” ; : % ! & # <= >= @ _
Whitespace Blank space, tabs ( ), carriage return (↵), newline, formfeed.
Other characters Python can process all ASCII and Unicode characters
Tokens
The smallest individual unit in a program is known as a Token or a lexical unit .
Example
Python has following tokens :
i. Keywords ii. Identifiers (Names) iii. Literals
iv. Operators v. Punctuators
i. Keywords
A keyword is a word having special meaning reserved by programming language .
Python programming language contains following keywords :
False assert del for in or while
None break elif from is pass with
True class else global lambda raise yield
and continue except if nonlocal return as
def finally import not try
ii . Identifiers (Names)
• Identifiers are the names given to different parts of a program such as variables,
objects, classes, functions, lists, and dictionaries.
1. An identifier is an arbitrarily long sequence of letters and digits.
2. The first character of an identifier must always be a letter or an underscore ( _ ).
3. Uppercase and lowercase letters are treated as different (Python is case-sensitive). For
example, MyFile and myfile are two different identifiers.
4. Digits 0 to 9 can be used in identifiers, but not as the first character.
5. An identifier must not be a keyword of Python (example: break, class, etc.).
6. Special characters are not allowed in identifiers except the underscore ( _ ).
7. Therefore, valid identifiers can include letters, digits, and underscores, but cannot start
with a digit and cannot contain spaces or special symbols like @, #, -, or ..
Examples of valid identifiers:
Myfile, MYFILE, CHK, Z27OZ9, DATE9_7_77, _DS, FILE13, HJ13_JK
Examples of invalid identifiers:
DATA-REC → invalid because it contains a hyphen (-)
29CLCT → invalid because it starts with a digit
break → invalid because it is a reserved keyword
My.file → invalid because it contains a special character (.)
iii . Literals / Values
• Literals (or constant values) are fixed values that are used in programs.
• Python allows different kinds of literals:
A. String literals
B. Numeric literals
C. Boolean literals
D. Special Literal
E. Literal Collections
DA String literals
A string literal in Python is a sequence of characters enclosed in quotes.
Examples:
Single character: 'a', "b"
Multiple characters: 'abc', "xyz"
String Types in Python
Python allows two types of strings:
Single-line Strings
E.g: Text1 = 'Hello'
Multiline Strings
E.g: Text3 = '''Hello
there
Python'''
Escape Sequences in Python
• An escape sequence begins with a backslash ( \ ) followed by one or more characters.
Escape Sequence What it does
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (Beep sound)
\b ASCII Backspace
\f ASCII Formfeed
\n New line
\t Horizontal Tab
\r Carriage Return
\v Vertical Tab
\ooo Character with octal value
\xhh Character with hex value
\uxxxx Unicode character (16-bit)
\Uxxxxxxxx Unicode character (32-bit)
\N{name} Unicode character by name
Size of Strings
• The size of a string = number of characters in the string.
• Python counts escape sequences (\n, \t, \\, etc.) as one character.
Examples:
'\\' → size is 1 (Because \\ represents one backslash \)
'abc' → size is 3
"\ab“ → size is 2 (\a is counted as one )
“Ram\'s pen" → size is 8 (\' is counted as one ')
"Amy's" → size is 5 (No escape needed since ' is inside double quotes)
Note : We use len (<object name>) to get the size or length of an object .
E.g: str1 = ‘\\’
print( len (str1)) # out put is 1
B. Numeric literals
• Python has three types of numeric literals:
(i) int (signed integers)
• Positive or negative whole numbers.
• Example: 5, -10, 1000
(ii) float (floating-point real values)
• Real numbers with a decimal point.
• Example: 3.14, -0.75, 2.0
(iii) complex (complex numbers)
• Form: a + bj (where a and b are floats, and j = √-1).
• a = real part, b = imaginary part.
• Example: 3+4j, -2.5+1.5j
(i) Integer Literals
• Whole numbers without any fractional part.
• Must have at least one digit and cannot contain commas.
• May have a + or - sign.
Types of Integer Literals in Python:
a) Decimal Integer Literals
• Standard integers (base 10).
• Example: 1234, 41, -97.
b) Octal Integer Literals
• Start with 0o (digit 0 followed by letter o).
• Digits allowed: 0–7.
• Example: 0o10 = 8 in decimal (10 8 = 8 10) , 0o14 = 12.
• Invalid if contains 8 or 9 (e.g., 0o28, 0o19).
c) Hexadecimal Integer Literals
• Start with 0x or 0X.
• Digits allowed: 0–9 and A–F.
• Example: 0xC =12 in decimal
(ii) Floating Point Literals
• Numbers having decimal point.
• Can be written in two forms:
A. Fractional Form
• Valid Example: 2.0, 1.75, -1.30, -0.026, 0.3
• Invalid examples: 7 , 17/2 , 17.250.26 , 17,250.262
B. Exponent Form
• Written as: mantissa E exponent
• Mantissa = real number (5.8)
• Exponent = integer (10² )
• Example: 5.8E02 → 5.8 × 10² = 580.0
0.58E-01 → 0.58 × 10⁻¹ = 0.058
5.8 0.58 × 10¹ = 0.58E01
Q. Value 0.000615 is equivalent to
Ans: 0.000615 = 6.15 × 10⁻⁴ = 6.15E-4
0.615 × 10⁻³ = 0.615E-3
C. Boolean Literals
• Only two Boolean literals exist in Python: True and False.
D. Special Literal None
• Python has one special literal: None.
• Represents absence of a value (similar to “nothing” or “no useful information”).
Example
Value1 = 10
Value2 = None
Value1 # outputs 10
Value2 # outputs nothing (blank)
print(Value2) # prints None
iv. Operators
• Operators are tokens that trigger some computation and are applied to variables and
other objects in an expression.
Unary Operators
• Need only one operand.
+ (Unary plus) → +5 = 5 ~ (Bitwise complement) → flips bits
- (Unary minus) → -5 = -5 not (Logical negation)
Binary Operators
• Need two operands.
(a) Arithmetic Operators
+ (Addition) / (Division → result is float) // (Floor division →
- (Subtraction) % (Modulus → remainder) integer quotient)
* (Multiplication) ** (Exponent → power)
(b) Bitwise Operators
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
(c) Shift Operators
<< (Left shift)
>> (Right shift)
(d) Identity Operators
Is → checks if two references point to same object
is not → checks if they do not point to same object
(e) Relational Operators
< Less than >= Greater than or equal to
> Greater than == Equal to
<= Less than or equal to != Not equal to
(f) Logical Operators
and (Logical AND)
or (Logical OR)
not (Logical NOT)
(g) Membership Operators
in (Checks if element is in a sequence)
not in (Checks if element is not in a sequence)
v. Punctuators
Punctuators are symbols to organize sentences, groups of words, phrases, and program
statements.
Common Punctuators in Python are : ' ‘’ \ @ ( ) [ ] { } : , ; . = #
Barebones of a Python Program
# this is a program ← Comment
def see(): ← Function definition
print("Bye") ← Statement inside function
# Main program ← Comment
A = 15 ← Statement (Expression: 15)
B=5 ← Statement (Expression: 5)
print(A + B) ← Statement (Expression: A + B)
if B == 5: ← Conditional Statement (Expression: B==5)
print("This is 5") ← Block (Indented Statement)
else:
print("Not") ← Block (Indented Statement)
see() ← Function Call
A Python program usually contains:
I. Expressions
II. Statements
III. Comments
IV. Functions
V. Blocks & Indentation
I. Expressions
• An expression is any legal combination of symbols that represents a value.
• Simple values: 15, 2.9
• Above sample code expressions are : 15, 5, A+B, B==5
ii. Statements
• A statement is a programming instruction that performs an action.
• Examples of statements from above code: a = 15
b=5
print(a + 3)
if b == 5:
III. Comments
• Comments are the additional readable information to clarify the source code.
• Comments in Python begin with # and generally end with the end of the physical line.
Types of Comments
Full Line Comments
• Begin with # at the start of the line.
Inline Comments
• Start with # in the middle of a statement.
Multi-line Comments
• For Multi-line Comments we Use triple quotes (''' or """) or triple apostrophe (‘ ‘ ‘) are
called docstrings.
IV. Functions
• A function is a code that has a name and it can be reused by specifying its name in the
program where needed.
• Example: def see():
V. Blocks & Indentation
• A group of statements which are part of another statement or a function are called
black or code block.
• Example: if B==5:
print(“This is 5”)
Variables and Assignments
• Named labels, whose values can be used and processed during program run, are called
Variables.
• Syntax: variable_name = value
• E.g: marks = 70 (Here, marks is a variable storing numeric value 70.)
• Creating a Variable : marks = 70 # numeric variable
student = "Jacob" # string variable
Important: Variables are NOT Storage Containers in Python
• In most programming languages (C, C++, Java), variables are treated as containers that
store values.
• But in Python variables are just names (labels) that refer to objects in memory.
• Example:age = 15
age = 20
In Python:
First, age refers to the value 15.
Then, age is re-assigned to point to the value 20.
Python variables don’t store values inside them; they just point to objects.
Lvalues and Rvalues
Lvalue (Left value):
• Refers to a memory location (variable).
• Example: a = 20
b = 10
Rvalue (Right value):
• They are literals or expressions.
• Example: x = 10 + 5 # 10+5 is an Rvalue
❌ You cannot write:
10 = b # Error
a*2=b # Error
Multiple Assignments
(a) Assigning Same Value to Multiple Variables
a = b = c = 10
(b) Assigning Multiple Values to Multiple Variables
x, y, z = 10, 20, 30
print(x, y, z) #Output:10 20 30
(c) Assignment with Expressions
a, b, c = 5, 10, 7
a, b, c = a + 1, b + 2, c + 1
print(a, b, c) # Output: 6 12 8
Dynamic Typing
A variable pointing to a value of a certain type, can be made to point to a value/object of
different type. This is called Dynamic Typing.
Example:
x = 10
print(x) #output : 10
x = "Hello World"
print(x) #output: Hello World
Caution with Dynamic Typing
x = 10
y=2
x=x/y # legal, because two integers can be used in divide operation
x = "Day" # Python is comfortable with dynamic typing
x=x/y # ERROR!! a string cannot be divided
Finding the type of a variable
• Use type() function:
• type(variable_name)
• Example: A="Hello"
print(type(A)) #Output : <class 'str'>
Simple Input and Output
• In Python to get input from the user interactively, you can use built-in function input().
• variable = input(<prompt to be displayed>)
• Example: name = input('What is your name ? ')
Reading Numbers
• The function input() returns the input value in string type.
• Int() and float() to be used with input() to convert int and float type.
Output through print() function
• For output we use print() function.
Features of print() function
• print("Hello", "World") #Hello World
• print("Hello", "World", sep='…') # Hello…World
• print("Hello", "World", end='$') # Output : Hello World$
• a,b=10,20
print("a=",a,"b=",b, end=' ') # Output : a= 10 b= 20