lOMoARcPSD|61993372
Python Programming Unit I - Complete Notes
[Link](Computer Science) (Thiruvalluvar University)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
PYTHON PROGRAMMING
UNIT I
INTRODUCTION
What is Python?
Python is a general-purpose, interpreted, interactive, object-oriented and
high-level Programming language.
Python source code is available under the General Public License (GPL)
and it is now maintained by a core development team at the National
Research Institute.
Who developed Python?
Python was developed by Guido van Rossum at the National Research
Institute for Computer Science in Netherlands during 1985-1990.
Python is derived from many other language including ABC, C, C++,
ALGOL-68, SmallTalk, Unix and other scripting languages.
Rossum was inspired by Monty Python's Flying Circus. Hence he named it
Python.
Features of Python
Simple and easy-to-learn
Interpreted and Interactive
Object-Oriented
Portable
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Scalable
GUI Programming Support
Dynamic
Free and Open Source
Broad Standard Library
Simple and easy-to-learn
Python is a simple language with few keywords, simple structure and its
syntax is also clearly defined.
This makes Python a beginner's language.
Interpreted and interactive
Python is processed at runtime by the interpreter.
We need not compile the program before executing it.
The Python prompt interact with the interpreter to interpret the programs that
you have written.
Object-Oriented
Python supports Object Oriented Programming (OOP) concepts.
All concepts in OOPs like data hiding, inheritance , polymorphism etc
can be well written in Python.
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Portable
Python can run on a wide variety of hardware and software platforms
and has the same interface on all platforms.
All variants of Windows, Unix, Linux and Macintosh are to name a few.
Scalable
Python provides a better structure and support for large programs.
It can be used as a scripting language or can be compiled to bytecode
(intermediate code that is platform independent) for building large
applications.
GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5,
PyQt4, wxPython, or Tk in Python.
PyQt5 is the most popular option for creating graphical apps with Python.
Dynamic
Python provides very high-level dynamic data types and supports dynamic
type checking.
It also supports automatic garbage collection.
Free and Open Source
Python language is freely available at the official website.
Since it is open-source, this means that source code is also available to the
public. So you can download it, use it as well as share it.
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Broad Standard Library
Python's library is portable and cross platform compatible on UNIX,
Linux, Windows and Macintosh.
This helps in the support and development of a wide range of applications
from simple text processing to browsers and complex games.
IDENTIFIERS
What is Identifier?
A Python identifier is a name used to identify a variable, function, class,
module or any other object.
Python is case sensitive and hence uppercase and lowercase letters are
considered distinct.
Rules for naming an Identifier in Python
a) Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). For example Total and total is
different.
b) Reserved keywords cannot be used as an identifier.
c) Identifiers cannot begin with a digit. For example 2more, 3times etc. are
invalid identifiers.
d) Special symbols like @, !, #, $, % etc. cannot be used in an identifier. For
example sum@, #total are invalid identifiers.
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
e) Identifier can be of any length. Some examples of valid identifiers are total,
max_mark, count2, Student etc.
Examples of Python Identifiers
Valid identifiers
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
Example Program
radius=int(input("Enter the radius of the circle: "))
pi=3.14
area=pi*radius*radius
perimeter=2*pi*radius
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
rounded_num=round(area, 2)
rounded_number=round(perimeter, 2)
print(f"The area of the circle with radius {radius} is: {rounded_num:}")
print(f"The perimeter of the circle with radius {radius} is: {rounded_number:}")
Output
Enter the radius of the circle: 46
The area of the circle with radius 46 is: 6644.24
The perimeter of the circle with radius 46 is: 288.88
KEYWORDS
These are keywords reserved by the programming language and prevent the
user or the programmer from using it as an identifier in a program.
There are 33 keywords in Python 3.3.
This number may vary with different versions.
To retrieve the keywords in Python the following code can be given at the
prompt.
import keyword
print([Link])
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
The following lists shows the python keywords
Keyword and Descriptions
Keyword Description
True, False They are the results of logical (Boolean) operations in Python.
None None is a special constant in Python that represents the absence of a
value or a null value.
and, or , and, or, not are the logical operators in Python.
not
assert assert is used for debugging purposes.
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
return return statement is used inside a function to exit it and return a
value.
Keyword Description
class class is used to define a new user-defined class in Python.
def def is used to define a user-defined function.
if, else, elif if, else, elif are used for conditional branching or decision making.
except, except, raise, try are used with exceptions in Python.
raise, try
for,while for,while is used for looping
from, import keyword is used to import modules into the current
import namespace. from…import is used to import specific attributes or
functions.
STATEMENTS AND EXPRESSIONS
What is Statement in Python?
A Statement is a single, executable line of code.
8
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
It represents a complete instruction that the Python interpreter can
execute.
Statements in Python can be simple, like variable assignments or they can be
complex, involving control flow structures like loops and conditional
statements.
What is Expression in Python?
An expression is a combination of operators and operands that is
interpreted to produce some other value.
In any programming language, an expression is evaluated as per the
precedence of its operators.
So that if there is more than one operator in an expression, their precedence
decides which operation will be performed first.
Types of Expression in Python
Constant Expression
Arithmetic Expression
Integral Expression
Floating Expression
Relational Expression
Logical Expression
Multi-Operator Expression
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Constant Expressions
These are the expressions that have constant values only.
Example
x = 15 + 1.3
print(x)
Output
16.3
Arithmetic Expressions
An arithmetic expression is a combination of numeric values and operators.
The result of this type of expression is also a numeric value.
The operators used in these expressions are arithmetic operators like
addition, subtraction, multiplication, division etc.
Example
x=40
y=12
add=x+y
sub=x-y
pro=x*y
div=x/y
10
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
Integral Expressions
These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example
a=13
b=12.0
c=a+int(b)
print(c)
Output
25
11
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Floating Expressions
These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example
a=13
b=5
c=a/b
print(c)
Output
2.6
Relational Expressions
In these types of expressions, arithmetic expressions are written on both
sides of relational operator (> , < , >= , <=).
Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example
a=21
b=13
c=40
12
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
d=37
p=(a+b)>=(c-d)
print(p)
Output
True
Logical Expressions
These are kinds of expressions that result in either True or False.
It basically specifies one or more conditions.
Example
P=(10==9)
Q=(7>5)
R=P and Q
S=P or Q
T=not P
print(R)
print(S)
print(T)
Output
False
13
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
True
True
Multi-operator expression
It’s a quite simple process to get the result of an expression if there is only
one operator in an expression.
But if there is more than one operator in an expression, it may give different
results on basis of the order of operators executed.
Example
a=10+3*4
print(a)
b=(10+3)*4
print(b)
c=10+(3*4)
print(c)
Output
22
52
22
14
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
VARIABLES
What is Variable?
Variables are reserved memory locations to store values.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store
integers, float, characters etc in these variables.
Python variables do not need explicit declaration to reserve memory space.
The declaration happens automatically when you assign a value to a
variable.
The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.
Rules for naming a Variables in Python
a) Variables can be a combination of letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore (_). For example Total and total is
different.
b) Reserved keywords cannot be used as a variable name.
c) Variable cannot begin with a digit. For example 2more, 3times etc. are invalid
identifiers.
15
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
d) Special symbols like @, !, #, $, % etc. cannot be used as a variable name.
For example sum@, #total are invalid identifiers.
e) Variables can be of any length. Some examples of valid variables are total,
max_mark, count2, Student etc.
Python allows you to assign a single value to several variables
simultaneously.
For Example, a=b=c=1
a,b,c=1,2, "Tom"
Here, two integer objects with values 1 and 2 are assigned to variables a and
b respectively, and one string object with the value "Tom" is assigned to the
variable c.
Example Program
a=100
b=1000.0
name="John“
print(a)
print(b)
print(name)
Output
100
16
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
1000.0
John
Declaration and Initialization of Variables
# declaring the var
Number = 100
# display
print( Number)
Output
100
Redeclaring variables in Python
We can re-declare the Python variable once we have declared the variable
and define variable in python already.
# declaring the var
Number = 100
# display
print("Before re-declare: ", Number)
# re-declare the var
Number = 120.3
print("After re-declare:", Number)
17
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Output
Before re-declare: 100
After re-declare: 120.3
Global and Local Python Variables
Local Variables in Python are the ones that are defined and declared inside
a function. We cannot call this variable outside the function.
Global Variables in Python are the ones that are defined and declared
outside a function, and we need to use them inside a function.
Example Program
# Global variable
global_variable = 10
def example_function():
# Local variable
local_variable = 5
print("Local variable:", local_variable)
print("Global variable:", global_variable)
example_function()
print("Outside the function - Accessing global variable:", global_variable)
Output
Local variable: 5
18
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Global variable: 10
Outside the function - Accessing global variable: 10
OPERATORS
What is Operator?
An operator is a symbol that performs a specific operation on one or
more operands.
For Example, Consider the expression a+b=c.
Here a,b and c are the operands and +,= are the operators.
Types of operators supported by Python
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
Precedence and Associativity
Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication, and division.
19
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
The following are the arithmetic operators supported by Python
Operator Operation Description
+ Addition Adds two operands
– Subtraction Subtracts two operands
* Multiplication Multiplies two operands
/ Division Divides the first operand by the second
// Floor Divides the first operand by the second
Division
% Modulus Returns the remainder when the first operand is
divided by the second
** Exponent Performs Exponential Calculation
Example Program
a, b, c = 10, 5, 2
print("Sum-", (a+b))
print("Difference=", (a-b))
print("Product=", (a*b))
print("Quotient=", (a/b))
print("Remainder=", (b%c))
print("Exponent=", (b**2))
print("Floor Division=", (b//c))
20
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Output
Sum= 15
Difference= 5
Product= 50
Quotient= 2
Remainder=1
Exponent= 25
Floor Division= 2
Assignment Operators
Python provides various assignment operators.
Various shorthand operators for addition, subtraction multiplication,
division, modulus, exponent and floor division are also supported by Python.
The following are the assignment operators supported by Python
Operator Operation Description
= Equal to Assigns values from right side operand to the left
+= Add and Adds two operands and assigns result to the left
Assign operand
–= Subtract and Subtracts two operands and assigns result to the left
Assign operand
*= Multiply and Multiplies two operands and assigns result to the left
Assign operand
21
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
/= Divide and Divides the first operand by the second and assigns
Assign result to the left operand
//= Floor Division Divides the first operand by the second and assigns
result to the left operand
%= Modulus Returns the remainder when the first operand is
divided by the second and assigns result to the left
operand
**= Exponent Performs Exponential Calculation and assigns result
to the left operand
Example Program
a,b=10,5
a+=b
print(a)
a, b=10,5
a-=b
print (a)
a, b=10,5
a*=b
print(a)
a,b=10,5
a/=b
22
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print (a)
b,c=5,2
b%=c
print (b)
b,c=5,2
b**=c
print (b)
b,c=5,2
b//=c
print (b)
Output
15
50
25
23
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Comparison Operator
Comparison operators are used for comparing the values.
It either returns True or False according to the condition.
These operators are also known as Relational Operators.
The following are the comparison operators supported by Python
Operator Operation Description
> Greater than True if the left operand is greater than the right
< Less than True if the left operand is less than the right
== Equal to True if both operands are equal
!= Not equal to True if operands are not equal
>= Greater than or equal True if left operand is greater than or equal to
to the right
<= Less than or equal to True if left operand is less than or equal to the
right
Example Program
a,b=10,5
print("a==b is", (a==b))
print("a!=b is", (a!=b))
print("a>b is", (a>b))
print("a<b is", (a<b))
24
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print("a>=b is", (a>=b))
print("a<=b is", (a<=b))
Output
a==b is False
a!-b is True
a>b is True
a<b is False
a>=b is True
a<=b is False
Logical Operators
Logical operators in Python is used to perform various logical operations.
The following are the logical operators supported by Python
Operator Operation Description
and Logical If both the operands are true then condition becomes
AND true.
or Logical OR If any one of the operands are true then condition
becomes true.
not Logical Used to reverse the logical state.
NOT
25
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example Program
a,b,c,d=10,5,2,1
print((a>b)and(c>d))
print((a>b)or(d>c))
print(not(a>b))
Output
True
True
False
Bitwise Operators
Bitwise operators works on bits and performs bit by bit operation.
The following are the bitwise operators supported by Python
Operator Operation Description
& Bitwise AND Result bit 1,if both operand bits are 1;otherwise
results bit 0.
| Bitwise OR Result bit 1,if any of the operand bit is 1;
otherwise results bit 0.
^ Bitwise XOR Results bit 1,if any of the operand bit is 1,
otherwise results bit 0.
~ Binary Ones Inverts individual bits
Complement
26
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
<< Binary Left Shift The left operand’s value is moved toward left by
the number of bits specified by the right operand.
>> Binary Right The left operand’s value is moved toward right by
Shift the number of bits specified by the right operand.
Example Program
a,b=60,2
print(a&b)
print(alb)
print(a^b)
print(~a)
print(a>>b)
print(a<<b)
Output
62
62
-61
15
240
27
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Precedence and Associativity
In Python, operators have different levels of precedence, which
determine the order in which they are evaluated.
When multiple operators are present in an expression, the ones with higher
precedence are evaluated first.
In the case of operators with the same precedence, their associativity comes
into play, determining the order of evaluation.
The operator precedence in Python is listed in the following table
Operators Meaning Associativity
() Parentheses Left to Right
** Exponent Right to Left
*, /, //, % Multiplication, Division, Floor division, Left to Right
Modulus
+, - Addition, Subtraction Left to Right
<<, >> Bitwise shift operators Left to Right
& Bitwise AND Left to Right
^ Bitwise XOR Left to Right
| Bitwise OR Left to Right
Operators Meaning Associativity
==, !=, >, >=, <, Comparisons Operators Left to Right
<=
not Logical NOT Right to Left
28
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
and Logical AND Left to Right
or Logical OR Left to Right
DATA TYPES
The data stored in memory can be of many types.
For example, a person’s name is stored as alphabets, age is stored as numeric
value and address is stored as alphanumeric characters.
Python has the following standard data types
Numbers
Number data types store numeric values.
Number objects are created when you assign a value to them.
29
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
For example a=1, b=20.
The number data type is classified as int, float and complex types.
It is also possible to delete the reference to a number object by using the del
statement
The syntax of del statement is as follows:
del variable1[,variable2,….variable N]
For example:
del a
del a,b
int
int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
Example
x=1
y = 35656222554887711
z = -3255522
print(x)
print(y)
print(z)
30
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Output
35656222554887711
-3255522
float
float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
Example
x = 1.123
y = 1.0
z = -35.59
print(x)
print(y)
print(z)
Output
1.123
1.0
-35.50
Float can also be scientific numbers with an "e" to indicate the power of 10.
31
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example
x = 35e3
y = 12E4
print(x)
print(y)
Output
35000.0
120000.0
complex
Complex numbers are written with a "j" as the imaginary part:
Example
x = 3+5j
y = 5j
print(x)
print(y)
Output
(3+5j)
5j
32
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Boolean
Python boolean type is one of the built-in data types provided by Python,
which represents one of the two values i.e. True or False.
Example
print(10>9)
print(10==9)
print(10<9)
Output
True
False
False
Printing a message based on true or false value
Example
a = 200
b = 33
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
33
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Output
a is greater than b
Strings
Strings in python are identified as a continuous set of characters
represented in the quotation marks.
Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator with indexes starting
at 0 in the beginning of the string and ending at -1.
The + sign is the string concatenation operator and the asterisk * is the
repetition operator.
Example
str='Welcome to Python Programming'
print(str) #Prints complete string
print(str[0]) #Prints first character of the string
print(str[11:17]) #Prints characters starting from 11th to 17th
print(str[11:]) #Prints string starting from 11th character
print(str * 2) #Prints string two times
print(str+"Session") #Prints concatenated string
34
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Output
Welcome to Python Programming
Python
Python Programming
Welcome to Python ProgrammingWelcome to Python Programming
Welcome to Python ProgrammingSession
INDENTATION
What is Indentation in Python?
Python indentation refers to adding white space before a statement to a
particular block of code.
Python uses indentation to highlight the blocks of code.
Indentation is a very important concept of Python because without properly
indenting the Python code, you will end up seeing IndentationError and
the code will not get compiled.
Most programming languages like C, C++, and Java use braces { } to define
a block of code.
If a block has to be more deeply nested, it is simply indented further to the
right. You can understand it better by looking at the following lines of code.
35
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example 1 – Program with wrong indentation
if True:
print("Answer")
print("Correct")
else:
print("Answer")
print("Wrong")
Example 1 - with proper indentation
if True:
print("Answer")
print("Correct")
else:
print("Answer")
print("Wrong")
Output
Answer
Correct
Example 2 – Program with wrong indentation
x=5
36
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
if x > 0:
print("x is positive")
else:
print("x is non-positive")
Example 2 - with proper indentation
x=5
if x > 0:
print("x is positive")
else:
print("x is non-positive")
Output
x is positive
COMMENTS – SINGLE LINE & MULTILINE COMMENTS
What is Comments in Python?
Comments are very important while writing a program.
It describes what the source code has done.
Comments are for programmers for better understanding of a program.
In python, we use the # symbol to start writing a comment.
37
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Types of Comments in Python
Single line Comments
Multiline Comments
Single-Line Comments
Python single-line comment starts with the hashtag symbol # with no white
spaces.
If the comment exceeds one line then put a hashtag on the next line and
continue the Python Comment.
Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions.
Example
#This is demo of comment
#Display of Hello
print("Hello")
This produces the following result:
Hello
Multiline Comments
Multiline comments in Python refer to a block of text or statements that are
used for explanatory or documentation purposes within the code.
38
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Types of Multiline Comments in Python
There are three ways by which we can add Python multiline comments in our
code. They are as follows:
Consecutive single-line comment
Using a Multi-line string as a comment
Using Backslash Method
Consecutive single-line comment
The hash character should be placed before each line to be considered as
multiline comments in Python.
Example Program
# Write Python code here
# Single line comment used
print("Python Comments")
# print("Mathematics")
Output
Python Comments
Using a Multi-line string as a comment
Multiline comments are enclosed by triple double quotes (""") or triple
single quotes ('''). There should be no white space between delimiters.
39
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
These comments are often utilized to provide detailed explanations,
documentation, or notes about the code, and they can span multiple lines.
Example Program
""" Multi-line comment used
print("Python Comments") """
print("Mathematics")
Output
Mathematics
Using Backslash Method
A method to create multiline comments in Python involves using the
backslash \ at the end of each line to utilize the line continuation feature,
thereby allowing the comment to extend to the next line.
This line continuation method is less common than other approaches.
Example Program
The comments starting with # are extended to multiple lines using the
backslash (\) at the end of each line. The backslash indicates that the
comment continues on the next line.
# Using backslash for multiline comments
# This is a long comment \
#that spans multiple lines \
40
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
#using the backslash continuation method. \
# Code continues below
print("Hello, World!")
Output
Hello, World!
READING INPUT AND PRINTING OUTPUT
Reading Input
Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard.
These functions are raw_input and input.
raw_input function
The raw_input(prompt) function reads one line from standard input and
returns it as a string.
This prompts you to enter any string and it would display same string on the
screen.
Example
str = raw_input("Enter your name: ")
print("Your name is : ", str)
Output
Enter your name: Collin Mark
41
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Your name is : Collin Mark
input function
This function is called to tell the program to stop and wait for the user to
input the values.
It is a built-in function.
The input(prompt) function is equivalent to raw_input
Example
n= input("Enter a number ")
print("The number is: ",n)
Output
Enter a number: 5
The number is : 5
Example
n = input(5*2)
print(n)
Output
10
Printing Output
This function is used to print output on a screen where you can pass zero
or more expressions separated by commas.
42
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
The print function converts the expressions you pass into a string and writes
the result to standard output.
Example
print("Learning Python is fun and I enjoy it.")
Output
Learning Python is fun and I enjoy it.
Example
a=2
print("The value of a is", a)
This will produce the following output on the screen.
Output
The value of a is 2
Example
print(1,2,3,4)
print(1,2,3,4,sep='+')
print(1,2,3,4,sep='+',end='%')
Output
1234
1+2+3+4
43
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
1+2+3+4%
The output can be formatted according to the requirement of the user.
TYPE CONVERSIONS
What is Type Conversion?
The act of changing an object’s data type is known as type conversion.
There are two types of Type Conversion in Python
Python Implicit Type Conversion
Python Explicit Type Conversion
Python Implicit Type Conversion
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user
involvement.
Python prevents Implicit Type Conversion from losing data.
Example Program
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
44
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print("z is of type:",type(z))
Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
As we can see the data type of ‘z’ got automatically changed to the “float”
type while one variable x is of integer type while the other variable y is of
float type.
The reason for the float value not being converted into an integer instead is
due to type promotion that allows performing operations by converting data
into a wider-sized data type without any loss of information.
This is a simple case of Implicit type conversion in Python.
Python Explicit Type Conversion
The user converts the data types of objects using specified functions in
explicit type conversion, sometimes referred to as type casting.
When type casting, data loss could happen if the object is forced to conform
to a particular data type.
Example Program
# Example 1: Converting an integer to a float
integer_value = 42
45
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
float_value = float(integer_value)
print("Original Integer:", integer_value)
print("Converted Float:", float_value)
print("Type of Converted Float:", type(float_value))
Output
Original Integer: 42
Converted Float: 42.0
Type of Converted Float: <class 'float'>
# Example 2: Converting a float to an integer
float_number = 3.14
integer_number = int(float_number)
print("Original Float:", float_number)
print("Converted Integer:", integer_number)
print("Type of Converted Integer:", type(integer_number))
Output
Original Float: 3.14
Converted Integer: 3
Type of Converted Integer: <class 'int'>
46
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
# Example 3: Converting a string to an integer
string_number = "123"
integer_from_string = int(string_number)
print("Original String:", string_number)
print("Converted Integer:", integer_from_string)
print("Type of Converted Integer:", type(integer_from_string))
Output
Original String: 123
Converted Integer: 123
Type of Converted Integer: <class 'int'>
int() FUNCTION
The int() function converts the specified value into an integer number.
Python supports built-in functions for the same.
Example
#Convert a string into an integer:
x=int("12")
print(x)
Output
12
47
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
The following table provides various functions and its purpose
Function Description
abs(x) Returns the absolute value of x
ceil(x) Finds the smallest integer not less than x
floor(x) Find the largest integer not greater than x
pow(x,y) Finds x raised to y
max(n1,n2,…xn) Returns the largest of its arguments
min(n1,n2,…xn) Returns the smallest of its arguments
round(x,n) In case of decimal numbers, x will be rounded to n
digits.
Example Program
import math
print("Absolute value of -120:",abs(-120))
print("Ceiling of 12.2:",[Link](12.2))
print("Floor of 12.2:",[Link](12.2))
print("3 raised to 4:",pow(3, 4));
print("Largest among 10,4,2:",max(10,4,2))
print("Smallest among 10,4,2:",min(10,4,2))
print("12.6789 rounded to 2 decimals places:",round(12.6789,2))
48
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Output
Absolute value of -120: 120
Ceiling of 12.2: 13
Floor of 12.2: 12
3 raised to 4: 81
Largest among 10,4,2: 10
Smallest among 10,4,2: 2
12.6789 rounded to 2 decimals places: 12.68
float() FUNCTION
The float() function converts the specified value into a floating point
number.
Example
#Convert a string into a floating point number.
x=float("3.14")
print(x)
Output
3.14
49
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example Program 1
a = float(2)
print(a)
b = float(" 5.98 ")
print(b)
c = float("-24.17")
print(c)
d = float(" xyz ")
print(d)
Output
2.0
5.98
-24.17
ValueError: could not convert string to float: ' xyz '
Example Program 2
integer_value = 42
float_value = float(integer_value) #Converting int to float
print("Original Integer:", integer_value)
print("Converted Float:", float_value)
50
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print("Type of Converted Float:", type(float_value))
Output
Original Integer: 42
Converted Float: 42.0
Type of Converted Float: <class 'float'>
str() FUNCTION
str() is a built-in function in the Python programming language that is used
to convert the specified value into a string datatype.
Example
num = 42
str_num = str(num)
print("Original Integer:", num)
print("Converted String:", str_num)
Output
Original Integer: 42
Converted String: 42
len(string) – Returns the length of the string
Example
s='Learning python is fun'
51
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print("Length of given string is",len(s))
Output
Length of given string is 22
lower() – Returns a copy of the string in which all uppercase alphabets in a string
are converted to lowercase alphabets.
Example
s='Learning python is fun'
print([Link]())
Output
learning python is fun
upper() - Returns a copy of the string in which all lowercase alphabets in a string
are converted to uppercase alphabets.
Example
s='Learning python is fun'
print([Link]())
Output
LEARNING PYTHON IS FUN
swapcase() – Returns a copy of the string in which the case of all the alphabets are
swapped i.e the lowercase alphabets are converted to uppercase and vice versa.
52
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example
s='LEARNing PYTHON is fun'
print([Link]())
Output
learnING python IS FUN
capitalize() – Returns a copy of the string with only its first character capitalized.
Example
s='learning python is fun'
print([Link]())
Output
Learning python is fun
title() – Returns a copy of the string in which first character of all the words are
capitalized.
Example
s='learning python is fun'
print([Link]())
Output
Learning Python Is Fun
lstrip() – Returns a copy of the string in which all the characters have been
stripped (removed) from the beginning. The default character is whitespaces.
53
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example
s=' learning python is fun'
print([Link]())
s='*****learning python is fun'
print([Link]('*'))
Output
learning python is fun
learning python is fun
rstrip() – Returns a copy of the string in which all the characters have been
stripped (removed) from the end. The default character is whitespaces.
Example
s='learning python is fun '
print([Link]())
s='learning python is fun*****'
print([Link]('*'))
Output
learning python is fun
learning python is fun
54
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
strip() – Returns a copy of the string in which all the characters have been stripped
(removed) from the beginning and end. The default character is white spaces.
Example
s=' learning python is fun '
print([Link]())
s='*****learning python is fun*****'
print([Link]('*'))
Output
learning python is fun
learning python is fun
chr() FUNCTION
The chr() function returns the character that represents the specified unicode.
Syntax
chr(number)
Example Program
x=chr(97)
y=chr(65)
print(x)
print(y)
Output
a
55
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
More Python chr() Function Examples
In this example, we are printing Computer Science with the chr() in
Python.
Example Program
print(chr(67), chr(111),
chr(109), chr(112),
chr(117), chr(116),
chr(101), chr(114),
chr(83),chr(99),
chr(105), chr(101),
chr(110), chr(99),
chr(101))
Output
ComputerScience
Python chr() to Print Dollar Symbol
Example Program
unicode_value = 36
character = chr(unicode_value)
print(character)
Output
$
Python chr() to print Smiley Emoji
56
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example Program
smiley_unicode = 0x1F604
smiley_emoji = chr(smiley_unicode)
print("The smiley emoji is:", smiley_emoji)
Output
The smiley emoji is: 😄
chr() with Non-Integer Arguments
Example Program
print(chr('Ronald'))
print(chr('Lupin'))
Output
TypeError: 'str' object cannot be interpreted as an integer.
In the above example, we have used the chr() method with Non-Integer
Arguments. This results in a TypeError.
complex() FUNCTION
Python complex() function returns a complex number ( real + imaginary)
example (5+2j) when real and imaginary parts are passed, or it also converts a
string to a complex number.
Syntax
complex ([real[, imaginary]])
Example Program
print(complex(1, 2))
Output
(1+2j)
57
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
complex() With Integer and Float Type Parameters
In this example, we are using complex() to create a complex number in
Python with integer and float type parameters.
Example Program
z = complex()
print("complex() with no parameters:", z)
complex_num1 = complex(5)
print("Int: first parameter only", complex_num1)
complex_num2 = complex(7, 2)
print("Int: both parameters", complex_num2)
complex_num3 = complex(3.6)
print("Float: first parameter only", complex_num3)
complex_num4 = complex(3.6, 8.1)
print("Float: both parameters", complex_num4)
print()
print(type(complex_num1))
Output
complex() with no parameters: 0j
Int: first parameter only (5+0j)
Int: both parameters (7+2j)
Float: first parameter only (3.6+0j)
Float: both parameters (3.6+8.1j)
<class 'complex'>
complex() with String Type Parameters of the Numeric Form
58
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
In this example, we are using complex() to create a complex number in
Python with String Type Parameters of the Numeric Form.
Example Program
z1 = complex("7")
print(z1)
z2 = complex("2", "3")
print(z2)
Output
(7+0j)
TypeError: complex() can't take second arg if first is a string
ord() FUNCTION
Python ord() function returns the Unicode code from a given character.
Syntax
ord(ch)
Example
print(ord('a'))
print(ord('€'))
Output
97
8364
The following example shows the ord() value of an integer, character, and
unique character with ord() function in Python.
Example
print(ord('2'))
59
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print(ord('g'))
print(ord('&'))
Output
50
103
38
If the string length is more than one, a TypeError will be raised. The
syntax can be ord(“a”) or ord(‘a’), both will give the same results. The example is
given below.
Demonstration of Python ord() function
Example
value = ord("A")
value1 = ord('A')
print (value, value1)
Output
AA
Error Condition while Using Ord(0)
A TypeError is raised when the length of the string is not equal to 1 as
shown below.
Example
value1 = ord('AB')
print(value1)
Output
60
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
TypeError: ord() expected a character, but string of length 2 found.
Example of ord() and chr() functions
This code print() the Unicode of the character with the ord() and after
getting the Unicode we are printing the character with the chr() function.
Example
value = ord("A")
print (value)
print(chr(value))
Output
65
A
hex() FUNCTION
The hex() function in Python is used to convert a decimal number to its
corresponding hexadecimal representation. Hexadecimal is a base-16 numbering
system commonly used in computer science and programming.
It takes an integer as an argument and returns a string representing the
hexadecimal value.
Syntax
hex(x)
Parameter: x – an integer number
Example Program: Basic Usage
decimal_number = 42
hex_string = hex(decimal_number)
61
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print(f"The hexadecimal representation of {decimal_number} is:
{hex_string}")
Output
The hexadecimal representation of 42 is: 0x2a
Example Program: Passing Negative Number as Argument
negative_number = -15
hex_string = hex(negative_number)
print(f"The hexadecimal representation of {negative_number} is:
{hex_string}")
Output
The hexadecimal representation of -15 is: -0xf
Example Program: Hexadecimal to Decimal Conversion
hex_string = "0x1a"
decimal_number = int(hex_string, 16)
print(f"The decimal representation of {hex_string} is: {decimal_number}")
Output
The decimal representation of 0x1a is: 26
Example Program: hex() with loop
for i in range(5):
hex_string = hex(i)
print(f"The hexadecimal representation of {i} is: {hex_string}")
Output
The hexadecimal representation of 0 is: 0x0
The hexadecimal representation of 1 is: 0x1
62
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
The hexadecimal representation of 2 is: 0x2
The hexadecimal representation of 3 is: 0x3
The hexadecimal representation of 4 is: 0x4
oct() FUNCTION
Python oct() function takes an integer and returns the octal representation in
a string format.
Syntax
oct(x)
Parameters
x – Must be an integer number and can be in either binary, decimal or
hexadecimal format.
Returns
octal representation of the value.
Example Program: Basic Usage
decimal_number = 42
octal_string = oct(decimal_number)
print(f"The octal representation of {decimal_number} is: {octal_string}")
Output
The octal representation of 42 is: 0o52
Example Program: Negative Number
negative_number = -15
hex_string = hex(negative_number)
63
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
print(f"The hexadecimal representation of {negative_number} is:
{hex_string}")
Output
The hexadecimal representation of -15 is: -0xf
Example Program: Octal to Decimal Conversion
octal_string = "0o24"
decimal_number = int(octal_string, 8)
print(f"The decimal representation of {octal_string} is: {decimal_number}")
Output
The decimal representation of 0o24 is: 20
Example Program: oct() with Loop
for i in range(5):
octal_string = oct(i)
print(f"The octal representation of {i} is: {octal_string}")
Output
The octal representation of 0 is: 0o0
The octal representation of 1 is: 0o1
The octal representation of 2 is: 0o2
The octal representation of 3 is: 0o3
The octal representation of 4 is: 0o4
type() FUNCTION AND ITS OPERATOR
The type() function is mostly used to find out the type of the given object
and also for debugging purposes.
Syntax
type(object)
64
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example Program
a = ("C", "C++", "Java")
b = ["Python", ".NET", "Ruby?"]
c = {1:"Hello",2:"Computer",3:"Science"}
d = "Hello World"
e = 10.23
f = 11
g=True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
Output
<class 'tuple'>
<class 'list'>
<class 'dict'>
<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>
Example Program
65
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
user_input = input("Enter a value: ")
value_type = type(user_input)
print(f"The entered value '{user_input}' is of type: {value_type}")
Output
Enter a value: 42
The entered value '42' is of type: <class 'str'>
DYNAMIC AND STRONGLY TYPED LANGUAGE
Dynamic Typing:
Dynamic typing means that the type of a variable is determined at runtime.
You can assign different types of values to a variable, and its type can
change during the execution of the program.
Example Program
variable = 42
print(type(variable))
variable = "Hello, Python!"
print(type(variable))
Output
<class 'int'>
<class 'str'>
Here, variable starts as an integer and later becomes a string. The type is
determined dynamically based on the assigned values.
Strong Typing
Strong typing means that the interpreter enforces strict type-checking rules.
66
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Operations between incompatible types result in errors, and explicit type
conversion is often required.
Example Program
num = 10
text = "20"
# Attempting to perform addition with different types
result = num + text # This will raise a TypeError
In this example, attempting to add an integer (num) to a string (text) results
in a TypeError because Python does not automatically convert between
incompatible types.
Dynamic and Strong Typing Combined
When dynamic and strong typing are combined, the interpreter dynamically
determines types but enforces strict type-checking during operations.
Example Program:
x=5
y = "10"
# Attempting to concatenate a string and an integer
result = x + y # This will raise a TypeError
In this case, trying to concatenate an integer (x) and a string (y) raises a
TypeError because Python is both dynamically typed and strongly typed. The
interpreter doesn't implicitly convert types during operations.
67
Downloaded by Keerthana.U -25 (keerthana6266@[Link])
lOMoARcPSD|61993372
Example Program:
value = 42
print(type(value))
value = value + 0.5
print(type(value))
value = str(value) + " is the answer."
print(type(value))
print(value)
Output
<class 'int'>
<class 'float'>
<class 'str'>
42.5 is the answer.
In this example, value starts as an integer, then becomes a float, and finally
becomes a string during runtime. The types change dynamically, demonstrating
dynamic typing. Additionally, strong typing is evident as explicit type conversion
is required when concatenating the float and string.
68
Downloaded by Keerthana.U -25 (keerthana6266@[Link])