Python Notes 4th Sem AKTU
Python Notes 4th Sem AKTU
Introduction
Python was created by Guido Van Rossum
The language was released in February I991.
Python got its name from a BBC comedy series from seventies- “Monty Python’s Flying
Circus”.
Python can be used to follow both Procedural approach and Object Oriented approach of
programming.
It is free to use.
Tokens
In a passage of text, individual words and punctuation marks are called tokens or lexical units or
lexical elements. The smallest individual unit in a program is known as Tokens.
Python has following tokens:
Keywords
Identifiers (Name)
Literals
Operators
Punctuators
Keywords
Keywords are the reserved words and have special meaning for python interpreter. Every keyword
is assigned specific work and it can be used only for that purpose.
or A logical operator used when either one of the conditions needs to be true
Identifier
Python Identifier is the names given to different parts of program like variables, objects, classes,
functions etc.
Identifier forming rules of Python are:
Is an arbitrarily long sequence of letters and digits.
The first character must be letter or underscore
Upper and lower case are different
The digits 0-9 are allowed except for first character
It must not be a keyword
No special characters are allowed other than underscore is allowed.
Space not allowed
Literals
When speaking of literals in Python, they refer to fixed constant values that are assigned to
variables or used directly in expressions. The constant values are of varying types, such
as numbers, strings, Booleans, collections, or other special identifiers. Unlike the variables above,
literals are immutable, which means they cannot be changed after being defined.
Literals in Python are the building blocks of a program. They are fixed, unchangeable values
of a specific data type. We encode literals directly into the script. In simple terms, Python
literals are static data stored within the source code.
Literals are self-explanatory, and we don’t need to evaluate them. While variables are
containers storing values that can be changed, literals are constant data elements. We use
them directly in expressions to designate data that can’t be modified, such as data
specifying the software's operating parameters.
Example
1. x = 10 # Integer literal
2. print(x)
Numeric Literals
Numeric literals are values that can be represented in Python, as their names suggest. They can be
assigned different values and are further described in three categories:
a) Integer (int)
Integer literals are defined as whole numbers without any decimals. They can be negative, positive or zero.
Python also allows the use of various formats of integer literals.
1. Decimal (Base 10): Uses digits 0-9 (e.g., 100, -5, 0).
2. Binary (Base 2): Prefixed with 0b or 0B (e.g., 0b1010 for decimal 10).
3. Octal (Base 8): Prefixed with 0o or 0O (e.g., 0o12 for decimal 10).
4. Hexadecimal (Base 16): Prefixed with 0x or 0X (e.g., 0xA for decimal 10).
Example
1. integer_num = 10 # Decimal integer
2. binary_num = 0b1010 # Binary integer
3. octal_num = 0o12 # Octal integer
4. hexadecimal_num = 0xA # Hexadecimal integer
5. print(integer_num)
6. print(binary_num)
7. print(octal_num)
8. print(hexadecimal_num)
Execute Now
Output:
10
10
10
10
In the above example, we have initialized multiple variables using different forms of integer literal and
printed their values.
b) Floating-Point (float)
Floating-point literals represent numbers that contain a decimal point or are written in scientific notation.
They are used for precise calculations involving fractions or real numbers.
Example
1. float_num = 20.5 # Standard floating-point number
2. scientific_num = 2.5e3 # Equivalent to 2500.0
3. negative_float = -0.99 # Negative floating-point number
4. print(float_num)
5. print(scientific_num)
6. print(negative_float)
Execute Now
Output:
20.5
2500.0
-0.99
In the above example, we have initialized multiple variables using different floating-point literals and
printed their values.
2. String Literals
String literals in Python are sequences of characters enclosed in either single (' '), double (" "), or triple (''' '''
or """ """) quotes. They are used to store text data, including words, sentences, or even multi-line
paragraphs.
a) Single-Line Strings
These are enclosed within single or double quotes and are used for short textual data.
Example
1. single_string = 'Hello' # Single-quoted string
2. double_string = "Python" # Double-quoted string
3. print(single_string)
4. print(double_string)
Output:
Hello
Python
In the above example, we have initialized multiple variables using different format of single-line string
literal and printed their values.
b) Multi-Line Strings
Multi-line strings are enclosed within triple single (''' ''') or triple-double (""" """) quotes. They are used
when the text spans multiple lines, such as documentation or large text blocks.
Example
1. # multi-line string
2. multi_string = """This is a multi-line string.
3. It can span multiple lines.
4. Useful for documentation and long texts."""
5. print(multi_string)
Execute Now
Output:
o \n - Newline
o \t - Tab
o \' - Single quote
o \" - Double quote
o \\ - Backslash
Example
1. escaped_string = 'Hello\nWorld' # Inserts a new line
2. print(escaped_string)
Execute Now
Output:
Hello
World
In the above example, we have initialized a multi-line string literal and printed its value.
Example
1. string1 = "Hello "
2. string2 = "World"
3. concatenated = string1 + string2 # "Hello World"
4. repeated = string1 * 3 # "Hello Hello Hello"
5. print(concatenated)
6. print(repeated)
Execute Now
Output:
Hello World
Hello Hello Hello
In the above example, we have initialized two strings and then performed operations like concatenation
and repetition.
3. Boolean Literals
Boolean literals represent truth values in Python. There are only two Boolean literals:
1. True
2. False
Example
1. is_python_fun = True # Boolean literal
2. is_raining = False
3. print(is_python_fun)
4. print(is_raining)
Execute Now
Output:
True
False
In the above example, we have initialized and printed two variables with Boolean values.
4. Collection Literals
Collection literals represent groupings of values and include the following types:
Example
1. list_literal = [10, 20, 30] # List literal
2. tuple_literal = (10, 20, 30) # Tuple literal
3. dict_literal = {'a': 1, 'b': 2} # Dictionary literal
4. set_literal = {10, 20, 30} # Set literal
5. print(list_literal)
6. print(tuple_literal)
7. print(dict_literal)
8. print(set_literal)
Execute Now
Output:
5. Special Literal
Python has a special literal called None, which represents the absence of a value.
When we print a variable without assigning it a value, it returns None as output. If we compare None with anything, it
returns False. We use None at the end of a Python list.
Example
1. val = None
2. print(val)
Output:
None
Python Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
:= print(x := 3) x=3
print(x)
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result not(x < 5 and x <
is true 10)
<< Zero fill Shift left by pushing zeros in from the right x << 2
left shift and let the leftmost bits fall off
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Example
Print the data type of the variable x:
x = 5
print(type(x))
Output:
<Class ‘int’>
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = None NoneType
Unit2
(Python Program Flow Control Conditional
blocks)
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and
loops.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen that "a
is greater than b".
Example
a = 200
b = 33
if b > a:
print ("b is greater than a")
else:
print ("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example
One line if statement:
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Example
a = 33
b = 200
if b > a:
pass
For Loop
A for loop in Python is a control flow statement that is used to repeatedly
execute a group of statements as long as the condition is satisfied.
Example
a=10
for i in range(a):
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output:
b
a
n
a
n
a
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
Example
Create a Tuple:
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Example
Print each fruit in a fruit list:
The for loop does not require an indexing variable to set beforehand.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Mutable (Unchangeable)
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Output:
Example
String, int and boolean data types:
Output:
Example
Print the second item in the tuple:
Example
Exit the loop when x is "banana":
Example
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
Example
Do not print banana:
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Example
Using the start parameter:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")