0% found this document useful (0 votes)
16 views67 pages

Python Functions and Arguments Explained

This document covers the fundamentals of Python functions, including their definition, syntax, types of arguments, and the return statement. It explains the concepts of variable scope, lifetime, and the differences between arguments and parameters. Additionally, it introduces anonymous functions (lambda), and the concept of first-class functions in Python.

Uploaded by

devi.j
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)
16 views67 pages

Python Functions and Arguments Explained

This document covers the fundamentals of Python functions, including their definition, syntax, types of arguments, and the return statement. It explains the concepts of variable scope, lifetime, and the differences between arguments and parameters. Additionally, it introduces anonymous functions (lambda), and the concept of first-class functions in Python.

Uploaded by

devi.j
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 - III

UNIT III - Functions:


Function Definition – Function Call – Variable Scope and its Lifetime-Return Statement. Function
Arguments: Required Arguments, Keyword Arguments, Default Arguments and Variable Length
Arguments Recursion. Python Strings: String operations- Immutable Strings - Built-in String
Methods and Functions - String Comparison. Modules: import statement- The Python module – dir()
function – Modules and Namespace – Defining our own modules.

FUNCTIONS
Python Functions
This tutorial will go over the fundamentals of Python functions, including what they are, their syntax,
their primary parts, return keywords, and significant types. We'll also look at some examples of
Python function definitions.
What are Python Functions?
A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is
known as a function. An assortment of proclamations called Python Capabilities returns the specific
errand. Python functions are necessary for intermediate-level programming and are easy to define.
Function names meet the same standards as variable names do. The objective is to define a function
and group-specific frequently performed actions. Instead of repeatedly creating the same code block
for various input variables, we can call the function and reuse the code it contains with different
variables.
Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python.
It aids in maintaining the program's uniqueness, conciseness, and structure.
Advantages of Python Functions
Pause We can stop a program from repeatedly using the same code block by including functions.
o Once defined, Python functions can be called multiple times and from any location in a
program.
o Our Python program can be broken up into numerous, easy-to-follow functions if it is
significant.
o The ability to return as many outputs as we want using a variety of arguments is one of
Python's most significant achievements.
o However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.
Syntax
# An example Python Function
def function_name( parameters ):
# code block
The accompanying components make up to characterize a capability, as seen previously.
o The start of a capability header is shown by a catchphrase called def.
o function_name is the function's name, which we can use to distinguish it from other functions.
We will utilize this name to call the capability later in the program. Name functions in Python
must adhere to the same guidelines as naming variables.
o Using parameters, we provide the defined function with arguments. Notwithstanding, they are
discretionary.
o A colon (:) marks the function header's end.
o We can utilize a documentation string called docstring in the short structure to make sense of
the reason for the capability.
o Several valid Python statements make up the function's body. The entire code block's
indentation depth-typically four spaces-must be the same.
o A return expression can get a value from a defined function.

Illustration of a User-Defined Function


We will define a function that returns the argument number's square when called.

# Example Python Code for User-Defined function


def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(6)
print( "The square of the given number is: ", object_ )
Output:
The square of the given number is: 36

Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify the arguments
it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from anywhere in the
program. An illustration of how to use the a_function function can be found below.

# Example Python Code for calling a function


# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)

# Calling the function we defined


print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Length of the string Functions is: 9

Length of the string Python is: 6

Pass by Reference vs. Pass by Value


In the Python programming language, all parameters are passed by reference. It shows that if we
modify the worth of contention within a capability, the calling capability will similarly mirror the
change. For instance,
Code

# Example Python Code for Pass by Reference vs. Value


# defining the function
def square( item_list ):
'''''''This function will find the square of items in the list'''
squares = [ ]
for l in item_list:
[Link]( l**2 )
return squares
# calling the defined function
my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )
Output:
Squares of the list are: [289, 2704, 64]

Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no worth
is provided for the contention when the capability is called. The following example demonstrates
default arguments.
Code
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument

number 1 is: 30

number 2 is: 20

Passing two arguments


number 1 is: 50

number 2 is: 30

2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a capability
with watchword contentions, the client might tell whose boundary esteem it is by looking at the
boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the Python
translator will interface the furnished watchwords to connect the qualities with its boundaries. One
more method for utilizing watchwords to summon the capability() strategy is as per the following:
Code
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )
function( 50, 30)
# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword

number 1 is: 50

number 2 is: 30

With using keyword

number 1 is: 30

number 2 is: 50

3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined positional
sequence. The number of arguments required in the method call must be the same as those provided
in the function's definition.
We should send two contentions to the capability() all put together; it will return a language structure
blunder, as seen beneath.
Code

# Python code to demonstrate the use of default arguments


# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 3
0
print( "Passing out of order arguments" )
function( 30, 20 )

# Calling function and passing only one argument


print( "Passing only one argument" )
try:
function( 30 )
except:
print( "Function needs two positional arguments" )
Output:
Passing out of order arguments

number 1 is: 30

number 2 is: 20

Passing only one argument

Function needs two positional arguments

4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However, we
need a capability. This can be accomplished with one of two types of characters:
"args" and "kwargs" refer to arguments not based on keywords.
To help you understand arguments of variable length, here's an example.
Code
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
[Link]( [Link]() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
[Link]([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']

[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]

RETURN STATEMENT:
When a defined function is called, a return statement is written to exit the function and return the
calculated value.

Syntax:

return < expression to be returned as output >


The return statement can be an argument, a statement, or a value, and it is provided as output when a
particular job or function is finished. A declared function will return an empty string if no return
statement is written.
A return statement in Python functions is depicted in the following example.
Code
# Python code to demonstrate the use of return statements
# Defining a function with return statement
def square( num ):
return num**2
# Calling function and passing arguments.
print( "With return statement" )
print( square( 52 ) )
# Defining a function without return statement
def square( num ):
num**2
# Calling function and passing arguments.
print( "Without return statement" )
print( square( 52 ) )
Output:
With return statement

2704

Without return statement

None

The Anonymous Functions


Since we do not use the def keyword to declare these kinds of Python functions, they are unknown.
The lambda keyword can define anonymous, short, single-output functions.
Arguments can be accepted in any number by lambda expressions; However, the function only
produces a single value from them. They cannot contain multiple instructions or expressions. Since
lambda needs articulation, a mysterious capability can't be straightforwardly called to print.
Lambda functions can only refer to variables in their argument list and the global domain name
because they contain their distinct local domain.
In contrast to inline expressions in C and C++, which pass function stack allocations at execution for
efficiency reasons, lambda expressions appear to be one-line representations of functions.
Syntax
Lambda functions have exactly one line in their syntax:
lambda [argument1 [,argument2... .argumentn]] : expression
Below is an illustration of how to use the lambda function:
Code
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;
# Calling the function and passing values
print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:
Value of the function is : 50

Value of the function is : 90

Scope and Lifetime of Variables


A variable's scope refers to the program's domain wherever it is declared. A capability's contentions
and factors are not external to the characterized capability. They only have a local domain as a result.
The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same
as the lifespan of its internal variables. When we exit the function, they are taken away from us. As a
result, the value of a variable in a function does not persist from previous executions.
An easy illustration of a function's scope for a variable can be found here.

Code

# Python code to demonstrate scope and lifetime of variables

#defining a function to print a number.


def number( ):
num = 50
print( "Value of num inside the function: ", num)
num = 10
number()
print( "Value of num outside the function:", num)
Output:
Value of num inside the function: 50

Value of num outside the function: 10

Here, we can see that the initial value of num is 10. Even though the function number() changed the
value of num to 50, the value of num outside of the function remained unchanged.
This is because the capability's interior variable num is not quite the same as the outer variable
(nearby to the capability). Despite having a similar variable name, they are separate factors with
discrete extensions.
Factors past the capability are available inside the capability. The impact of these variables is global.
We can retrieve their values within the function, but we cannot alter or change them. The value of a
variable can be changed outside of the function if it is declared global with the keyword global.
Python Capability inside Another Capability
Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same
everywhere they are used in a programming language. They can be stored in built-in data structures,
used as arguments, and in conditional expressions. If a programming language treats functions like
first-class objects, it is considered to implement first-class functions. Python lends its support to the
concept of First-Class functions.
A function defined within another is called an "inner" or "nested" function. The parameters of the
outer scope are accessible to inner functions. Internal capabilities are developed to cover them from
the progressions outside the capability. Numerous designers see this interaction as an embodiment.

Code

# Python code to show how to access variables of a nested functions


# defining a nested function
def word():
string = 'Python functions tutorial'
x=5
def number():
print( string )
print( x )
number()
word()
Output:
Python functions tutorial

A return statement

A return statement ends the execution of a function, and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return
statement can return a value to the calling function.

Python return statement


Introduction
The Python return statement is used to return a value from a function. The user can only use the
return statement in a function. It cannot be used outside of the Python function. A return statement
includes the return keyword and the value that will be returned after that.
Syntax of return statement:
def funtion_name():
statements
return [expression]
Program 1
def adding(x, y):
i=x+y
return i
result = adding(16, 25)
print(f'Output of adding(16, 25) function is {result}')
Output

Function Arguments
Arguments and Parameters in Python
Be it any programming language, Arguments and Parameters are the two words that cause a lot of
confusion to programmers. Sometimes, these two words are used interchangeably, but actually, they
have two different yet similar meanings. This tutorial explains the differences between these two
words and dives deep into the concepts with examples.
Both arguments and parameters are variables/ constants passed into a function. The difference is that:
1. Arguments are the variables passed to the function in the function call.
2. Parameters are the variables used in the function definition.
3. The number of arguments and parameters should always be equal except for the variable
length argument list.

Example:

def add_func(a,b):
sum = a + b
return sum
num1 = int(input("Enter the value of the first number: "))
num2 = int(input("Enter the value of the second number: "))
print("Sum of two numbers: ",add_func(num1, num2))
Output:

Enter the value of the first number: 5


Enter the value of the second number: 2
Sum of two numbers: 7
Points to grasp from the Example:
1. (num1, num2) are in the function call, and (a, b) are in the function definition.
2. (num1, num2) are arguments and (a, b) are parameters.

Mechanism:
Observe that in the above example, num1 and num2 are the values in the function call with which we
called the function. When the function is invoked, a and b are replaced with num1 and num2, the
operation is performed on the arguments, and the result is returned.
Functions are written to avoid writing frequently used logic again and again. To write a general logic,
we use some variables, which are parameters. They belong to the function definition. When we
need the function while writing our program, we need to apply the function logic on the variables we
used in our program, called the arguments. We then call the function with the arguments.
Types of Arguments:
Based on how we pass arguments to parameters, arguments are of two types:
1. Positional arguments
2. Keyword arguments

o Given some parameters, if the respective arguments are passed in order one after the other,
those arguments are called the "Positional arguments."
o If the arguments are passed by assigning them to their respective parameters in the function
call with no significance to the passing order, they are called "Keyword arguments".

Example:
def details(name, age, grade):
print("Details of student:", name)
print("age: ", age)
print("grade: ", grade)
details("Raghav", 12, 6)
details("Santhosh", grade = 6, age = 12)
Output:
Details of student: Raghav
age: 12
grade: 6
Details of student: Santhosh
age: 12
grade: 6
Points to grasp from the Example:
First Function Call:
o The function has three parameters-name, age and grade. So, it accepts three arguments.
o In the first function call:

details("Raghav", 12, 6)
The arguments are passed position-wise to the parameters, which mean according to the passed
order:
o name is replaced with "Raghav."
o age is replaced with 12 and
o grade is replaced with 6
o In the first function call, the order of passing the arguments matter. The parameters accept the
arguments in the given order only.
o In the Second Function Call:

details("Santhosh", grade = 6, age = 12)


Here, the first argument, "Santhosh", is passed based on its position to name, and the next two
arguments are passed by assignment to their respective parameters. As you can observe, here, the
position didn't matter.
Important Point:
o Keyword arguments must always follow positional arguments. If not, Python will raise a
syntax error:
If we write: details("Santhosh", age = 6, 12)
details("Santhosh", age = 6, 12)
SyntaxError: positional argument follows keyword argument
Call by Value and Call by Reference:
This is the most important concept on arguments and parameters. Based on the type of arguments
passed to the parameters, there are two methods of invoking/ calling functions-Call by value and Call
by reference.
When the values of arguments are passed into parameters in the function, the values are copied into
parameters. This method is called "Call by value".
In this method, arguments and parameters are different and are stored in different memory locations.
o Changes done on parameters inside the function do not affect the arguments in the program
and vice versa.
o Java functions/ methods follow only Call by value.

When the addresses of the arguments are passed into parameters instead of values, this method of
invoking a function is called "Call by Reference".
o Both the arguments and parameters refer to the same memory location.
o Changes to the parameters (pointers) will affect the values of the arguments in the program.
o By default, C language follows Call by value, but using the indirection operator and pointers;
we can simulate Call by reference.

Which Method does Python Follow?


Python doesn't use Call by value or Call by reference. It follows a method called "Call by
assignment". In Python, every single entity is an object. Objects are divided into Mutable and
Immutable objects. What happens in Python when we assign a value to a variable is different from
other low-level languages like C or Java.
Suppose, in the statement:
a = 20
a is the variable, and 20 is the value assigned. Here in a memory location, 20 is saved, and a is the
name we're giving to the reference we're making to the memory location. Now, if we say:
a = 21
The name stops referring to the memory location with 20 and starts to refer to another memory
location with 21.
In other languages like C, variables are the memory locations that store the values.
Example:
In C:
#include<stdio.h>
int main()
{
int a;
a = 20;
printf("%p", (void*)&a);
a = 22;
printf("\n%p", (void*)&a);
}
Output:

000000000062FE1C

000000000062FE1C
In Python:
a = 20
print(id(a))
a = 21
print(id(a))
Output:

140714950863232

140714950863264
o As you can observe: In C, after reassigning the value, the variable is still in the same memory
location, while in Python, it refers to a different memory location. (id -> address in Python).
o But that's not all. There are other types of objects too.

Now comes the concept of Mutable and Immutable objects in Python.


Mutable and Immutable Objects in Python:
1. Mutable objects are those objects/ data types in Python that we can modify after creating
them Ex: Lists, Dictionaries, Sets
2. Immutable objects, on the other hand, are objects that can't be modified once created. Ex: int,
float, strings, tuples

Example:
Mutable Objects:
a = [23, 45, 89]
print(id(a))
[Link](49)
print(id(a))
Output:

2253724439168

2253724439168
Understanding:
A list is immutable, which means we can alter or modify it after creating it. As you can observe,
when created with the name a, it is saved in the address "2253724439168". Using append(), we
altered it by appending another value. It is still in the same memory location, meaning the same
object is modified.
Immutable Objects:

a = 20
print(id(a))
a += 23
print(id(a))
Output:

140714950863232

140714950863968
Understanding:
This is the case we discussed before in the tutorial. An int object is immutable, meaning we can't
modify it once created. You might wonder we still added 23 in the above code. Observe that the
object when created is not the same object after adding. Both are in different memory locations
which means they are different objects.
So, how are arguments passed to the parameters when a function is invoked?
With all the knowledge about assignment operation in Python:
1. The passing is like a "Call by Reference" if the arguments are mutable.
2. The passing is like "Call by Value" if the arguments are immutable.

Example:
def details(name, age, grade, marks):
[Link](26)
name += " Styles"
print("Details of the student: ")
print("name: ",name)
print("age: ",age)
print("grade: ", grade)
print("marks: ", marks)
name = "Harry"
age = 15
grade = 10
marks = [25, 29, 21, 30]
details (name, age, grade, marks)
print(grade)
print(marks)
Output:

Details of the student:

name: Harry Styles

age: 15

grade: 10

marks: [25, 29, 2F1, 30, 26]

10

[25, 29, 21, 30, 26]

Variable Length Arguments in Python:


We have tried and learned the different ways of defining and calling a function in our program.
In this article, we will discuss what are the variable-length arguments in Python.
Here we will cover two types-
1. Non - Keyworded Arguments (*args)
2. Keyworded Arguments (**kwargs)

Non - Keyworded Arguments (*args)


First let us understand the properties of *args,
1. The * in *args indicates that we can pass variable number of arguments in a function in
Python.
2. We can pass any number of arguments during the function call.

The program given below illustrates the same,


#program to demonstrate *args in python
def my_func(*argp):
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Output:

Let

us

study

Data Science

and

Blockchain
Explanation-
Let's understand what we have done in the above program,
1. In the first step, we have created a function that will take variable arguments as its parameters.
2. After this, we have used a for loop that will take each element or parameter in this case and
print it.
3. Finally, we have passed six strings as the parameters in our function.
4. On executing the program, the desired output is displayed.
Let's have a look at one more program based on *args.
#program to demonstrate *args in python
def my_func(par1,par2,*argp):
#displaying the first parameter
print("The first parameter is: ",par1)
#displaying the second parameter
print("The second parameter is: ",par2)
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Output:

The first parameter is: Let

The second parameter is: us

study

Data Science

and

Blockchain
Explanation-
It's time to have a glance at the explanation of this program.
1. In the first step, we have created a function that will take two parameters and then rest as
variable arguments as its parameters.
2. In the next step, we have defined the function in which we have displayed the values of the
first two parameters.
3. After this, we have used a for loop that will take each element or parameter in this case and
print it.
4. Finally, we have passed six strings as the parameters in our function.
5. On executing the program, the desired output is displayed.

Now let us understand what is a keyworded argument or **kwargs in Python.


Keyworded Arguments (**kwargs)
Here we can pass a keyworded variable-length argument.
Some of its characteristics are-
1. The double star indicates that any number of keyworded arguments can be passed in a
function.
2. It is analogous to a dictionary where each key is mapped to a value.

Consider the program given below,


#program to demonstrate **kwargs in python
def my_func(**kwargs):
for k,v in [Link]():
print("%s=%s"%(k,v))
#passing the parameters in function
my_func(a_key="Let",b_key="us",c_key="study",d_key="Data Science",e_key="and",f_key
="Blockchain")
Output:

a_key=Let

b_key=us

c_key=study

d_key=Data Science

e_key=and

f_key=Blockchain
Explanation-
Let us see what we have done in the above program.
1. In the first step, we have created a function that takes keyworded arguments as its parameters.
2. After this, in the function definition we have specified that a for loop will be used to fetch the
key-value pair.
3. Finally, we have passed six key value pairs inside the function.
4. On executing this program, the desired output is displayed.

Consider one more program given below based on **kwargs.


#program to demonstrate **kwargs in python
def my_func(p1,**kwargs):
for k,v in [Link]():
print("%s=%s"%(k,v))
#passing the parameters in function
my_func("Let",b_key="us",c_key="study",d_key="Data Science",e_key="and",f_key="Bloc
kchain")
Output:

b_key=us

c_key=study

d_key=Data Science

e_key=and

f_key=Blockchain
Explanation-
Check out the explanation of this program,
1. In the first step, we have created a function that takes one parameter and rest as keyworded
arguments as its parameters.
2. After this, in the function definition, we have specified that a for loop will be used to fetch
the key-value pair.
3. Finally, we have passed five key-value pairs inside the function and so it displays only those
pairs in the output and doesn't consider the first string.
4. On executing this program, the desired output is displayed.

We will conclude this article with a program that illustrates how *args and **kwargs can be used in a
single program.
#program to demonstrate **kwargs in python
def my_func(*args,**kwargs):
#displaying the value of args
print("The value of args is:",args)
#displaying the value of kwargs
print("The value of kwargs is:",kwargs)
#passing the values in function
my_func("Let","us","study",a_key="Data Science",b_key="and",c_key="Blockchain")
Output:

The value of args is: ('Let', 'us', 'study')

The value of kwargs is: {'a_key': 'Data Science', 'b_key': 'and', 'c_key': 'Blockchain'}
Explanation-
1. In the first step, we have created a function that takes *args and **kwargs (non-keyworded
and keyworded arguments) as its parameters.
2. After this, we have the function definition where we have displayed the values of both
parameters.
3. Finally, we have passed six parameters in the function, from which three are strings and the
other three are key-value pairs.

On executing this program, the desired output is disp..


Python Strings:
A String is a group of [Link] you want to use text in Python,you have to use a [Link]
can use a string in the following ways in a python program.
Using Single Quotes(‘):For example,a string can be written as ‘HELLO’.
Using Double Quotes(“): Strings in double quotes are exactly same as those in single
[Link],’HELLO’ is same as “HELLO”.
Using Triple Quotes(‘’’ ‘’’):You can specify multi-line strings using triple [Link] can use as
many single quotes and double quotes as you want in a string within triple [Link] example of a
multi-line string can be given as,
‘’’Good morning everyone.
“Welcome to the world of python’.”
Happy Reading.’’’
String Concatenation:To concatenate, or combine, two strings you can use the + operator.
Example:
a = "Hello"
b = "World"
c=a+b
print(c)
Output:
HelloWorld
Unicode Strings:
Unicode is a standard encoding system that is used to represent characters from almost all
languages. Every Unicode character is encoded using a unique integer code point between 0 and
0x10FFFF . A Unicode string is a sequence of zero or more code points.
Example:
Use Unicode code points in strings: \x , \u , \[Link] should be 2, 4, or 8 digits like \xXX ,
\uXXXX , and \UXXXXXX , respectively. An error is raised if the number of digits is not correct.
Each code is treated as one character. You can check it with the built-in function len() which returns
the number of characters.
Escape Sequences:

To insert characters that are illegal in a string, use an escape [Link] escape character is
a backslash \ followed by the character you want to insert.

Example:

txt = "We are the so-called \"Vikings\" from the north."

Output:

We are the so-called “Vikings” from the north.

Raw Strings:
Raw strings are particularly useful when working with regular expressions, as they allow
you to specify patterns that may contain backslashes without having to escape them. They are also
useful when working with file paths, as they allow you to specify paths that contain backslashes
without having to escape them. Raw strings can also be useful when working with strings that
contain characters that are difficult to type or read, such as newline characters or tabs. In general,
raw strings are useful anytime you need to specify a string that contains characters that have
special meaning in Python, such as backslashes, and you want to specify those characters literally
without having to escape them.
Example:
str = r'Python\nis\easy\to\learn'
Output: Python\nis\easy\to\learn
Explanation: As we can see that the string is printed as raw,
and it neglected all newline sign(\n) or tab space (\t).

String Formatting:
String formatting in Python allows you to create dynamic strings by combining variables
and values. String formatting in Python allows you to create dynamic strings by combining
variables and values.

There are five different ways to perform string formatting in Python:

 Formatting with % Operator.


 Formatting with format() string method.
 Formatting with string literals, called f-strings.
 Formatting with String Template Class
 Formatting with center() string method.

Formatting string using % Operator


It is the oldest method of string formatting. Here we use the modulo % operator. The
modulo % is also known as the “string-formatting operator”.In this code, the % operator is used
for string formatting. The expression “%s gobbled down” % hurriedly formats the string by
replacing the %s placeholder with the value hurriedly.

Example:
print("The mangy, scrawny stray dog %s gobbled down" %'hurriedly' +
"the grain-free, organic dog food.")

Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog
food.

Python Operators:
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators:

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example Try

+ Addition x+y Try

- Subtraction x-y Try

* Multiplication x*y Try


/ Division x/y Try

% Modulus x%y Try

** Exponentiation x ** y Try

// Floor division x // y Try

Python Assignment Operators:

Assignment operators are used to assign values to variables:

Python Comparison Operators:

Comparison operators are used to compare two values:

Operator Name Example Try

== Equal x == y Try

!= Not equal x != y Try

> Greater than x>y Try


< Less than x<y Try

>= Greater than or equal to x >= y Try

<= Less than or equal to x <= y Try

Python Logical Operators:

Logical operators are used to combine conditional statements:

Operator Description Example Try

and Returns True if both statements are true x < 5 and x < 10 Try
»

or Returns True if one of the statements is true x < 5 or x < 4 Try


»

not Reverse the result, returns False if the result not(x < 5 and x < 10) Try
is true
»

Python Identity Operators:

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example Try

is Returns True if both variables are the same x is y Try


object
»

is not Returns True if both variables are not the same x is not y Try
object
»

Python Membership Operators:

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example Tr

in Returns True if a sequence with the specified value is x in y Tr


present in the object
»

not in Returns True if a sequence with the specified value is x not in y Tr


not present in the object
»

Python Bitwise Operators:

Bitwise operators are used to compare (binary) numbers:


Operator Name Description Example T

& AND Sets each bit to 1 if both bits are 1 x&y T


»

| OR Sets each bit to 1 if one of two bits is 1 x|y T


»

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y T


»

~ NOT Inverts all the bits ~x T


»

<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2 T
shift leftmost bits fall off
»

>> Signed right Shift right by pushing copies of the leftmost bit in from x >> 2 T
shift the left, and let the rightmost bits fall off
»

Operator Precedence:

Operator precedence describes the order in which operations are performed.

Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:

print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence at
the top:

Operator Description Try

Try
() Parentheses

Try
** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT Try


»

* / // % Multiplication, division, floor division, and modulus Try


»

+ - Addition and subtraction Try


»
<< >> Bitwise left and right shifts Try
»

Try
& Bitwise AND

Try
^ Bitwise XOR

Try
| Bitwise OR

== != > >= < <= is is not in not Comparisons, identity, and membership operators Try
in
»

Try
not Logical NOT

Try
and AND

Try
or OR

»
If two operators have the same precedence, the expression is evaluated from left to right.

Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the
expression from left to right:

print(5 + 4 - 7 + 3)

Formatting using format() Method


Format() method was introduced with Python3 for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders defined
by a pair of curly braces { } into a string and calling the [Link](). The value we wish to put
into the placeholders and concatenate with the string passed as parameters into the format
function.

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)


Example:
print('We all are {}.'.format('equal'))

Output:
We all are equal
Understanding Python f-string
PEP 498 introduced a new string formatting mechanism known as Literal String
Interpolation or more commonly as F-strings (because of the leading f character preceding the
string literal). The idea behind f-String in Python is to make string interpolation simpler.
To create an f-string in Python, prefix the string with the letter “f”. The string itself can be
formatted in much the same way that you would with str. format(). F-strings provide a concise
and convenient way to embed Python expressions inside string literals for formatting.

String Formatting with F-Strings:In this code, the f-string f ” My name is


{name}.” is used to interpolate the value of the name variable into the string.

Example:
name = 'Ele'
print(f"My name is {name}.")

Output:
My name is Ele
Python String Template Class

In the String module, Template Class allows us to create simplified syntax for output
specification. The format uses placeholder names formed by $ with valid
Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing
$$ creates a single escaped $:
Formatting string using Template Class:

This code imports the Template class from the string module. The Template class allows us
to create a template string with placeholders that can be substituted with actual values. Here we are
substituting the values n1 and n2 in-place of n3 and n4 in the string n.
Example:
# Python program to demonstrate
# string interpolation

from string import Template

n1 = 'Hello'
n2 = 'GeeksforGeeks'

# made a template which we used to


# pass two variable so n3 and n4
# formal and n1 and n2 actual
n = Template('$n3 ! This is $n4.')

# and pass the parameters into the


# template string.
print([Link](n3=n1, n4=n2))

Output:
Hello ! This is GeeksforGeeks.

Python String center() Method


The center() method is a built-in method in Python‘s str class that returns a new string that is
centered within a string of a specified width.

Formatting string using center() method:This code returns a new string padded
with spaces on the left and right sides.

Example:
string = "GeeksForGeeks!"
width = 30

centered_string = [Link](width)

print(centered_string)

Output:
GeeksForGeeks!
String Operations:
In python, String operators represent the different types of operations that can be employed
on the program's string type of variables. Python allows several string operators that can be applied
on the python string are as below: Assignment operator: “=.” Concatenate operator: “+.” String
repetition operator: “*.”
String operators with examples:
In python, String operators represent the different types of operations that can be employed on

the program’s string type of variables. Python allows several string operators that can be applied on

the python string are as below:

 Assignment operator: “=.”

 Concatenate operator: “+.”

 String repetition operator: “*.”

 String slicing operator: “[]”

 String comparison operator: “==” & “!=”

 Membership operator: “in” & “not in”

 Escape sequence operator: “\.”

 String formatting operator: “%” & “{}”

Example #1 – Assignment Operator “=”


Python string can be assigned to any variable with an assignment operator “= “. Python string

can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name =

“string” assigns “string” to variable var_name.

Code:

string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)

Output:

hello

hello

hello

Example #2 – Concatenate Operator “+”


Two strings can be concatenated or join using the “+” operator in python, as explained in

the below example code:

Code:

string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)

Output:

helloworld

Example #3 – String Repetition Operator “*”


The same string can be repeated in python by n times using string*n, as explained in the

below example.

Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)

Output:

helloworld helloworld

helloworld helloworld helloworld

helloworld helloworld helloworld helloworld

helloworld helloworld helloworld helloworld helloworld

Example #4 – String slicing operator “[]”


Characters from a specific index of the string can be accessed with the string[index]

operator. The index is interpreted as a positive index starting from 0 from the left side and a negative

index starting from -1 from the right side.

 string[a]: Returns a character from a positive index a of the string from the left side as

displayed in the index graph above.

 string[-a]: Returns a character from a negative index a of the string from the right side as

displayed in the index graph above.

 string[a:b]: Returns characters from positive index a to positive index b of the as displayed

in index graph above.

 string[a:-b]: Returns characters from positive index a to the negative index b of the string as

displayed in the index graph above.

 string[a:]: Returns characters from positive index a to the end of the string.
 string[:b] Returns characters from the start of the string to the positive index b.

 string[-a:]: Returns characters from negative index a to the end of the string.

 string[:-b]: Returns characters from the start of the string to the negative index b.

 string[::-1]: Returns a string with reverse order.

Code:

string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])

Output:

ello

ellowo

lloworld

hello
hellowor

ld

dlrowolleh

Example #5 – String Comparison Operator “==” & “!=”


The string comparison operator in python is used to compare two strings.

 “==” operator returns Boolean True if two strings are the same and return Boolean False if

two strings are not the same.

 “!=” operator returns Boolean True if two strings are not the same and return Boolean False if

two strings are the same.

These operators are mainly used along with if condition to compare two strings where the

decision is to be taken based on string comparison.

Code:

string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)

Output:

False
True

True

False

Example #6 – Membership Operator “in” & “not in”


Membership operator is used to searching whether the specific character is part/member of

a given input python string.

 “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in

the string.

 “a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a”

is in the string.

A membership operator is also useful to find whether a specific substring is part of a given

string.

Code:

string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)

Output:
True

False

False

True

True

False

False

Example #7 – Escape Sequence Operator “\”


To insert a non-allowed character in the given input string, an escape character is used. An

escape character is a “\” or “backslash” operator followed by a non-allowed character. An example

of a non-allowed character in python string is inserting double quotes in the string surrounded by

double-quotes.

1. Example of non-allowed double quotes in python string:

Code:

string = "Hello world I am from "India""


print(string)

Output:

File “[Link]”, line1


string=”Hello world I am from “India””

SyntaxError:invalid syntax

Example #8 – String Formatting Operator “%”


String formatting operator is used to format a string as per requirement. To insert another type of

variable along with string, the “%” operator is used along with python string. “%” is prefixed to

another character indicating the type of value we want to insert along with the python string.

Code:

name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)

Output:

Hey india

my age is 19

Hey india,my age is 19


Hey india,my subject mark is 20.560000

Mutable and Immutable in Python:

In Python, the terms “mutable” and “immutable” refer to the ability of an object to be
changed after it is [Link] object is considered mutable if its state or value can be modified after
it is created. This means that you can alter its internal data or attributes without creating a new object.
Examples of mutable objects in Python include lists, dictionaries, and sets. If you modify a mutable
object, any references to that object will reflect the [Link] of these states are integral to
Python data structure.

What is Mutable?

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’
is the ability of objects to change their values. These are often the objects that store a collection of
data.

What is Immutable?

Immutable is the when no change is possible over time. In Python, if the value of an object
cannot be changed over time, then it is known as immutable. Once created, the value of these objects
is permanent.

List of Mutable and Immutable objects:

Objects of built-in type that are mutable are:

 Lists
 Sets
 Dictionaries
 User-Defined Classes (It purely depends upon the user to define the characteristics)
Objects of built-in type that are immutable are:

 Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)


 Strings
 Tuples
 Frozen Sets
 User-Defined Classes (It purely depends upon the user to define the characteristics)
Object mutability is one of the characteristics that makes Python a dynamically typed language.
Though Mutable and Immutable in Python is a very basic concept, it can at times be a little
confusing due to the intransitive nature of immutability.

Mutable Objects in Python

#Creating a list which contains name of Indian cities


cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:

print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

Immutable Objects in Python

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

Python String Methods

Python has a set of built-in methods that you can use on [Link] string methods returns new
values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case


lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was foun

rindex() Searches the string for a specified value and returns the last position of where it was foun

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list


startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

Python Built in Functions:

Python has a set of built-in functions.

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true


ascii() Returns a readable version of an object. Replaces none-ascii characters

with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is divided by

argument2

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object

eval() Evaluates and executes an expression

exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or method)


globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute

(property/method)

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object


len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current local symbol table

map() Returns the specified iterator with the specified function applied to each item

max() Returns the largest item in an iterable

memoryview() Returns a memory view object

min() Returns the smallest item in an iterable

next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of the specified character


pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increments by 1

(by default)

repr() Returns a readable version of an object

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list


staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

super() Returns an object that represents the parent class

tuple() Returns a tuple

type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators

String Comparison in Python:


Python string equals Using Relational Operators

The relational operators compare the Unicode values of the characters of the strings from
the zeroth index till the end of the string. It then returns a boolean value according to the operator
used.
Example:

print("Geek" == "Geek")
print("Geek" < "geek")

print("Geek" > "geek")

print("Geek" != "Geek")

Output:
True
True
False
False

String Comparison in Python Using is and is not:

The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same is
the case for != and is not.
Example:

str1 = "Geek"

str2 = "Geek"

str3 = str1

print("ID of str1 =", hex(id(str1)))

print("ID of str2 =", hex(id(str2)))

print("ID of str3 =", hex(id(str3)))

print(str1 is str1)

print(str1 is str2)

print(str1 is str3)
str1 += "s"

str4 = "Geeks"

print("\nID of changed str1 =", hex(id(str1)))

print("ID of str4 =", hex(id(str4)))

print(str1 is str4)

Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True

True

ID of changed str1 = 0x7f60356137d8

ID of str4 = 0x7f60356137a0

False
The object ID of the strings may vary on different machines. The object IDs of str1, str2
and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is
changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as
in the new str1, the answer will be false as their object IDs are different.
Vice-versa will happen with is not.
String Comparison in Python Creating a user-defined function.

By using relational operators we can only compare the strings by their unicodes. In order
to compare two strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the
number of digits.
 Python3

# function to compare string


# based on the number of digits

def compare_strings(str1, str2):

count1 = 0

count2 = 0

for i in range(len(str1)):

if str1[i] >= "0" and str1[i] <= "9":

count1 += 1

for i in range(len(str2)):

if str2[i] >= "0" and str2[i] <= "9":

count2 += 1

return count1 == count2

print(compare_strings("123", "12345"))

print(compare_strings("12345", "geeks"))

print(compare_strings("12geeks", "geeks12"))

Output:
False
False
True

Python Modules:

What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example

Save this code in a file named [Link]

def greeting(name):
print("Hello, " + name)
Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

[Link]("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module:
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):

Example

Save this code in the file [Link]

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)
Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

Import and use the platform module:

import platform

x = [Link]()
print(x)
Using the dir() Function:
There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:

Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Namespaces and Modules:


(a) Object reference

 It is of paramount importance in learning Python to clearly understand what


happens 'under the hood' when an assignment command is executed. So:

What happens when 'x = 1' is executed?


 Three actions are taken:
 (a) a name 'x' (a simple sequence of characters, an
identifier) is created somewhere in the system memory
 (b) an object (a specific data structure) with value '1' is
created somewhere in memory
 (c) a binding between name x and object '1' is
established (that is: a pointer is created directing from
'x' to '1')

This binding is typically called 'object reference'

Pythontutor
 It is advisable to use online pythontutor to visualize execution of Python code
 See how pythontutor visualizes object reference

Shared object reference

 See that two (or even more names, a and c in this example) may reference the same
object (integer '1'). This is typically called "shared object reference"
(b) Namespaces

What is a namespace?

 In Python a 'namespace' is a mapping from names to their objects (values) in a


specific programming context. For example, the mapping of names a, b, c, d in the
example above on objects 1, 3 and 'spam' constructs a namespace.
 A namespace can be also conceptualized as the 'ecosystem' where a name is born,
lives and dies.
 A concrete example:
 x = 1 (a name is almost always created ('is born') by
some assignment command)
 x = 'spam' (other assignments may alter the name
binding, that is its 'object reference')
 del x (one way for a name to 'die' - that is, expelled
from the namespace- is by using the 'del' command)

In [7]:
x=1
x='spam'
print(x)

del x
print(x)
spam
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-2bb509689422> in <module>()
4
5 del x
----> 6 print(x)

NameError: name 'x' is not defined

 x=1 introduces 'x' in the namespace but name 'x' is not recognized after executing
the 'del x' command. 'x' is deleted from the namespace.

Printing values onscreen

 Please note that when working interactively in a Python shell (like, for example,
jupyter notebook) you may either use the print() function to present values
onscreen or simply write the name or expression whose value you want in the
output.
 In the latter case only the last expression in the cell will be presented in the output
unless you define otherwise by adjusting the notebook settings

In [1]:
x=1
y = 2.5
x+y
# Just writing the expression will present the outcome
Out[1]:
3.5
In [5]:
x=1
y = 2.5
print(x, y, 2*x**y)
# Better use print() when you want to present more than one values
1 2.5 2.0
(c) Modules

What is a module?

 A module is practically any .py file containing useful code (for example:
statements, functions, and classes) that can be used for code development.
 As the name implies, modules promote the idea of modular development in
practice. Python offers a simple yet powerful way to link modules and use/reuse
code in many different situations

How to connect modules

 Modules are connected using the 'import' command


 Typically you write the import command in the beginning (not necessarily though)
of your main program module, as follows:

import module_name
 The 'import' command imports the namespace of the module to the namespace of
the code you are writing in your main program. For example:

In [ ]:
import random

print([Link](1,10))

 The 'random' module offers functions for generating and managing random
numbers. The 'import random' command imports the namespace of 'random' in your
program code. We shall see more of that later.
 Note the use of 'dot notation' to refer to the imported
names: 'module_name.imported_name'. This is a practical way to visualize
namespaces and import them safely in your code.

 There are two other common ways to write the 'import' command. One you should
avoid; the other you should follow.

 Avoid this:

In [4]:
from random import *
print(randint(1,10))

 The benefit here is that you import the entire module namespace and you can use it
without writing the module name as a prefix.
 However: this technique provides no visual cues as to the origin of the names and it
may confuse you - so avoid it unless you are completely confident about your code!

 Follow this:

In [6]:
import random as rn
print([Link](1,10))

 This technique allows you to:


 (a) Use a two-letter alias for the imported module, so
the overload from writing the prefix is minimized
 (b) You still have a visual cue about the namespace.
You easily understand, for example, that the 'randint'
function comes from the 'rn' module and this is a very
very useful information in developing and debugging.
 Create your own Python Modules

 Python is a multi-purpose, high level, and dynamic programming language. It provides many
built-in modules and functions to perform various types of tasks. Aside from that, we can also
create our own modules using Python. A module is like a library in Java, C, C++, and C#. A
module is usually a file that contains functions and statements. The functions and statements
of modules provide specific functionality. A Python module is saved with the .py extension.
In this article, we will learn to create our own Python modules.

 A module is typically used to divide the large functionality into small manageable files. We
can implement our most used functions in a separate module, and later on, we can call and
use it everywhere. The module’s creation promotes reusability and saves a lot of time.

 Create Python modules


 To create a Python module, open a Python script, write some statements and functions, and
save it with .py extension. Later on, we can call and use these modules anywhere in our
program.

 Let’s create a new module named “MathOperations”. This module contains functions to
perform addition, subtraction, multiplication, and division.

 #creating MathOperation module

#the module provides addition, subtraction, multiplication, and division functions

#all the functions take two numbers as argument

#creating addition function

def addition(num1,num2):

return num1+num2

#creating subtraction function

def subtraction(num1,num2):

return num1-num2

#creating multiplication function

def multiplication(num1,num2):

return num1*num2
#creating division function

def division(num1,num2):

return num1/num2

Part- A
Choose the best answer:

1. What will be the output of above Python code?

str1="6/4"

print("str1")

a). 1
b). 6/4
c). 1.5
d). str1

2. Which of the following is False?

a). String is immutable.


b). capitalize() function in string is used to return a string by converting the whole given string into
uppercase.
c). lower() function in string is used to return a string by converting the whole given string into
lowercase.
d). None of these.

3. What is called when a function is defined inside a class?

a). class
b). function
c). method
d). module

4. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity

[Link] to connect namespace?


a) import
b) syntax
c) method
d) module

6. What will be the output of below Python code?

str1="poWer"

[Link]()

print(str1)

a). POWER
b). Power
c). power
d). poWer

[Link] will following Python code return?

str1="Stack of books"

print(len(str1))

a). 13
b). 14
c). 15
d). 16

[Link] will be the output of below Python code?

str1="Information"

print(str1[2:8])

a). format
b). formatio
c). orma
d). ormat

[Link] keyword is use for function?

a). define
b). fun
c). def
d). function

10. Which of the following items are present in the function header?
a). function name
b). parameter list
c). return value
d). Both A and B

11. Which of the following will print the pi value defined in math module?

a). print(pi)
b). print([Link])
c). from math import pi
print(pi)
d). from math import pi
print([Link])

12. Which operator is used in Python to import modules from packages?

a). .
b). *
c). ->
d). &

13. What is a variable defined outside a function referred to as?

a). local variable


b). global variable
c). static Variable
d). automatic variable

14. What is the output of the following program?z = lambda x : x * x

print(z(6))
a). 6
b). 36
c). 0
d). error

15. What is the output of the following program?

print(chr(ord(chr(97))))

a). a
b). A
c). 97
d). error

Part – B
1. Explain about Python strings?
2. Explain about Python strings operators?
3. Explain about example of a string in Python?
4. How to do length of a string in Python?
5. Why strings are immutable with an example in Python?
6. What are immutable strings in Python?
7. What are immutable strings write a short note?
8. What are string function and method in Python?
9. What are the 5 string methods?
10. What are the 2 string method in Python?

Part-C
1. What is the method string?
2. What is string function and method in Python?
3. What are the built-in types in Python?
4. What are 4 built-in data types in Python?
5. How strings are immutable in Python with example?
6. Explain about string immutable data types in Python?
7. What are examples of immutable in Python?
8. Explain about string Comparison ?
9. What are the modules and namespace in Python?
10. How to defining our own modules?

-------------------------------------------------- UNIT - 3 completed ------------------------------------------

You might also like