0% found this document useful (0 votes)
7 views81 pages

Python Notes Part1

The document provides an introduction to Python, covering installation, data types, control structures, functions, and modules. It outlines Python's advantages, characteristics, applications, and its historical development from creation to current status. Additionally, it explains various data types, including lists, tuples, dictionaries, and sets, along with their functionalities and examples.

Uploaded by

cutandkeystudios
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views81 pages

Python Notes Part1

The document provides an introduction to Python, covering installation, data types, control structures, functions, and modules. It outlines Python's advantages, characteristics, applications, and its historical development from creation to current status. Additionally, it explains various data types, including lists, tuples, dictionaries, and sets, along with their functionalities and examples.

Uploaded by

cutandkeystudios
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT – I qq

Introduction to Python: Installation and IDEs (Jupyter Notebook, VSCode) - Python


indentation, variables, data types - Lists, Tuples, Range, Sets, Dictionaries. Operators

Control Structures: Conditional statements (if, elif, else), Loops (for, while)

Functions and Modules: Defining and calling functions, Arguments and return values,
Recursive Functions, Lambda functions, map, filter, reduce, Importing and using Python
modules

Modules and System Interaction: The OS Module: File and directory operations ([Link](),
[Link](), [Link](), [Link]()), Working with file paths The sys Module: Command-line
arguments ([Link]), Exiting programs ([Link]())

Unit II -Text and File Handling: Covered these topics

Lists: Creating and modifying lists, Accessing elements, Inserting, removing, replacing
elements, Basic list operations: Searching, Sorting

Tuples: Creating tuples, Accessing tuple elements, Immutability concept

Dictionaries: Dictionary literals, Adding, removing keys, Accessing and updating values.
Traversing dictionaries

What is Python?
• Python is a very popular general-purpose interpreted, interactive, object-oriented, and
high-level programming language.
• Python is dynamically-typed and garbage-collected programming language.
# You don't declare types in Python
x = 10 # x is an integer
print(type(x)) # <class 'int'>

x = "Hello" # Now x is a string


print(type(x)) # <class 'str'>

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 1


Python automatically manages memory for you.
When an object (like a list, string, etc.) is no longer used, Python’s garbage collector
frees that memory so it can be reused.

• It was created by Guido Van Rossum during 1985- 1990. Like Perl, Python source code
is also available under the GNU General Public License (GPL).
• Python supports multiple programming paradigms, including Procedural, Object Oriented
and Functional programming language.
• Python design emphasizes code readability with the use of significant indentation.

What are the Advantages of python.

1. Python is Interpreted − Python is processed at runtime by the interpreter. It means


not required to compile the program before executing it.
2. Python is Interactive – It means we can type commands and then immediately
executed.
3. Portable - run the code in any platform.
4. Python is object-oriented - supports OOPs concepts such as polymorphism,
operator overloading and multiple inheritance etc.
5. Indentation - Indentation is one of the greatest feature in python
6. It’s free (open source) - Downloading python and installing python is free and easy
7. It’s Powerful - Dynamic typing, Built-in types and tools, Library utilities , Third
party utilities (e.g. Numeric, NumPy etc), Automatic memory management
8. Python is a Beginner's Language – supports development of a wide range of
applications from simple text processing to WWW browsers to games.
9. Straight forward syntax - The formation of python syntax is simple and straight
forward which also makes it popular.

What are the Characteristics of Python?


Following are important characteristics of Python Programming −

• It supports functional and structured programming methods as well as OOP.


• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX and Java.

Mention Applications of Python

1. Web Development: Websites and web apps (Django, Flask)


2. Data Science & Analytics: Data analysis, visualization, business insights
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 2
3. Machine Learning & AI: Predictive modeling, NLP, computer vision
4. Automation & Scripting: Automating tasks, web scraping, testing
5. Game Development: 2D/3D games and simulations
6. Scientific Computing & Research: Simulations and research data analysis
7. Finance & FinTech: Trading algorithms, risk analysis, fraud detection
8. Education: Teaching programming and prototyping
9. Embedded Systems & IoT: Microcontrollers and IoT devices

History of Python

1. Creation:
o Python was created by Guido van Rossum in 1989 at CWI, Netherlands.
o He wanted a language that was easy to read, simple, and powerful.
2. First Release:
o Python 1.0 was released in 1991.
o It included basic features like functions, exceptions, and core data types.
3. Python 2.x:
o Released in 2000.
o Added features like list comprehensions and garbage collection.
o Python 2 was widely used for many years.
4. Python 3.x:
o Released in 2008.
o Introduced improvements for Unicode support, better syntax, and cleaner
code.
o Not fully backward compatible with Python 2.
5. Growth & Popularity:
o Python became popular for web development, data science, AI, automation,
and more.
o Its simple syntax and strong community support helped it grow rapidly.
6. Current Status:
o Python is one of the most popular programming languages in the world.
o Continues to be updated with new features, libraries, and tools.

Explain the features of Python.

1.
2. Interpreted Language -Python code is executed line by line, Easier to debug.
3. Dynamically Typed - No need to declare variable types, Types are determined at
runtime.
4. Object-Oriented -Supports classes, objects, inheritance, and encapsulation.
5. Open Source - Python is free to use, modify, and distribute.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 3


6. Extensive Libraries - Offers pre-built modules for web development, data science, AI,
etc.
7. Portability - Python runs on Windows, Linux, Mac, and other platforms.
8. High-Level Language - Handles complex tasks easily without worrying about memory
management.
9. Garbage Collected - Automatically frees unused memory to manage resources
efficiently.
10. Embeddable & Extensible - Python code can be embedded in C/C++ programs and
extended with C/C++.

Explain different data types in Python. 6m


Python Data Types are used to define the type of a variable. Python has various built-in data
types .

• Numeric - int, float


• String – str
• Boolean - bool
• Sequence - list, tuple
• Binary - bytes, bytearray, memoryview
• Mapping - dict
• Set - set, frozenset
• Range data type
• None - NoneType
Note: In Python, every thing is an Object.

int data type


Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
print(20)
20

float data type


Float is a number, positive or negative, containing one or more decimals.

y=2.8

2.8
Boolean data type
Objects of Boolean type may have one of two values, True or False:
type(True)
<class 'bool'>

Strings data type


Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes.
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 4
print("presidency college")
OUTPUT: presidency college

type("presidency college")
OUTPUT: <class 'str'>

List data type


• List is a collection which is ordered and changeable and allows duplicate members used
in data structures. (Grow and shrink as needed, type, sortable).
• To use a list, you must declare it first. Do this using square brackets and separate values
with commas.
• We can construct / create list in many ways.
Ex:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
print list # Prints complete list
OUTPUT: ['abcd', 786, 2.23, 'john', 70.2]

example
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
list[0]=”presidency”

print list[1:3] # Prints elements starting from 2nd till 3rd


print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

Output
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 5


Tuple data type

• A tuple is another sequence data type that is similar to the list.


• A tuple consists of a number of values separated by commas.
• tuples are enclosed within parentheses.

Differences between lists and tuples are:


• Lists are enclosed in brackets ( [ ] ) tuples are enclosed in parentheses ( ( ) )
• List elements and size can be changed, while tuple cannot be updated.
• Tuples can be thought of as read-only lists.

Example

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print (tuple) # Prints complete list
#tuple[0]="presidency" //this will give error
print (tuple[0] )# Prints first element of the list
print (tuple[1:3] ) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists

Output
This produce the following result −
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Set data type

• Unordered, mutable, unique elements only.


• No duplicates, cannot access elements by index.

# Creating a set
my_set = {1, 2, 3, 4, 4}
print(my_set) # {1, 2, 3, 4} -> duplicates removed
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 6
# Adding and removing elements
my_set.add(5)
my_set.remove(2)
print(my_set) # {1, 3, 4, 5}

mapping – dictionary data type


• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes and consist of key-value pairs.
• A dictionary key can be almost any Python type, but are usually numbers or strings.

Example
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2] ) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values

Output
This is one
This is two
{'name': 'john','code':6734, 'dept': 'sales'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. they are simply unordered.

Range data type

• In Python, the range data type is used to represent a sequence of numbers and is most
commonly used for looping a specific number of times.
• It is an immutable sequence type, meaning its values cannot be changed once created.
• The range() function can take one, two, or three arguments in the form range(start, stop,
step).

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 7


Example1: the statement range(5) generates numbers from 0 to 4.

for i in range(5):
print(i)

output: 0 1 2 3 4

Example2: specify both the starting and ending points.


for i in range(2, 6):
print(i)

output: 2 3 4 5

Example3 :range(0, 10, 2) will generate even numbers from 0 to 8.


for i in range(0, 10, 2):
print(i)

output: 0 2 4 6 8

Example4: negative step to generate numbers in reverse order.

for i in range(10, 0, -2):


print(i)
Output: 10 8 6 4 2

Example5: range() itself does not directly display as a list, you can convert it into one using the
list() function.

numbers = list(range(1, 6))


print(numbers)

Output: [1, 2, 3, 4, 5]

EXERCISE ON RANGE() -REFER CLASS NOTES FOR EXAMPLES

None – NoneType (2m)


• The None keyword in Python is a data type and an object of the NoneType class.
• The None keyword is used for defining a null variable or an object in Python.
Example:
x = None
print(x)

OUTPUT
none

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 8


What is the importance of indentation in python?
• Indentation in Python is essential because it defines the structure of code blocks (like
loops, functions, and conditionals).
• It determines which statements belong together, ensures code readability, and prevents
errors.
• Python enforces consistent indentation—usually 4 spaces per level—instead of using
braces {} like other languages.

Correct:
if True:
print("Hello")
print("World")

Incorrect:
if True:
print("Hello")
print("World")

Variables:
Variables are nothing but reserved memory locations to store values. This means that when we
create a variable we reserve some space in memory.

Rules for Python variables:


• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
• and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

Assigning Values to Variables: - for reference


The symbol = is used to assign values to variables.
For example −
a= 100 # An integer assignment
b = 10.2 # A floating point
c = "Raj" # A string
print (a)
print (b)
print (c)

This produces the following result −


100
10.2
Raj

How multiple assignment is done in python? 2m


PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 9
Python allows to assign a single value to several variables simultaneously.

For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. We can also assign multiple objects to multiple variables.

For example −
a,b,c = 1,2,”BCA”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively and
one string object with the value "BCA" is assigned to the variable c.

Expressions:
In Python, an expression is any valid combination of literals, variables, operators, and
function calls that produces a value when evaluated.
Type Example Result
Arithmetic 3+5 8
String "Hi" + "!" "Hi!"
Boolean 5>3 True
Function call len("Python") 6
Conditional "Yes" if True else "No" "Yes"

Examples: REFER CLASS NOTES

Python Input and Output Functions


In Python, input( ) function is used to accept data as input at run time. The syntax
for input() function is,
Variable = input (“prompt string”)
Where, prompt string in the syntax is a statement or message to the user, to know what input
can be given.
It always returns a string, so we need to convert it (to int, float, etc.)
Example:
Example1: String Input
name = input("Enter your name: ")
print("Hello,", name)
Example 2: Numeric input
age = int(input("Enter your age: "))
print("You will be", age + 1, "next year.")

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 10


Example3: Taking multiple inputs in one line
a, b = input("Enter two numbers separated by space: ").split()
a = int(a)
b = int(b)
print("Sum =", a + b)

WHAT IS OUTPUT FUNCTION IN PYTHON?

• The print() function prints the specified message to the screen, or other standard output
device.
• The message can be a string, or any other object
• the object will be converted into a string before written to the screen.

Example1: printing text and variables


name = "Bob"
age = 25
print("My name is", name, "and I am", age, "years old.")

Example 2: Using f-strings (modern formatting)


name = "Alice"
marks = 89.5
print(f "{name} scored {marks} marks in the test.")

KEYWORDS IN PYTHON 2m
Keywords in Python are reserved words that can not be used as a variable name, function
name, or any other identifier.

Keywords in Python programming language


False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

# printing all keywords at once using "kwlist()"


import keyword
print("The list of keywords is : ")
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 11
print([Link])

What is an identifier in python? 2m


Any name that is used to define a class, function, variable module, or object is
an identifier.

Rules for Naming Python Identifiers


• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).

Valid identifiers:
name
student_name
age1
_sum
EmployeeData

Invalid Identifiers
1name
student-name
class
my name

How do we write comments in python?


In Python, comments are used to explain code — they are ignored by the interpreter and exist
only to make the code more readable for humans.

Types of Comments in Python

1. Single-line Comment

• Use the # symbol at the beginning of a line.


• Everything after # on that line is treated as a comment.

Example:
#Write a python pgm to add to numbers
A=10
B=20
C=A+B
print(c)

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 12


2. Multi-line Comment

Python doesn’t have a special syntax for multi-line comments

But we can use

• Use multiple single-line comments, or


• Use a multi-line string (''' ... ''' or """ ... """) as a comment block.

What is the importance of import in python? 2m


• In Python, we use the import keyword to make code in one module available in another.
• Import in Python are important for structuring the code effectively.
• Using imports allows us to reuse code.
• Import in python is similar to #include header_file in C/C++.
Example - code

import math
pie = [Link]
print("The value of pi is : ",pie)

Explain different types of operators in Python. 6m

1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.

Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2 * 3 = 6

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 13


/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16

Program 1: Arithmetic Operators in Python


a=7
b=2
print ('Sum: ', a + b)
print ('Subtraction: ', a - b)
print ('Multiplication: ', a * b)
print ('Division: ', a / b)
print ('Floor Division: ', a // b)
print ('Modulo: ', a % b)
print ('Power: ', a ** b) # a to the power b

output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
2. Python Assignment Operators

Assignment operators are used to assign values to variables.

Operator Name Example

= Assignment Operator a=7

+= Addition Assignment a += 1 #a=a+1

-= Subtraction Assignment a -= 3 #a=a-3

*= Multiplication Assignment a *= 4 #a=a*4

/= Division Assignment a /= 3 #a=a/3

%= Remainder Assignment a %= 10 # a = a % 10

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 14


**= Exponent Assignment a**= 10 # a = a ** 10

Program2: Assignment Operators


# assign 10 to a
a = 10

# assign 5 to b
b=5

# assign the sum of a and b to a


a += b #a=a+b
print(a)

# Output: 15

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False. They are used in
decision-making.
Operator Example Meaning
and a and b Logical AND:

True only if both the operands are True


or a or b Logical OR:

True if at least one of the operands is True


not not a Logical NOT:

True if the operand is False and vice-versa.

5. Python Bitwise operators

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 15


Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit

Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)


Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)

6. Python Special operators

Python language offers some special types of operators like the identity operator and
the membership operator. They are described below with examples.
Identity operators

In Python, is and is not are used to check if two values are located on the same part of the
memory.

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1) # prints False
print(x2 is y2) # prints True

Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value
or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary membership operators tests for presence of key, not the value.

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

What do you mean by operator precedence? Explain.


• If multiple operators present then which operator will be evaluated first is decided by
operator precedence.
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 16
• Operator precedence affects how an expression is evaluated.

For example1:
x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first
multiplies 3*2 and then adds into 7.

For example2:
print(3+10*2)
print((3+10)*2)
output
23
26

Operator Associativity: If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine. It can either be Left to Right or
from Right to Left.

Example: ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as
“(100 / 10) * 10”.

Operator Description Associativity

() Parentheses left-to-right

** Exponent right-to-left

* / % Multiplication/division/modulus left-to-right

+ – Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to


left-to-right
> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

is, is not Identity


left-to-right
in, not in Membership operators

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 17


Operator Description Associativity

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

not Logical NOT right-to-left

and Logical AND left-to-right

or Logical OR left-to-right

= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

Data Type Conversion


Python defines type conversion functions to directly convert one data type to another.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion

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. To get a more clear view of
the topic see the below examples.
EXAMPLE
# Implicit Type Conversion
a=5 # int
b = 2.5 # float
c = a + b # int + float → float (implicit conversion)
print(c, type(c))

output: 7.5, float


PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 18
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement. But there is a risk of data loss since we are forcing an expression to be
changed in some specific data type.
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in
which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.

EXAMPLE:
# Explicit Type Conversion (Type Casting)

a = "10" # string
b = int(a) # convert string to integer
c = float(b) # convert integer to float

print(a, type(a)) #prints 10,string


print(b, type(b)) #prints 10,int
print(c, type(c)) #prints 10.0 , float

Control Structures: Decision making statements, Python loops, Python control statements.
Python Native Data Types: Numbers, Lists, Tuples, Sets, Dictionary, Functions & Methods of
Dictionary, Strings (in detail with their methods and operations).

Flow Control Statements


Flow control describes the order in which statements will be executed at runtime.
Flow control statements are divided into three categories in Python.

1. Conditional Statements (or) Selection Statements


In conditional statement, based on some condition result, some group of statements will be
executed and some group of statements will not be executed.

Note: There is no switch statement in Python. (Which is available in C and Java)


There is no do-while loop in Python.(Which is available in C and Java)
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 19
goto statement is also not available in Python. (Which is available in C)

i) if Statement :
Syntax:
if condition:
statement 1
statement 2
statement 3
statement 4

Note: All the statements under if condition must follow indentation. Otherwise there will be
error.
if condition:
statement 1
statement 2
statement 3
statement

example
if 10<20:
print('10 is less than 20')
print('End of Program')

example

name=input("Enter Name:")
if name=="Smith":
print("Hello Smith Good Morning")
print("How are you!!!")

ii) if - else Statement:


Syntax:
if condition:
statement 1
else:
statement2
if condition is true then statement-1 will be executed otherwise statement-2 will be executed.

Example
Wap to accept your name. If name is correct print valid else print invalid.(use if-else
statement)
name = input('Enter Name : ')
if name == 'Smith':
print('Hello Smith! Good Morning')
else:

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 20


print('Hello Guest! Good MOrning')
print('How are you?')

output:
Enter Name : Smith
Hello Smith! Good Morning
How are you?

iii) if-elif-else Statement:


Syntax:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
...
else:
Default Action

If condition1 is true, action1 is executed, if cond1 is false, condition2 is checked. If it is true,


action2 is executed otherwise condition3 is checked. It it is true action 3 is executed else default
action is executed.

Example:write a python program to enter your average marks.


If marks>=75 print distinction
If marks >=60 and <75 - I class
If marks >=50 and <60 - II class
If marks >=40 and <50 - pass class
If marks <40 - fail

marks=int(input("Enter Your marks:"))


if marks>=75 and marks<=100:
print("Distinction")
elif marks>=60 and marks<75:
print("First class")
elif marks>=50 and marks<60:
print("second class”)
elif marks>=40 and marks<50:
print("Pass class")
elif marks>=0 and marks<40:
print("FAIL")
else:
print("Invalid Input!")

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 21


Example Programs
Q 1. Write a program to find largest of given 2 numbers.
n1=int(input("Enter First Number:"))
n2=int(input("Enter Second Number:"))
if n1>n2:
print("Biggest Number is:",n1)
else :
print("Biggest Number is:",n2)

Enter First Number:10


Enter Second Number:20
Biggest Number is: 20

# Program to print the English word of a single-digit number

# Take input from the user


num =input("Enter a single digit number (0-9): "))

# Check and print corresponding word


if num == '0':
print("Zero")
elif num == '1':
print("One")
elif num == '2':
print("Two")
elif num == '3':
print("Three")
elif num == '4':
print("Four")
elif num == '5':
print("Five")
elif num == '6':
print("Six")
elif num == '7':
print("Seven")
elif num == '8':
print("Eight")
elif num == '9':
print("Nine")
else:
print("Invalid input! Please enter a single digit (0-9).")

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 22


Q 7. Write a program to take a single digit number from the key board and print it's value
in English word? Hint: use concept of dictionary
num = input("Enter a single-digit number (0–9): ")

# Dictionary mapping numbers to words


word = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}

# Check and print the word


if num in word:
print("You entered:", word[num])
else:
print("Invalid input! Please enter a single-digit number (0–9).")

Write the same program using List

list1 = Enter a digit from 0 to 9 :7


['ZERO','ONE','TWO','THREE','FOUR','FIVE','S SEVEN
IX','SEVEN','EIGHT','NINE']
n =int(input('Enter a digit from 0 to 9 :'))
print(list1[n])

2. Iterative Statements
If we want to execute a group of statements multiple times then we should go for Iterative
statements. Python supports 2 types of iterative statements.

i. for loop
ii. while loop

i) for loop:
If we want to execute some action for every element present in some sequence (it may be string
or collection) then we should go for for loop.

Syntax:
for x in sequence:
body
where 'sequence' can be string or any collection.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 23


Body will be executed for every element present in the sequence.

Eg 1: Write a Program to print characters present in the given string.


s="BCA"
for x in s :
print(x)
B
C
A
Eg 2: To print characters present in string index wise.

s=input("Enter some String: ")


i=0
for x in s :
print("The character present at" ,i,"index is:",x)
i=i+1

output
Enter some String: BCA
The character present at 0 index is : B
The character present at 1 index is : C
The character present at 2 index is : A

REFER CLASS NOTES FOR MORE EXAMPLES….

ii) while loop:


• Python while loop keeps reiterating a block of code defined inside it until the desired
condition is met.
• It contains a boolean expression and the code inside the loop is repeatedly executed as
long as the boolean expression is true.
Syntax:
while(expression):
Statement(s)

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 24


Eg 1: To print numbers from 1 to 10 by using while loop
x=1 1
while x <=5: 2
print(x) 3
x=x+1 4
5

Eg 2: To display the sum of first n numbers.


n=int(input("Enter number:")) Enter number:10
sum=0 The sum of first 10 numbers
i=1
is : 55
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)

Infinite Loops
Some times a loop can execute infinite number of times if it does not satisfy the given condition.
i = 1
while True:
print('Hello', i) # This program never going to terminates
i=i+1

Note: By pressing Ctrl + C we can stop this program

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 25


Nested Loop

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":
for i in range(4): Hello
for j in range(2): Hello
print(i,j) Hello
Hello
Hello
Hello

for i in range(4): i = 0 j = 0 i = 2 j = 1
for j in range(4): i = 0 j = 1 i = 2 j = 2
#print("i=",i," j=",j) i = 0 j = 2 i = 2 j = 3
print('i = {} j = {}'.format(i,j)) i = 0 j = 3 i = 3 j = 0
i = 1 j = 0 i = 3 j = 1
i = 1 j = 1 i = 3 j = 2
i = 1 j = 2 i = 3 j = 3
i = 1 j = 3
i = 2 j = 0

Transfer Statements

i) break:
• Break' in Python is a loop control statement.
• It is used to control the sequence of the loop.
• We can use break statement inside loops to break loop execution based on some
condition.

EXAMPLE: Output
i=0 0
for i in range(5): 1
if i == 3: 2
break
print(i)

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 26


ii) continue:
• It is used to control the sequence of the loop.
• We can use continue statement to skip current iteration and continue next iteration.

Eg 1: To print odd numbers in the range 0 to 9.


for i in range(10): 1
if i%3==0: 3
continue 5
print(i) 7
9

Loops with else block:


Inside loop execution,if break statement is not executed ,then only else part will be executed.
else means loop without break
cart=[10,20,30,40,50] 10
for item in cart: 20
if item>=500: 30
print("We cannot process this order") 40
break 50
print(item) Congrats ...all items
else: processed successfully
print("Congrats ...all items processed
successfully")

What is the difference between for loop and while loop in Python?
For Loop While Loop

Uses for keyword Uses while keyword

For loop is used when the number While loop is used when the number
of iterations is already known. of iterations is already Unknown.

The loop runs infinite times in the Returns the compile time error in the
absence of condition absence of condition

Once done, it cannot be repeated In the while loop, it can be repeated


at every iteration.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 27


To iterate, the range function is There is no such function in the
used. while loop.

To be done at the beginning of In the while loop, it is possible to do


the loop. this anywhere in the loop body.

Python's for loop can iterate over While loops cannot be directly
generators. iterated on Generators.

The for loop is faster than the While loop is relatively slower as
while loop. compared to for loop.

Python Native data types – Numbers, Lists, Tuples, Sets, Dictionary

I. Numbers:
Numbers represent numeric values that can be used for mathematical operations.
Types of numbers
Type Example Description
int 10, -25, 0 Whole numbers (no decimal point).
float 3.14, -0.5, 2.0 Numbers with decimal points.
complex 2 + 3j, 5j Numbers with a real and imaginary part.

Example:

x = 10 # int
y = 3.14 # float
z = 2 + 5j # complex

print(type(x)) # <class 'int'>


print(type(y)) # <class 'float'>
print(type(z)) # <class 'complex'>

COMMON OPERATIONS
a = 10
b=3

print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division (float result)
print(a // b) # Floor division
print(a % b) # Modulus
print(a ** b) # Exponentiation

NOTE:

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 28


• In fundamental data types every variable can hold only single value.
• If we want to represent a group of values (i.e., Names of all students, roll numbers of all
students or mobile numbers of all students etc.,) as a single entity where insertion order
required to preserve and duplicates are allowed then we should go for list data type.

II. List data type

• A list is an ordered, mutable (changeable) collection of elements.


• Lists can store different data types in one container.
• List allows duplicates.

EXAMPLE1
my_list = [10, 20, "Python", 3.14, True]
print(my_list)

EXAMPLE2
numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
mixed = [10, "Python", 3.5, True]
empty = []

ACCESSING ELEMENTS
Operation Example Output
Access by index numbers[0] 1
Access last element numbers[-1] 4
Slice elements numbers[1:3] [2, 3]

LIST functions and methods

Function /
Description Example Output
Method
len(list) Returns the number of elements len([1, 2, 3]) 3
max(list) Returns the largest element max([2, 5, 1]) 5
min(list) Returns the smallest element min([2, 5, 1]) 1
sum(list) Returns sum of all numeric elements sum([1, 2, 3]) 6
[Link](x) Counts occurrences of value [1, 2, 1, 3].count(1) 2
[Link](x) Returns index of first occurrence [10, 20, 30].index(20) 1
lst = [1,2]; [Link](3);
[Link](x) Adds an element at the end [1, 2, 3]
lst
[Link](i, x) Inserts element x at index i [1,3].insert(1,2) [1,2,3]
[Link](x) Removes first occurrence of x [1,2,3,2].remove(2) [1,3,2]
[Link]([i]) Removes and returns element at index i [1,2,3].pop() 3

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 29


Function /
Description Example Output
Method
(default last)
lst=[1,2,3]; [Link]();
[Link]() Reverses the list in place [3,2,1]
lst
[Link]() Sorts the list in ascending order lst=[3,1,2]; [Link](); lst [1,2,3]
[Link]() Returns a shallow copy of the list lst=[1,2]; [Link]() [1,2]
[Link]() Removes all elements from the list lst=[1,2,3]; [Link](); lst []
Extends list by appending elements from
[Link](iterable) [1,2].extend([3,4]) [1,2,3,4]
iterable

Tuple data type


• Tuple data type is exactly same as list data type except that it is immutable, i.e., once
we create a tuple object, we cannot perform any changes in that object.
• Read-only version of list is tuple.
• Tuple elements can be represented within parenthesis ()

Examples
t1 = (1, 2, 3, 4)
t2 = ("apple", 10, 3.5, True)
t3 = 1, 2, 3
print(type(t3)) # <class 'tuple'>

t4 = (5,) # Must have a comma to create single element


print(type(t4)) # <class 'tuple'>

Accessing Tuple Elements


We can use indexing and slicing, just like with lists.
t = (10, 20, 30, 40, 50)
print(t[0])
print(t[-1])
print(t[1:4])

Tuple functions and methods


Function / Method Description Example Output
len(tuple) Returns the number of elements len((1, 2, 3)) 3
max(tuple) Returns the largest element max((2, 5, 1)) 5
min(tuple) Returns the smallest element min((2, 5, 1)) 1
sum(tuple) Returns sum of all numeric elements sum((1, 2, 3)) 6
[Link](x) Counts occurrences of value (1, 2, 1, 3).count(1) 2
[Link](x) Returns index of first occurrence (10, 20, 30).index(20) 1

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 30


Dictionaries:

• A dictionary in Python is a collection of key–value pairs, where each key is unique and is
used to access its corresponding value.
• Dictionaries are mutable, meaning we can change their contents after creation.
• Dictionaries are used to store data with meaningful labels (keys) instead of using just
indices.

Creating a Dictionary
Dictionaries are created using curly braces {} with key: value pairs.
Example:
student = {"name": "Rahul", "age": 16, "grade": "A"}
• "name", "age", "grade" are keys
• "Rahul", 16, "A" are values
An empty dictionary can be created as:
d = {}

WHAT IS A DICTIONARY LITERAL?


A dictionary literal is a way to directly create a dictionary
(a mapping of keys to values) using curly braces {}.

• Keys must be unique.


• Keys can be strings, numbers, tuples (immutable types).
• Values can be any type.
• Items are written as key: value pairs, separated by commas.

Simple dictionary literal


student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}

1. Adding Keys to a Dictionary


Dictionaries are mutable, so new key–value pairs can be added anytime.

Method 1: Using Assignment


student = {"name": "Alice", "age": 20}

student["course"] = "MCA" # Adding a new key


student["age"] = 21 # Updating existing key

print(student)

OUTPUT:
{'name': 'Alice', 'age': 21, 'course': 'MCA'}

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 31


Method 2: Using update()
[Link]({"city": "Delhi", "semester": 3})

2. Removing Keys from a Dictionary


Method 1: Using del - Removes a key permanently.

student = {"name": "Alice", "age": 21, "city": "Delhi"}

del student["city"]
print(student)

Method 2: Using pop() - Removes a key and returns its value.

age_value = [Link]("age")
print(age_value) # 21
print(student)

Method 3: Using popitem() - Removes the last inserted key–value pair.

student = {"name": "Alice", "age": 21}


[Link]() # removes ('age', 21)

Method 4: Using clear() - Removes all entries.

[Link]()

3. Accessing and Updating Values


Dictionaries in Python store data as key–value pairs. To work with the values stored in a
dictionary, we mainly access (read) and update (modify) them using their keys.

Accessing Values
To access a value, you use its key inside square brackets [] or the get() method.

a) Using [ ] (Direct Access) - This method directly returns the value of the given key.
If the key does not exist, Python raises a KeyError.

student = {"name": "Alice", "age": 21}

print(student["name"]) # Output: Alice


print(student["age"]) # Output: 21

b) Using get() (Safe Access) - This method returns the value if the key exists, or a
default value if it doesn’t. This avoids errors and is useful when you are unsure whether a
key exists.

print([Link]("city")) # Output: None


print([Link]("city", "Not found")) # Output: Not found

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 32


Updating Values - To update a value, simply assign a new value to an existing key.
a) Updating an existing key's value
student["age"] = 22
print(student)

b) Updating multiple values using update() - The update() method changes one or more values
at once.

[Link]({"age": 23, "city": "Mumbai"})


print(student)

4. TRAVERSING DICTIONARIES
Traversing (or iterating through) a dictionary means going through each key, value, or key–value
pair in the dictionary. This can be done using loops.

Dictionaries can be traversed through:


• Keys
• Values
• Key–Value pairs
• Sorted order of keys
• Nested dictionaries

1. Traversing Keys - When you loop over a dictionary directly, it automatically iterates over
its keys.
a) Default iteration (keys)
student = {"name": "Alice", "age": 23, "city": "Mumbai"}

for key in student:


print(key)

b) Using keys()
for key in [Link]():
print(key)
OUTPUT:
name
age
city

2. Traversing Values - Use the values() method to iterate only through the dictionary values.
for value in [Link]():
print(value)
Output:
Alice
23
Mumbai

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 33


3. Traversing Key–Value Pairs - The items() method returns each key along with its value,
making it easy to process both together.
for key, value in [Link]():
print(key, ":", value)
Output:
name : Alice
age : 23
city : Mumbai

4. Traversing Dictionaries in Sorted Order - Sometimes we want the keys in alphabetical or


numerical order.

Sorted by keys
for key in sorted(student):
print(key, ":", student[key])

5. Traversing Nested Dictionaries - A dictionary may contain other dictionaries inside it.
To access nested data, you can specifically iterate inside that inner dictionary.
student = {
"name": "Alice",
"marks": {"math": 90, "python": 95}
}

for subject, score in student["marks"].items():


print(subject, ":", score)

Output:
math : 90
python : 95

Function / Method Description Example Output


Returns the number
len(dict) len({'a':1,'b':2}) 2
of key-value pairs
Returns a view of all
[Link]() {'a':1,'b':2}.keys() dict_keys(['a','b'])
keys
Returns a view of all
[Link]() {'a':1,'b':2}.values() dict_values([1,2])
values
Returns a view of
[Link]() {'a':1,'b':2}.items() dict_items([('a',1),('b',2)])
key-value pairs
Returns value for
[Link](key[, default]) key, or default if key {'a':1}.get('b',0) 0
not found
Updates dictionary d={'a':1};
[Link](other_dict) {'a':1,'b':2}
with key-value pairs [Link]({'b':2}); d
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 34
Function / Method Description Example Output
from another dict
Removes and returns
d={'a':1,'b':2};
[Link]() the last inserted key- ('b',2)
[Link]()
value pair
Removes all key-
[Link]() d={'a':1}; [Link](); d {}
value pairs
Returns a shallow
[Link]() copy of the d={'a':1}; [Link]() {'a':1}
dictionary
Returns value for
[Link](key[, d={'a':1};
key; inserts key with {'a':1,'b':2}
default]) [Link]('b',2); d
default if not present

Functions and Modules: Defining and calling functions, Arguments and return values,
Recursive Functions, Lambda functions, map, filter, reduce, Importing and using Python
modules

Modules and System Interaction: The OS Module: File and directory operations
([Link](), [Link](), [Link](), [Link]()), Working with file paths

The sys Module: Command-line arguments ([Link]), Exiting programs ([Link]())


Try this example:

Wap to count number of digits in a given number

num = 75869
count = 0
while num != 0:
num = num // 10
count = count + 1
print("Total digits are:", count)

FUNCTIONS IN PYTHON

• In Python, the function is a block of code defined with a name.


• We use functions whenever we need to perform the same task multiple times without
writing the same code again.
• It can take arguments and returns the value.
• Function improves efficiency and reduces errors because of the reusability of a code.
Once we create a function, we can call it anywhere and anytime.
• The benefit of using a function is reusability and modularity.
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 35
Types of Functions

Python support two types of functions

1. Built-in function

2. User-defined function

1. Built-in function
• The functions which are come along with Python itself are called a built-in
function or predefined function.
• Example: range(), id(), type(), input(), eval() etc.

Python range() function

• generates the immutable sequence of numbers starting from the given start integer to
the stop integer.

• The range() is a built-in function that returns a range object that consists series of integer
numbers, which we can iterate using a for loop.

Wap to print sum of given natural number.


s=0
n = int(input("Enter number "))
for i in range(n + 1):
s =s+ i
print("\n")
print("Sum is: ", s)

id() - Returns the unique memory address of an object.


Example:
x = 10
print(id(x))

type() - Shows the data type of a variable.


Example:
a = 3.14
b = "Hello"

print(type(a)) # <class 'float'>


print(type(b)) # <class 'str'>

eval() - Evaluates a string as a Python expression.


expr = input("Enter an expression: ") # Example: 10 + 20
result = eval(expr)
print("Result:", result)

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 36


II. User-defined function

Functions which are created by programmer explicitly according to the requirement are called a
user-defined function.

Creating a Function

STEPS:

1. Use the def keyword with the function name.

2. pass the number of parameters as per the requirement. (Optional).

3. define the function body with a block of code to perform a task.

Note: no need to specify curly braces for the function body. The only indentation is essential
to separate code blocks. Otherwise, error.

SYNTAX

def function_name(parameter1, parameter2):

# function body

# write some action

return value

• function_name: Function name is the name of the function. We can give any name to
function.

• parameter: Parameter is the value passed to the function. We can pass any number of
parameters. Function body uses the parameter’s value to perform an action

• function_body: The function body is a block of code that performs some task. This block
of code is nothing but the action you wanted to accomplish.

• return value: Return value is the output of the function.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 37


Creating a function without any parameters

def greet():
print(" Welcome to Python programming.")

# calling the function


greet()

Creating a function with parameters


• A function with parameters in Python is defined using the def keyword and includes
variables inside parentheses to receive input values.
• These parameters allow the function to work with different data each time it is called,
making the code more flexible and reusable.
• When calling the function, corresponding arguments must be provided.

Example 1: Function with one parameter – pass name and print name

def greet(name):
print("Hello", name)

greet("Raj")

Example 2: Function with two parameters – pass 2 numbers and print sum
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 38
def add(a, b):
print("Sum =", a + b)

add(5, 7)

Another example for passing parameters to calculate area of rectangle

def area_of_rectangle(length, width):


return length * width

result=area_of_rectangle(10, 4)
print(result)

Creating a function with parameters and return value

Functions can return a value. The return value is the output of the function. Use the return
keyword to return value from a function.

Example: calculate sum of 2 numbers and return value and print in calling(main) function

def sum(a, b):


add = a + b
return add

# call function
res = sum(20, 5)
print("Addition :", res)

# Output Addition : 25

Calling a function
• Once we defined a function we can call that function by using its name.
• Also call that function from another function or program by importing it.
• To call a function, use the name of the function with the parenthesis, and if the function
accepts parameters, then pass those parameters in the parenthesis.

Example: check a number is even or odd


def even_odd(n):
if n % 2 == 0:
print('Even number')
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 39
else:
print('Odd Number')
# calling function by its name
num=int(input(‘enter a value’))
even_odd(num)

Return Value From a Function


In Python, to return value from the function, a return statement is used. It returns the value of the
expression following the returns keyword.
Syntax of return statement
def fun():
statement-1
statement-2
statement-3
.
.
return [expression]

Return value is nothing but a outcome of function.


• The return statement ends the function execution.
• For a function, it is not mandatory to return a value.
• If a return statement is used without any expression, then the None is returned.
• The return statement should be inside of the function block.
Example
def is_even(list1):
even_num = []
for n in list1:
if n % 2 == 0:
even_num.append(n)
# return a list
return even_num

# Pass list to the function


even_num = is_even([2, 3, 42, 51, 62, 70, 5, 9])
print("Even numbers are:", even_num)

Return Multiple Values


We can return multiple values from a function. Use the return statement by separating each
expression by a comma.
Example: create a function to calculate sum,sub,mul,div and return the values

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 40


def arithmetic(num1, num2):
add = num1 + num2
sub = num1 - num2
multiply = num1 * num2
division = num1 / num2
return add, sub, multiply, division

# read four return values in four variables


a, b, c, d = arithmetic(10, 2)

print("Addition: ", a)
print("Subtraction: ", b)
print("Multiplication: ", c)
print("Division: ", d)

The pass Statement


Pass is a null statement in Python. It does nothing when executed.
pass is used to
1. Create an empty function, class, or loop without getting an error.
2. Plan code structure before implementing the actual logic.
3. Temporarily ignore a condition in if, for, or while blocks.
4. Avoid syntax errors when a block cannot be empty.

Example
x = 10

if x > 0:
pass # will handle positive case later
else:
print("x is not positive")

Scope and Lifetime of Variables


• When we define a function with variables, then those variables’ scope is limited to that
function.
• In Python, the scope of a variable is an area where a variable is declared. It is called the
variable’s local scope.
• We cannot access the local variables from outside of the function.
• Because the scope is local, those variables are not visible from the outside of the
function.

Note: The inner function does have access to the outer function’s local scope.
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 41
When we are executing a function, the life of the variables is up to running time. Once we return
from the function, those variables get destroyed. So function does no need to remember the value
of a variable from its previous call.

with arguments, with return value


def add(num1,num2)
print(num1,num2)
return num1+num2

print(add(2,4))
--------------------
with arguments, without return
def add(num1,num2):
print(num1,num2)
print(num1+num2)

add(2,4)
--------------------
without arguments and w/o return
def add():
num1=10
num2=20
print(num1+num2)

add()
-----------------------
without arguments and with return
def add():
num1=10
num2=20
return num1+num2

print("addition of 2 numbers is ", add())

---------------------------------------------------

The following code shows the scope of a variable inside a function.


Example
global_lang = 'DataScience'

def scope_test():
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 42
local_lang = 'Python'
print(local_lang)

scope_test()
print(global_lang)

Local Variable in function


• A local variable is a variable declared inside the function that is not accessible from
outside of the function.
• The scope of the local variable is limited to that function only where it is declared.
• If we try to access the local variable from the outside of the function, we will get the error
as NameError.

Global Variable in function


• A Global variable is a variable that is declared outside the function.
• The scope of a global variable is accessed anywhere in the program
• It is accessible in all functions of the same module.

Example for LOCAL VARIABLE


def function1():
# local variable
loc_var = 888
print("Value is :", loc_var)

def function2():
print("Value is :", loc_var)

function1()
function2()

output
Value is : 888
print("Value is :", loc_var) # gives error,
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 43
NameError: name 'loc_var' is not defined

Example FOR GLOBAL VARIABLE


global_var = 999

def function1():
print("Value in 1nd function :", global_var)

def function2():
print("Value in 2nd function :", global_var)

function1()
function2()
output
Value in 1nd function : 999
Value in 2nd function : 999

Python Function Arguments

The argument is a value, a variable, or an object that we pass to a function or method

call. In Python, there are four types of arguments allowed.

1. Positional arguments

2. keyword arguments

3. Default arguments

4. Variable-length arguments

[Link] Arguments

• Positional arguments are arguments that are passed to function in

proper positional order.

• Ie 1st positional argument needs to be 1st when the function is called.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 44


The 2nd positional argument needs to be 2nd when the function is called, etc.

Example

def sub(a, b):

print(a - b)

sub(50, 10)

sub(10, 50)

What is the output?

If you try to use pass more parameters you will get an error

def add(a, b):

print(a - b)

add(105, 561, 4)

[Link] Arguments

• A keyword argument is an argument value, passed to function


preceded by the variable name and an equals sign.
• Keyword arguments allows to pass values to a function by specifying
the parameter names.
• This makes the function call more readable and allows arguments to be given
in any order, like:

Example

def studentInfo(name, age, course):

print("Name:", name)

print("Age:", age)

print("Course:", course)

studentInfo(name="Alice", age=20, course="Computer Science")


PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 45
MCQ (Keyword Arguments)

1. Which of the following is a valid use of keyword arguments?

A. func(10, a=20)
B. func(x=10, 20)
C. func(a=10, b=20)
D. func(a, b=20)

Answer: C

2. What happens if you pass an unknown keyword argument to a function?

A. It is ignored
B. Function uses a default value
C. Python raises a TypeError
D. Python converts it to positional argument

Answer: C

3. Which function call will cause an error for the function def fun(a, b):?

A. fun(a=10, b=20)
B. fun(10, b=20)
C. fun(b=20, a=10)
D. fun(a=10, 20)

Answer: D (positional argument cannot follow keyword argument)

4. Which statement is TRUE about keyword arguments?

A. Order matters
B. They must always appear before positional arguments
C. Order does not matter
D. They cannot be mixed with positional arguments
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 46
Answer: C

5. A variable defined inside a function is called:

A. Global variable
B. Local variable
C. Nonlocal variable
D. Built-in variable

Answer: B

6. What keyword is used to modify a global variable inside a function?

A. nonlocal
B. global
C. static
D. extern

Answer: B

7. What will be the output of the following code?

x=5

def func():
x = 10
print(x)

func()
print(x)

A. 10 and 10
B. 5 and 5
C. 10 and 5
D. Error

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 47


Answer: C
(Local x is 10 inside the function; global x remains 5)

8. Which of the following statements about local variables is TRUE?

A. They exist throughout the program


B. They are created when the function is called
C. They can be accessed outside the function
D. Their value is stored permanently

Answer: B

10. What happens when you try to access a local variable outside its function?

A. It returns None
B. Python converts it to global
C. It raises a NameError
D. Function returns the variable

Answer: C

[Link] Arguments

• Default arguments take the default value during the function call if we do
not pass them.
• We can assign a default value to an argument in function definition using
the = assignment operator.

Example – Simple default argument

def welcome(name="presidency"):

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 48


print("Hello,", name)

welcome()

welcome("MCA")

OUTPUT???

Example – Default Argument with Multiple Parameters

def add(a, b=10):

return a + b

print(add(5))

print(add(5, 3))

output?

Invalid example

def func(a=10, b):

pass

when we call a function with an argument, it will take that value.

[Link]-length Arguments

• there is a situation where we need to pass multiple number of arguments


to the function.
• Such types of arguments are called variable-length arguments.
• We can declare with the * (asterisk) symbol.

def fun(*var):

function body

• We can pass any number of arguments to this function. Internally all these values are
represented in the form of a [Link]

def addition(*numbers):
total = 0
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 49
for no in numbers:
total = total + no
print("Sum is:", total)

addition() # 0 arguments
addition(10, 5, 2, 5, 4) # 5 arguments
addition(78, 7, 2.5) # 3 arguments

output
Sum is: 0
Sum is: 26
Sum is: 87.5

MCQ

1. WHAT IS THE OUTPUT


def fun(a, b=5):

return a + b

print(fun(3))

2. OUTPUT?
def show(x, y=2, z=3):
print(x + y * z)

show(1, z=4)

3. Output?

def calc(a=2, b=3):

print(a * b)

calc(b=4)

4. Output
def test(a, b=10):

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 50


print(a - b)

test(20, b=5)
5. Output
def fun(a, b=2, c=3):
print(a, b, c)

fun(5, c=10)

5 2 10

Recursive Function

• A recursive function is a function that calls itself, again and again.


• calculating the factorial of a number is a repetitive activity, in that case, we can call a
function again and again, which calculates factorial.

factorial(5)

5*factorial(4)

5*4*factorial(3)

5*4*3*factorial(2)

5*4*3*2*factorial(1)

5*4*3*2*1 = 120

Example

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 51
print("factorial of a number is:", factorial(8))

The advantages of the recursive function are:

1. By using recursive, we can reduce the length of the code.

2. The readability of code improves due to code reduction.

3. Useful for solving a complex problem

The disadvantage of the recursive function:

1. The recursive function takes more memory and time for execution.

2. Debugging is not easy for the recursive function.

Python Anonymous/Lambda Function

• When we need to declare a function without any name. The nameless property function is
called an anonymous function or lambda function.

• The reason behind the using anonymous function is for instant use, that is, one-time
usage.

• Normal function is declared using the def function. Whereas the anonymous function is
declared using the lambda keyword.

• Python lambda function is a single expression.

• But, in a lambda body, we can expand with expressions over multiple lines using
parentheses or a multiline string.

ex : lambda n:n+n

Syntax of lambda function:

lambda: argument_list:expression

When we define a function using the lambda keyword, the code is very concise so that there
is more readability in the code. A lambda function can have any number of arguments but
return only one value after expression evaluation.

Example 1: Program for even numbers without lambda function

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 52


def even(nums):

list = []

for n in nums:

if n % 2 == 0:

[Link](n)

return list

num_list = [10, 5, 12, 78, 6, 1, 7, 9]

print("Even numbers are", even)

Example 2: Program for even number with a lambda function

L = [10, 5, 12, 78, 6, 1, 7, 9]

even= list(filter(lambda x: x % 2 == 0, L))

print("Even numbers are: ", even)

Note: Not required to write explicitly return statements in the lambda function because the
lambda internally returns expression value.

Lambda functions are more useful when we pass a function as an argument to another function.
We can also use the lambda function with built-in functions such as filter, map, reduce because
this function requires another function as an argument.

1. What is a lambda function in Python?


A. A function that can take only one argument
B. A function defined without a name.
C. A function that must return multiple values
D. A function that works only inside classes

2. Which of the following is the correct syntax of a lambda function?


PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 53
A. lambda x: x + 2
B. def lambda x: x + 2
C. lambda(x) = x + 2
D. lambda: x, x + 2

3. What will be the output of the following code?


f = lambda x, y: x * y
print(f(3, 4))

12

4. Lambda functions in Python can have:


A. Multiple expressions
B. Zero or more arguments but only one expression
C. Only one argument
D. No return value

5. Which built-in function is commonly used with lambda?


A. input()
B. map()
C. print()
D. int()

Map(), also used: filter(), sorted())

6. What will this code output?


nums = [1, 2, 3, 4]
print(list(map(lambda x: x**2, nums)))

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 54


A. [1, 4, 9, 16]
B. [2, 3, 4, 5]
C. 1, 4, 9, 16
D. Error
A

7. Which of the following statements is TRUE about lambda functions?


A. They can contain multiple statements
B. They must be assigned to a variable
C. They automatically return the result of their expression
D. They are faster than normal functions

8. What does this code print?


print((lambda x: x if x > 5 else 5)(3))

Answer: 5

9. Which of the following uses lambda correctly with filter()?


A. filter(lambda x: x > 10, numbers)
B. filter(x > 10: lambda, numbers)
C. filter(lambda x, numbers: x > 10)
D. filter(lambda: x > 10, numbers)

10. Can lambda functions be recursive in Python?

never

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 55


filter() function in Python

In Python, the filter() function is used to return the filtered value. this function is used to filter
values based on some conditions.

Syntax of filter() function:

filter(funtion, sequence)

where,

• function – Function argument is responsible for performing condition checking.

• sequence – Sequence argument can be anything like list, tuple, string.

Write a python code to print even numbers using lamda and filter.

nums = [1, 2, 3, 4, 5, 6]

evens = list(filter(lambda x: x % 2 == 0, nums))

print(evens)

write a code to Filter names starting with 'A'

names = ["Alice", "Bob", "Ankit", "Jim"]

result = list(filter(lambda x: [Link]("A"), names))

print(result)

write python code to filter values greater than 10

values = [5, 12, 3, 18, 7]

greater = list(filter(lambda x: x > 10, values))

print(greater)

MCQs on filter() with Lambda


1. What does the filter() function return?
A. A list
B. A tuple

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 56


C. An iterator
D. A dictionary

Answer: C

2. What will be the output of the following code?


nums = [1, 2, 3, 4, 5]
result = list(filter(lambda x: x % 2 != 0, nums))
print(result)

[1, 3, 5]

3. Which option correctly uses filter() to select numbers less than 50?
A. filter(x < 50, nums)
B. filter(lambda x: x < 50, nums)
C. filter(nums, lambda x: x < 50)
D. filter(lambda: x < 50, nums)

4. What will be the output?


names = ["Ram", "Rita", "Rohan", "Sita"]
result = list(filter(lambda x: [Link]("R"), names))
print(result)

['Ram', 'Rita', 'Rohan']

5. Which statement about filter() is TRUE?

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 57


A. It must return a list
B. It removes elements permanently from the list
C. It takes a function and an iterable as arguments.
D. It can only be used with numbers

map() function in Python

• map() function is used to apply some functionality for every element present in the given
sequence and generate a new series with a required modification.

• Ex: for every element present in the sequence, perform cube operation and generate a
new cube list.

Syntax of map() function:

map(function,sequence)

where,

• function – function argument responsible for applied on each element of the sequence

• sequence – Sequence argument can be anything like list, tuple, string

Example: lambda function with map() function

list1 = [2, 3, 4, 8, 9]

list2 = list(map(lambda x: x*x*x, list1))

print("Cube values are:", list2)

QUIZ…

1. What does the map() function do in Python?

A. Filters values based on a condition


B. Applies a function to each item in an iterable
C. Sorts elements of a list
D. Converts values to a dictionary

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 58


B

2. What will the following code output?

nums = [1, 2, 3]

result = list(map(lambda x: x + 1, nums))

print(result)

[2, 3, 4]

3. What type does map() return ?

A. List
B. Tuple
C. Iterator
D. String

4. Which of the following correctly applies map() to square each number in a list?

A. map(x**2, nums)
B. map(lambda x: x**2, nums)
C. map(nums, lambda x: x**2)
D. map(lambda: x**2, nums)

5. What will this code print?

a = [1, 2, 3]

b = [4, 5, 6]

result = list(map(lambda x, y: x + y, a, b))

print(result)
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 59
[5, 7, 9]

6. What will be the output?

words = ["hello", "python"]

result = list(map(lambda x: [Link](), words))

print(result)

['HELLO', 'PYTHON']

7. Which of the following statements is TRUE about map()?

A. It can take multiple iterables


B. It can only work with numbers
C. It always returns a list
D. It doesn't work with lambda functions

8. What is the output of the following code?

nums = [2, 4, 6]

result = list(map(lambda x: x % 4, nums))

print(result)

[2, 0, 2]

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 60


10. What will this print?

result = map(lambda x: x*2, "abc")

print(list(result))

['aa', 'bb', 'cc']

In Python, a string is an iterable of its characters:

"abc" → ['a', 'b', 'c']

So the map() function will process each character one at a time.

reduce() function in Python

• reduce() function is used to minimize sequence elements into a


single value by applying the specified condition.
• The reduce() function is present in the functools module;
hence, we need to import it using the import statement before using it.

Syntax of reduce() function:

reduce(function, sequence)

How reduce() works (conceptually)

Given:

reduce(func, [a, b, c, d])

It performs:

func(func(func(a, b), c), d)

It reduces multiple values to a single result.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 61


Example 1: Sum of numbers
from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3, 4])


print(result)

Output:10
Example 2: Multiply all numbers
from functools import reduce

result = reduce(lambda x, y: x * y, [2, 3, 4])


print(result)

Output:
24

Example 3: Using an initializer


result = reduce(lambda x, y: x + y, [1, 2, 3], 10)
print(result)
Here:
• Start with 10
• Then add 1, 2, 3
Output:16
Example 4: Find the maximum value
from functools import reduce
nums = [3, 8, 2, 5]
max_value = reduce(lambda x, y: x if x > y else y, nums)
print(max_value)
Output:
8

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 62


When to use reduce()?
reduce() is powerful but sometimes hard to read. But
• If we want compact code
• If we need cumulative processing
Qq
Importing Modules in Python
• To use the functionality present in any module, we have to import
it into our current program.
• use the import keyword along with the desired module name.
• When the interpreter comes across an import statement, it imports the module to current
program.
• use the functions inside a module by using a dot (.) operator along with the module name.
• In the below example, the math module is imported into the program so that we can use
the sqrt() function.
• In Python, modules refer to the Python file, which contains Python code like Python
statements, classes, functions, variables, etc. A file with Python code is defined with
[Link]

• For example: In [Link], where the test is the module name.

• In Python, large code is divided into small modules. The benefit of modules is, it
provides a way to share reusable functions.

Types of modules

In Python, there are two types of modules.

1. Built-in Modules

2. User-defined Modules

1. Built-in modules
• Built-in modules come with default Python installation.
• One of Python’s most significant advantages is its rich library support that contains lots
of built-in modules.
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 63
• Hence, it provides a lot of reusable code.

• Example datetime, os, math, sys, random, etc.

2. User-defined modules

• The modules which the user defines or create are called a user-defined module.

• We can create our own module, which contains classes, functions, variables, etc.,
as per our requirements.

How to import modules?

• import statement is used to import the whole module. Also, we can import specific
classes and functions from a module.

For example, import module name

• When the interpreter finds an import statement, it imports the module presented in a
search path.
• The module is loaded only once, even we import multiple times.
• To import modules in Python, we use the Python import keyword.
• With the help of the import keyword, both the built-in and user-defined modules are
imported.

importing a math module.

CODE EXAMPLE
import math # Import the math module
num = 4
print([Link](num)) # Call the sqrt() function from the math module

Import multiple modules

• To use more than one module, then we can import multiple modules.
• This is the simplest form of import statement.

Syntax of import statement

import module1[,module2[,.. moduleN]

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 64


EXAMPLE

# Import two modules


import math, random

print([Link](5))
print([Link](10, 20))

Import only specific classes or functions from a module


• To import particular classes or functions, we can use the from...import statement.
• It is an alternate way to import.
• we can import individual attributes and methods directly into the program.
• In this way, we are not required to use the module name.

Syntax of from...import statement:


from <module_name> import <name(s)>

EXAMPLE
# import only factorial function from math module
from math import factorial

print(factorial(5))

Import with renaming a module

• To use the module with a different name, we can use from..import…as statement.
• It is also possible to import a particular method and use that method with a different
name.
• It is called aliasing.
• Afterward, we can use that name in the entire program.

Syntax of from..import ..as keyword:

from <module_name> import <name> as <alternative_name>

Example 1: Import a module by renaming it

import random as rand


print([Link](10, 20, 2))

Example 2: import a method by renaming it

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 65


# rename randint as random_number
from random import randint as random_number

# Gives any random number from range(10, 50)


print(random_number(10, 50))

Import all names

If we need to import all functions and attributes of a specific module,

then instead of writing all function names and attribute names,

we can import all using an asterisk *.

Syntax import *

Example

from math import *


print(pow(4,2))
print(factorial(5))

print(pi*3)
print(sqrt(100))

How to Write Your Own Python Modules

Now that you have learned how to import a module in your program, it is time to write your
own, and use it in another program. Writing a module is just like writing any other Python file.
Let's start by writing a function to add/subtract two numbers in a file [Link]

def add(x,y):

return (x+y)

def sub(x,y):

return (x-y)

if you try to execute this script on the command line, nothing will happen because you have not
instructed the program to do anything

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 66


Create another Python script in the same directory with the name module_test.py and write the
following code into it.

import calculation #Importing calculation module

print([Link](1,2)) #Calling function defined in the calculation module

If you execute module_test.py, you will see "3" as output.

MCQ ON MODULE

1. Which is correct way to import the math module?

A. import math

2. After import math, which is the correct way to use the sqrt() function?

[Link](16)

3. What does this statement do?

from math import pi**


A. Imports all functions from math
B. Imports pi and renames it
C. Imports only the constant pi
D. Imports math but not its functions

4. What will be the output?

from math import sqrt as s

print(s(81))

5
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 67
5. Which method imports all objects from a module?

A. import module.*

B. from module import all

C. from module import *

D. import * from module

`*` imports everything (not recommended).

6. What is the purpose of the `as` keyword in module import?

To rename the module

7. Which of these is NOT a valid Python module import?

A. `import os`

B. `import sys`

C. `from random import randint`

D. `import random from`

8. Suppose we have a file `[Link]`. Which import loads it?

`import mymath`

Files in the same directory can be imported as modules.

9. What happens if a module is imported twice?

A. It loads twice

B. Python reloads it automatically

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 68


C. Python loads it only once (cached)

D. Causes an error

✔ Python caches modules, so they are imported only once.

10. Which statement is true about Python modules?

A. A module can contain only functions

B. A module is a single Python file

C. A module must be named “[Link]”

D. A module cannot import another module

11. What will this code output?

import random

print(type(random))

A. <class 'function'>
B. <class 'module'>
C. <class 'package'>
D. <class 'object'>

B
✔ random is a module.

12. Which statement imports the module and gives it a shorter alias?

A. import statistics alias s


B. import statistics -> s
C. import statistics as s
D. alias statistics as s

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 69


Module-Based MCQs (With Code)

What is printed?

import math

math = 10

print(math)

10
✔ Variable assignment overrides the module name.

What happens?

from math import sqrt

print([Link](9))

output

Error: math not defined

from math import sqrt

print(sqrt(9))

Output?

from random import randint

import random

print(randint(1, 5), [Link](1, 5))

Two random numbers


Both accesses work and produce independent random numbers.

consider a file [Link]:

x=5

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 70


def show():

return "Hello"

Main file:

import helper

print([Link](), helper.x)

What is output?

"Hello" 5

22. What happens?

import os

print([Link]())

A. Prints files in working directory


B. Prints environment variables
C. Prints OS name
D. Error

:A

Which module is built-in in Python?

A. numpy
B. pandas
C. math
D. requests

• math is a built-in module included with Python.

• numpy, pandas, and requests are external modules that must be installed

separately using pip.


PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 71
What happens here?

import math

del math

print(math)

A. Prints module math


B. Error
C. None
D. 0

B
✔ math is deleted from namespace.

What does this code print?

import time

start = [Link]()

print(type(start))

A. <class 'datetime'>
B. <class 'timestamp'>
C. <class 'float'>
D. <class 'int'>

Explanation:

• [Link]() returns the current time in seconds since the epoch (January 1, 1970).

• The value is a floating-point number (to include fractions of a second).

• Therefore, type(start) is <class 'float'>.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 72


What will be printed?

from math import pi as p

import math

print(p, [Link])

Modules and System Interaction: The OS Module: File and directory operations ([Link](),
[Link](), [Link](), [Link]()), Working with file paths

The sys Module: Command-line arguments ([Link]), Exiting programs ([Link]())

OS MODULE

• OS module in Python provides functions for interacting with the operating system.
• OS comes under Python's standard utility modules.
• This module provides a portable way of using operating system-dependent functionality.

OS-Module Functions

Important functions of the Python os module:

• Handling the Current Working Directory

• Creating a Directory

• Listing out Files and Directories with Python

• Deleting Directory or Files using Python

• File Permissions and Metadata

1. Handling Current Working Directory

• The Current Working Directory (CWD) is the folder where Python is currently operating.
• When we open files without specifying a full path, Python looks for them inside this
directory.

Note: The folder where the Python script is running is known as the Current Directory. This is
not the path where the Python script is located.

1.1 Getting the Current working directory

To get the location of the current working directory, [Link]() is used.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 73


Example: This code uses the 'os' module to get and print the current working directory (CWD)
of the Python script. It retrieves the CWD using the '[Link]()' and then prints it to the console.

import os
cwd = [Link]()
print("Current working directory:", cwd)

OUTPUT
C:\Users\Welcome

1.2 Changing the Current working directory

• We can change Current Working Directory using [Link](path).


• It takes the target directory path as its only argument and switches the context to that
folder.

Note: The current working directory is the folder in which the Python script is operating.

Example: The code checks and displays the current working directory (CWD) twice: before and
after changing the directory up one level using [Link]('../'). It provides a simple example of how
to work with the current working direct

import os
def current_path():
print("Current working directory ")
print([Link]())
print()

current_path()
[Link]('../')
current_path()

Output:
Current working directory
C:\Users\MCA\Desktop\gfg
Current working directory
C:\Users\MCA\Desktop

2. Creating a Directory
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 74
There are different methods available in the OS module for creating a directory. These are:
• [Link]()
• [Link]()
2.1 Using [Link]()

[Link]() method is used to create a directory named path with the specified numeric mode.
This method raises FileExistsError if the directory to be created already exists.

EXAMPLE:

import os
# Name of the new directory
new_dir = "anitha"
# Create the directory
[Link](new_dir)
print(f"Directory '{new_dir}' created successfully!")

2.2 Using [Link]()


[Link]() method is used to create a directory recursively. That means while making leaf
directory if any intermediate-level directory is missing, [Link]() method will create them
all.

EXAMPLE
import os
# Nested directory path
nested_dir = "parent_folder/child_folder/grandchild_folder"
# Create the directories
[Link](nested_dir)
print(f"Nested directories '{nested_dir}' created successfully!")

3. Listing out Files and Directories with Python


[Link]() method is used to get the list of all files and directories in the specified directory. If
we don’t specify any directory, then the list of files and directories in the current working
directory will be returned.

EXAMPLE
Import os
# List files and directories in current working directory
entries = [Link]()
print("All entries:", entries)
# List files and directories in a specific path
path = "/Users/welcome"
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 75
entries = [Link](path)
print(f"Entries in {path}:", entries)

4. Deleting Directory or Files using Python

OS module provides different methods for removing directories and files in Python. They are:
• Using [Link]()
• Using [Link]()

4.1 Using [Link]() Method


[Link]() method is used to remove or delete a file path. This method can not remove or delete
a directory. If the specified path is a directory then OSError will be raised by the method.

EXAMPLE
import os

# Name of the file to delete


file_path = "/users/welcome/MCA/[Link]"

# Check if file exists


if [Link](file_path):
[Link](file_path)
print(f"File '{file_path}' has been deleted!")
else:
print(f"File '{file_path}' does not exist.")

WORKING WITH FILE PATHS


Absolute vs. Relative Paths in Python
1. Absolute Path: An absolute path specifies the complete location of a file or directory starting
from the root of the file system. It is unambiguous and works regardless of the current working
directory.
# Example of an absolute path on Windows
absolute_path_windows = "C:\\Users\\welocome\\MCA\\[Link]"

[Link] Path: A relative path specifies the location of a file or directory relative to the current
working directory (the directory from which the Python script is executed).

DEMONSTRATION OF ABSOLUTE VS RELATIVE PATH

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 76


PATH JOINING
• The [Link]() function in Python is used to intelligently concatenate one or more path
components into a single path string, ensuring platform-independent path construction.
• It is part of the [Link] module within Python's standard library.
• safe way to build paths across operating systems

PATHS SPLITTING - [Link](path)

Splits a path into directory and file name.

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 77


OUTPUT

Directory: C:\Users\welcome\anitha

File Name: [Link]

PS C:\Users\Welcome>

The sys Module: Command-line arguments ([Link]), Exiting programs ([Link]())

• sys module provides access to variables and functions that interact closely with Python
interpreter and runtime environment.
• It allows developers to manipulate various aspects of program execution and interpreter
itself.
Example:
import sys
print([Link])

OUTPUT:
3.10.9

code prints the version of the Python interpreter currently in use, which helps in identifying
compatibility and environment detail.

Input and Output using sys


The sys module controls program input, output and error streams, enabling precise data handling
beyond standard input and print functions.

1. [Link]:
Reads input directly from the standard input stream and supports reading multiple lines or
redirected input.
EXAMPLE

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 78


OUTPUT

NOTE: [Link]() removes the newline (\n) at the end.

2. [Link]:
Writes output to the standard output stream and allows low-level control over printed output.
import sys
[Link]('MCA')

OUTPUT: MCA
• [Link] is the standard output stream (normally your screen).
• write() prints text without automatically adding a newline.

Command-line arguments ([Link]), Exiting programs ([Link]())


1. Command-line Arguments ([Link])

• [Link] is a list that contains the command-line arguments passed to a Python program.
• Comes from the sys module → must be imported.
• Allows users to give input without using input().
• Commonly used in automation scripts, shell scripting
• Every argument is a string, so conversions (e.g., int()) may be needed.

Structure of [Link]
PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 79
• [Link][0] → the script name (automatically included)
• [Link][1] → first actual argument
• [Link][2] → second argument
• len([Link]) → number of arguments including script name
Example:

import sys

print([Link])

OUTPUT

Example 1:

import sys

print("Script name:", [Link][0])

print("Arguments passed:", [Link][1:])

Run:

REFER CLASS NOTES FOR EXAMPLES.

What is [Link]()?

• This function immediately stops program execution.


• It raises a built-in exception: SystemExit
• Useful for stopping program on errors and ending early based on conditions.
Arguments to [Link]()

[Link]() can take:

1. No argument → same as [Link](0)


PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 80
2. Integer → exit status
o 0 → success
o non-zero → error
3. String → prints the message, then exits
Example:
[Link](0) # success
[Link](1) # failure

Example 1: Basic exit

import sys
print("Program started")
[Link]()
print("This will NOT run")

Output:Program started

Example 2: Exit with error message

import sys
age = int(input("Enter your age: "))
if age < 18:
[Link]("Error: You must be 18 or older!")
print("Access granted")

output:
Enter your age: 16
Error: You must be 18 or older!

PYTHON UNIT1 NOTES (INTRODUCTION to Python) Faculty: Ms. Anitha Page 81

You might also like