Unit 2 - TCS-102 Notes
Unit 2 - TCS-102 Notes
Comments
Programming reflects programmer’s way of thinking in order to describe the single step’s that were followed
to solve a problem using a Computer. Commenting helps the programmers to explain the thought process
involved, and helps the programmer and others to understand the intention of the code. This allows one to
easily find errors, to fix them, to improve the code later on, and to reuse it in other applications as well.
• Single line Comment: Single line Comment(s) in Python are written starting with # (hash)
character
# Program to read two numbers and
# display it to the screen
Y=25//2 # finds the integer division
• Multiline Comments: Single line Comment(s) in Python are written in """ quotes.
"""
Write a Python Program to read two numbers and display the remainder to the screen after dividing the
first number by second.
"""
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier. They are used to define
the syntax and structure of the Python language.
Python Variables
• Creating Variables
Unlike other programming languages, Python has no command for declaring a variable. A variable is created
the moment you first assign a value to it.
x=5
y = "John"
print(x) #5
print(y) #John
▪ Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
i)
x = "Python"
ver="3.10.5"
print("Version of “ + x +” is "+ ver))
Output: Version of Python is 3.10.5
ii)
x = "Python is "
y = "awesome"
z=x+y
print(z)
O/P: Python is awesome
iii)
x=5
y = "John"
print(x + y)
O/P: TypeError: unsupported operand type(s) for +: 'int' and 'str
iv)
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
O/P:
5
3.2
Hello
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
x=1
print(type(x)) # int
y = 2.8
print(type(x)) # float
z = 1j
print(type(x)) # complex
int
x=1
y = 35656222554887711
z = -3255522
float
x = 1.10
y = 1.0
z = -35.59
x = 35e3 is equivalent of 35×103
y = 12E4 is equivalent of 12×104
z = -87.7e100 is equivalent of 87.7×10 100
Complex
x = 3+5j
print(x) => 3+5j
print(x.real) => 3.0
print(x.imag) => 5.0
y = 5j
print(y.real) => 0.0
print(y.imag) => 5.0
z = -5j
print(z.real) => 0.0
print(x.imag) => -5.0
Python Casting
Sometimes you may need to assign a specific type to a variable. This process is called casting. Since Python
is an object-oriented language, it uses classes to define data types—even for its basic types.
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by rounding down to the
previous whole number), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal (providing
the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is
the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode
characters. However, Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
O/P: e
Strings are immutable
In Python, strings are immutable, which means:
• Once a string object is created, its contents cannot be changed.
• Any operation that looks like it’s modifying a string (e.g., concatenation, replace, slicing
assignment) actually creates a new string object in memory.
Example:
s = "hello"
print(id(s)) # prints the memory address of "hello"
s = s + " world"
print(s) # "hello world"
print(id(s)) # prints different memory address i.e. of new string s
Slicing:
Extracting a Substring from the existing string by specifying the index.
Slicing syntax
string[ start : end : step]
• start → index where slicing begins (default = 0)
• end → index where slicing stops (exclusive)
• step → interval (default = 1)
Examples:
s = "Python Programming"
1. Basic slicing
print(s[0:6]) # Output: Python (from index 0 to 5)
print(s[:6]) # Output: Python (start default = 0)
print(s[7:]) # Output: Programming (till end)
2. Negative indexing
print(s[-11:-1]) # Output: Programmin (counting from end)
print(s[-7:]) # Output: mming
3. Using step
print(s[::2]) # Output: Pto rgamn (every 2nd char)
print(s[1::2]) # Output: yhnPormig (every 2nd char starting at index 1)
4. Reversing a string
print(s[::-1]) # Output: gnim margorP nohtyP
5. Extracting substrings
print(s[0:6]) # "Python"
print(s[7:18]) # "Programming"
Length of a string:
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))
print statement:
A statement is a unit of code that the Python interpreter can execute. print is an executable statement. When
print statement is typed in interactive mode, the interpreter executes it and displays the result, if there is one.
Ex.
name = "Prashant"
age = 25
print(f"My name is {name} and I am {age} years old.")
or
print("My name is {} and I am {} years old.".format(name, age))
or
print("My name is %s and I am %d years old." % (name, age))
In above cases the output remains the same.
#Output: My name is Prashant and I am 25 years old.
Ex. ff=56.78943
print("Value of ff is %0.2f" % (ff))
#Output: Value of ff is 56.79
Ex. A string can be passed to be displayed to the user before pausing for input:
name = input('What is your name?\n') # “Kiran” is passed as input
print(name)
O/P: Kiran
Ex.. Two add two numbers by accepting from the user
num1=input(‘Enter the first number:’)
num2=input(‘Enter the second number:’)
sum =int(num1)+int(num2)
print(‘The sum is :’ , sum)
Ex
x = "Python"
ver="3.10.5"
print("Version of {} is {} ".format(x , ver))
Output: Version of Python is 3.10.5
Ex
x=10
y=78.976467
print(f”{x} , {y:0.2f}”)
O/P: 10 , 78.98
Python Operators
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
1. Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Opera Name Example
tor
+ 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
== Equal x == y
!= Not equal x != y
not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true
Evaluation of Logical Expressions
Python processes a logical expression such as x >= 2 and (x/y) > 2, by evaluating the expression from left to
right. When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it
stops its evaluation and does not do the computations in the rest of the logical expression. When the evaluation
of a logical stops because the overall value is already known, it is called short-circuiting the evaluation.
The short-circuit behaviour leads to a clever technique called the guardian pattern. Consider the following
code sequence in the Python interpreter:
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
O/P: True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
O/P: False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
5. Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z) # returns True because z is the same object as x
print(x is y) # returns False because x is not the same object as y, even if they have thew same content
print(x == y) # to demonstrate the difference betweeen "is" and "==": this comparison returns True
because x is equal to y
O/P:
True
False
True
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z) # returns False because z is the same object as x
print(x is not y) # returns True because x is not the same object as y, even if they have the same content
print(x != y) # to demonstrate the difference between "is not" and "!=": this comparison returns False
because x is equal to y
O/P:
False
True
False
x = ["apple", "banana"]
print("banana" in x) # returns True because a sequence with the value "banana" is in the list
O/P: True
x = ["apple", "banana"]
print("pineapple" not in x) # returns True because a sequence with the value "pineapple" is not in the
list
O/P: True
7. Bitwise Operators
• These operators are used to perform logical operation (and, or, not) on individual bits of a binary
number.
The boolean expression after the if statement is called the condition. The if statement with a
colon character (:) and the line(s) after the if statement are indented (as indicated by the arrow
tab spacing).
The statement consists of a header line that ends with the colon character (:) followed by an
indented block. These statements are called compound statements because they stretch across
more than one line.
There is no limit on the number of statements that can appear in the body, but there must be at
least one. If body has no statements, then pass statement may be used, which does nothing.
For Example:
x=100
if x>99:
x=x+500
if x < 101 and x>99:
y=x+100
x=x-50
x=x+y
print(x)
OUTPUT:
600
Alternative Execution
A second form of if statement is alternative execution, in which there are two possibilities
and the condition determines which one gets executed. The syntax looks like this:
if x%2 == 0:
print('x is even')
else:
print('x is odd')
Ex. Write a program in python to accept an integer from the user and determine whether its
even or odd.
Solution:
num=input('Input a number:') num=int(num)
if(num!=0):
if num%2!=0:
print(num,'is an Odd number')
else:
print(num,'is an Even number')
elif is an abbreviation of “else if”. There is no limit on the number of elif statements.
Example:
Write a program in python to accept an integer from the user and determine whether its
positive, negative or zero.
Solution:
num=input('Input a number:') num=int(num)
if num >0:
print(num,' is a positive number')
elif num<0:
print(num,’ is a negative number')
else:
print(num,’ is zero')
Match-case
What is Match-Case?
Syntax:
match value:
case pattern1:
# Code to execute if value matches pattern1
case pattern2:
# Code to execute if value matches pattern2
case _:
# Default case (if no patterns match)
# Default case (if no patterns match)
Example:
status = 404
match status:
case 200:
print("Success!")
case 404:
print("Not Found")
case _:
print(“Unknown Status”)
Python Loops
Python has two primitive loop commands:
1. while loop:
Syntax for while loop:
while (expression):
statement(s)
2. for loop:
Syntax:
for variable_name in sequence:
Statement(s)
Example:
S= “Hello”
for i in S:
print(i)
Output:
H
e
l
l
o
range function:
Syntax:
range(start, stop, step)
where The start and step arguments are optional.
Example1:
# create a sequence from 0 to 3 (4 is not included)
for i in range(4):
print(i)
Output:
0
1
2
3
Example2:
for i in range(1,5):
print(i)
Output:
1
2
3
4
Example3:
for i in range(1,10,2):
print(i)
Output:
1
3
5
7
9
break statement: break statement is used to exit a loop based on certain condition.
for i in range(10):
print(i)
if i == 2:
break
Output:
0
1
2
Continue statement: The continue statement skips the current iteration of the loop and the
control flow of the program goes to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
pass statement: The Python pass statement is a null statement. But the difference between
pass and comment is that comment is ignored by the interpreter whereas pass is not ignored.
n = 10
for i in range(n):
pass
Built-in functions
In the context of programming, a function is a set statements grouped under a name that
performs a specific task. When a function is defined, first name is specified and then the set or
sequence of statements. Function is called by its name.
type(32)
O/P: <class 'int'>
The name of the function is type(). The expression in parentheses is called the argument of the
function. The argument is a value or variable that we are passing into the function as input to
the function. The result, for the type function, is the type of the argument. The result sent back
by the function is called the return value.
The max() and min() functions give us the largest and smallest values in a list, respectively:
print ( max('Hello world') )
O/P: 'w'
print ( min('Hello world') )
O/P: ' '
The max() function tells us the “largest character” in the string (which turns out to be the letter
“w”) and the min() function shows us the smallest character (which turns out to be a space).
A very common built-in function is the len() function which tells how many items are in its
argument. If the argument to len() is a string, it returns the number of characters in the string.
print(len('Hello world'))
O/P: 11
int(-2.3)
O/P: -2
Rounds by chopping the fractional part.
Creating a Function
In Python a function is defined using the def keyword:
EXAMPLE:
# A simple Python function
def fun():
print("Welcome to Graphic Era")
FUNCTION SYNTAX
1. Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function.
EXAMPLE:
# Defining function print_str(str1)
#This function prints the string being passed as an argument
def print_str(str1):
print(str1)
return
2. Parameters in function
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters separated by comma.
Example 1: # A simple Python function to check whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
Example 4: #Count all letters, digits, and special symbols from a given string
def find_digits_chars_symbols(sample_str):
chr_count = 0
digit_count = 0
symbol_count = 0
for chr in sample_str:
if chr.isalpha():
chr_count += 1
elif chr.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1
print("Chars =", chr_count, "Digits =", digit_count, "Symbol =", symbol_count)
sample_str = "Gra@phic2Era&#Hi5ll@univer&$sity"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)
Output:
Enter first number: 5
Enter second number: 6
Sum of 5 and 6 is 11 and multiplication is 30
• All functions in Python have a return value, even if no return line inside the code
• Functions without a return return the special value None
• None is a special constant in the language
• None is used like NULL, void, or nil in other languages
• None is also logically equivalent to False
• The interpreter’s REPL(Read-Eval-Print loops) doesn’t print None
Types of Arguments:
1. Positional Arguments
def greet(name="Guest"):
return f"Hello, {name}!"
def student(name, age):
print(f"Name: {name},
print(greet()) Age:
# Output: {age}")
Hello, Guest!
student(age=20, name="Bob")
3. Keyword Arguments
Syntax:
square = lambda x: x * x
print(square(4)) # Output: 16
Recursion in Python
Built-in modules
1. random module
Given the same inputs, most computer programs generate the same outputs every time, so they
are said to be deterministic. In determinism, it’s expected that the same calculation yield’s the
same result. For some applications, though, the computer needs to be unpredictable. Games are
an obvious example, but there are more.
The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0).
Each time random is called, the next number is generated in a long series. The following
program produces the following list of 10 random numbers between 0.0 and up to but not
including 1.0:
import random
for i in range(10):
x = random.random()
print(x)
The function randint takes the parameters low and high, and returns an integer between low
and high (including both).
random.randint(5, 10)
O/P: 5
random.randint(5, 10)
O/P: 9
random.choice(t)
O/P: 3
2. math module
Python has a math module that provides most of the familiar mathematical functions. Before
using the module, it must be imported:
import math
This statement creates a module object named math. If you print the module object, you get
some information about it:
print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To access one
of the functions, specify the name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
ratio = signal_power/noise_power
decibels = 10 * math.log10(ratio)
radians = 0.7
height = math.sin(radians)
The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module
also provides a function called log that computes logarithms base e. The second example finds
the sine of radians. The name of the variable is a hint that sin and the other trigonometric
functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide
by 360 and multiply by 2:
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
math.sin(radians)
O/P: 0.7071067811865476
The expression math.pi gets the variable pi from the math module. The value of this variable
is an approximation of pi, accurate to about 15 digits.
Custom Modules
You can create your own modules by saving Python code in a .py file. You can then import
and use them in other scripts.
# mymodule.py
def greet(name):
return f"Hello, {name}! Welcome to Python modules."
pi = 3.14159
# main.py
import mymodule # importing our custom module
Output:
Hello, Alice! Welcome to Python modules.
Sum of 5 and 7 is: 12
Value of pi is: 3.14159
• try-except block: Code that might raise an exception is placed in the try block. If an
exception occurs, the code in the corresponding except block is executed.
• finally block: This block is always executed, whether an exception occurred or not.
Example:
try:
num = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("This code always runs.")