Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Application Development Using Python - Unit 2-2

The document discusses various Python operators like arithmetic, logical, comparison, and assignment operators. It explains the usage and precedence of different operators and provides examples. The document also covers flow control statements, looping constructs, importing modules and functions of the sys module.

Uploaded by

Tushar Vaswani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Application Development Using Python - Unit 2-2

The document discusses various Python operators like arithmetic, logical, comparison, and assignment operators. It explains the usage and precedence of different operators and provides examples. The document also covers flow control statements, looping constructs, importing modules and functions of the sys module.

Uploaded by

Tushar Vaswani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Self-Learning Material

tushar.1801@gmail.com
D0OLHR8SGA

Program: MCA
Specialization: Core
Semester: 3
Course Name: Application Development using Python *
Course Code: 21VMT0C301
Unit Name: Flow Control

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Table of Contents

1. Operators …3
2. Operators precedence …4
3. Logical and Membership operators …5
4. Mixing Boolean and comparison Operator …7
5. Flow control statements … 10
6. Python looping constructs … 15
7. Importing modules … 21
8. The sys module … 23
9. Functions of the sys module

tushar.1801@gmail.com
D0OLHR8SGA

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Unit 2:
Flow Control
Unit Overview:
Once we’ve acquainted ourselves with Python shell, it is important to know how to use it
appropriately. Python is capable of a lot of easy and difficult tasks. In this unit, we put focus
on the fundamental operators that are like building blocks of the code along with variables
and keywords.
Unit Outcomes:

• Operators
• Logical and Membership operators
• Operators precedence
• Mixing Boolean and comparison Operator
tushar.1801@gmail.com
D0OLHR8SGA • Program execution
• Flow control statements
• Python looping constructs
• Importing modules
• The sys module
• Functions of the sys module

Python operators are used to perform calculations on values and variables in general. These
are standard symbols used in logical and arithmetic operations. We further look at various
Python operators.
Operators: These are the unique symbols. Eg- + , * , /, etc.
Operand: The value that the operator is applied to.
Arithmetic Operators: these are basic mathematical operations like addition, multiplication,
subtraction and division. There are 7 arithmetic operators:

Operator // Syntax Description


+ Addition of two operands

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
x+y
- Subtraction between two operands
x-y
* Multiplication of two operands
X*y
/ Division of two operands. Returns the float
x/y value.
% It is called the modulus operator and is
x%y used to find the remainder while dividing
the first operator by the second.
** The power operator gives the power values
x**y when the first operand is raised to the
second.
// Floor division operator can be used find the
x//y division of the first operand by the second
operand. It returns the floor value.

Example:

tushar.1801@gmail.com
D0OLHR8SGA

Precedence of operators:
P stands for parentheses.
E stands for exponentiation.
M stands for Multiplication (Multiplication and division have the same precedence)
Division D
A is for addition (Addition and subtraction have the same precedence)
S stands for Subtraction.
The modulus operator assists us 4etermineing the last digit/s of a number. As an example:
x% 10 -> returns the final digit
x% 100 -> return the last two digits

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Comparison Operators:
These operators compare the values on both sides and determine the relationship between
them. Relational operators are another name for them.
One must note that = is an assignment operator while == is a comparison operator.
The following are the 8 comparison operators usually used. Here, we consider an example
where a=25 and b=32;

Operator Explanation Syntax/Example


< Less than sign compares if A<b
the left hand side operator Example: if a=25, b=32
is less than the right. If it is, Returns: TRUE
returns TRUE.
> Greater than sign compares A>b
if the left hand side Example: if a=25, b=32
operator is greater than the Returns: FALSE
right. If it is, returns TRUE.
== Equal to operator checks for A == b
equality of two operands. Example: if a=25, b=32
Returns: FALSE
>= Greater than or equal to A >= b
True if the left operand Example: if a=25, b=32
tushar.1801@gmail.com exceeds or equals the right Returns: FALSE
D0OLHR8SGA operand.
<= less than or the equal to A<b
True if the left operand is Example: if a=25, b=32
less or equal to the right Returns: TRUE
operand.
is not Checks if operand one is not a is not b
the same as the other Example: if a=25, b=32
Returns: TRUE
Is Checks if operand one is the a is b
same as the other Example: if a=25, b=32
Returns: FALSE

Output:

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Assignment operators: operators used to assign values to variables are called assignment
operators.

Operator Function Example


= Assignment box = 5
-= Subtraction, equivalent to c-d box -= 2
= > box = box -2
+= Addition, equivalent to c+d Box +=2
= > box=box+2
*= Multiplication, equivalent to c*d Box *=2
= > box=box*2
/= Division, equivalent to c/d Box /=2
= > box=box/2
%= Modulus- gives the remainder of box % =2
a division problem = > box = box % 2
//= Floor division- gives the quotient Box //= 2
tushar.1801@gmail.com
D0OLHR8SGA without the decimals. = > box = box // 2
**= Exponential- raised to the power Box **=2
= > box ** 2

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Comparison operators: as the name suggests these operators are used for comparison of
two variables or values. Returns Boolean values.

Operator Function Example


== Equal to c == d
!= Not equal to c != d
> Greater than c>d
< Less than c<d
>= Greater than equal to c >= d
<= Less than equal to c <= d

tushar.1801@gmail.com
D0OLHR8SGA

Logical operators: they are used to compare two conditional statements. Returns Boolean
values.

Operator Function Example


And If both conditions are true, c > d and c > e
returns True
Or If either one of the conditions c > d or c > e
are true, then returns True
Not If c>d

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Identity Operators: they are used to compare two objects, if they are infact the same object
or not.
Operator Function Example
is If both objects are the same, c is d
returns True
is not If both objects are different, c is not d
then returns True

tushar.1801@gmail.com
D0OLHR8SGA

Boolean Operators:
Python Boolean values have only two possible values, True or False, the operators can be
completely specified in terms of the results they assign to every possible input combination.
Because they are displayed in a table, these specifications are known as truth tables.
True and False can be thought of as Boolean operators with no inputs. One of these
operators is always True, while the other is always False.
It’s sometimes useful to think of Python’s Boolean values as operators. This method, for
example, serves to remind you that they are not variables. For the same reason that you
can’t assign to +, you can’t assign to True or False.
There are only two Python Boolean values. With no inputs, a Boolean operator always
returns the same value. As a result, True and False are the only two Boolean operators that
do not accept inputs.
Not is the only Boolean operator with a single argument. It accepts one argument and
returns the inverse value: False for True and True for False.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
The table below shows all possible theoretical Boolean operators that would take one
argument:

A B A and B A or B Not A
False False False False True
True True True True False
False True False True
True False False True

With only one argument, there are only four possible operators. Aside from that, the
remaining three operators all have somewhat wacky names because they don’t exist:
Identity: Because this operator simply returns its input, removing it from your code has no
effect.
Yes, because it does not rely on its argument, this is a short-circuit operator. You could
simply replace it with True to achieve the same result.
No, because it does not rely on its argument, this is another short-circuit operator. You
could simply replace it with False to achieve the same result.
Bitwise Operators:
Bitwise operators are used in Python to perform bitwise calculations on integers. After
converting the integers to binary, operations are performed bit by bit, hence the name
tushar.1801@gmail.com
D0OLHR8SGA
bitwise operators. The result is then returned in decimal format.

Operator Function Example


& Bitwise AND : If both bits are 1, c&d
returns 1
| Bitwise OR : If either bits are 1, C|d
returns 1, else 0.
~ Bitwise NOT : returns the ~c
complement of the number
^ Bitwise XOR : if one of the bits is C^d
1 and the other is 0, then
returns 1, else 0.
>> Bitwise right shift : As a result, C >>
the bits of the number are
shifted to the right, and voids
on the left are filled with 0 (or
1, if the number is negative).
The same effect as dividing a
number by a power of two.
<< Bitwise left shift : the bits of the C <<
number are shifted to the left,
and 0 is filled on the voids on
the right. The same effect as

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
multiplying the number by a
power of two.

a=

Conditionals Statements:
As the name suggests conditional statements are those which are dependent on certain
conditions. Meaning if a person had to choose between two or more options, conditions
would play a role in determining the output of the program. They are used to control the
flow of the program based on certain conditions. To see if the condition is true or not,
comparison operators are used. Keywords in conditional statements are: if, else, and elif.
Indentation in python is important when conditional statements are used.
tushar.1801@gmail.com
D0OLHR8SGA
If-else:
When there are questions(maybe one, two or more) having one solution, and the rest
having another solution, then an if-else statement comes in handy. A block of code is
executed only when the condition is true, otherwise the second block contained inside the
‘else: ‘ is executed. If the condition is false, the interpreter does not enter the specified
block of codes.
For example, if a child is told that he would get a chocolate if he does his homework. Here
the condition is homework, if it is done, then the boy gets a chocolate, otherwise he
doesn’t. Similarly, in the world of coding, if-else statements help to execute programs where
multiple either-or or this-or-that that type of problems exist.
Here are a few more examples of If-else statements in programs:
1. A person must get grade ‘Pass’ if they score above 45 in a 100 marks test. If they
score below it, they must get a ‘Fail’.
2. If a person’s salary is more than Rs. 200000, then display ‘Pay Tax’, if it is less than
that, display ‘Not liable to Pay tax’.
3. For whether a number is positive or negative. If the integer is more than zero, then it
is positive, if it less than zero, then it is negative.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Syntax of an If -else statement:

if (condition):
code of statements if the given condition is true
else:
code of statements if the given condition is false.
Example

tushar.1801@gmail.com
D0OLHR8SGA

If-elif conditional statements:


The above given syntax is easy to implement in cases where we have two outcomes, but
what if there are more than two? For instance, if we have to divide the grading system of a
subject, say, into more than two parts. Those who score between 80-100 get “Grade A”,
those who score between 60-80 get “Grade B”, those scoring between 40-60 get “Grade C”
and the rest get “Not passed”. For such questions we use something called if-else if
statements. In python, we call it if-elif statements.
Syntax of if-else if statements:
if (condition1):
Statements if condition 1 is true.
elif (condition2):
Statements if condition 2 is true.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
elif (condition3):
Statements if condition 3 is true.

elif (condition N):
Statements if condition N is true.
else:
Statements if all the above conditions are false.
Note that the code will run even without the else part of the else if function. You can also
compare two conditions in the same condition statement using logical and identical
operators.
Example:

tushar.1801@gmail.com
D0OLHR8SGA

Nested if-else statements.


A nested if statement is an if statement within an if statement.
Syntax of a nested if statement:
if (condition1):
if (condition 1.1):
Set of statements 1.
else:
Set of statements 2.
Elif (condition2):
if (condition 2.1):
Set of statements 3.
else:
Set of statements 4.
Else:
if (condition 3.1):

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Set of statements 5.
else:
Set of statements 6.

When the first condition is true, the statements inside it are executed. Sequentially, the if
code inside it is checked. Incase the if within the bigger if is true, the conditions inside the
former are executed, otherwise the else block is executed. The interpreter enters any block
of code if and only if the condition on which its execution is dependent is true.
Example:

tushar.1801@gmail.com
D0OLHR8SGA

In the example, when the first condition is true, the statements inside it are executed.
Sequentially, the if code inside it is checked. Incase the if within the bigger if is true, the
conditions inside the former are executed, otherwise the else block is executed. The
interpreter enters any block of code if and only if the condition on which its execution is
dependent is true.

Pass Statement:
Pass statement can be used when you don’t have statements inside a set of codes. A pass
statement does not have any impact on the program. The interpreter just continues and
goes to the next statement when it reads a pass statement.
Pass is a keyword in Python.
The example shows how pass is used. The program shows no display, meaning it runs
without encountering errors but there are no statements inside the if statements, only an if,
therefore, the output is empty. It is used to execute nothing.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Loops:
When you have a condition that needs to be executed multiple times, typing it everytime
will be a task. Let’s say you want to print numbers from 1 to 100, typing all numbers will
take a lot of human time. But the program is fast, and it doesn’t take as long as humans do.
This is where the concept of using loops comes into the picture. A loop is dependent on a
tushar.1801@gmail.com
D0OLHR8SGA variable that is initialised before and runs the code the number of times specified. Every
time the loop runs it is called an iteration. For n iterations, the loop will run n times and the
codes within the loop will also run n times, making it possible for us to run multiple
statements again and again. All of it in a giffy!

While loop:
In a while loop, the set of statements keeps on repeating till the condition is true. As soon as
the condition is false, the loop ends and the set of codes written after the loop is executed.
It is used in cases when the number of iterations is unknown.
For a while loop, you first initialise a variable (conventionally i=0). Then the while condition
is written. Inside the loop, the set of statements that are to be printed in every iteration are
written. One must note that it is important to increment or decrement the initialised
variable otherwise it will become an infinite loop.

Increment means increasing the value of the variable, decrement means decreasing the
value of a variable.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Syntax of a while loop:
i=0 #you can use any variable instead of i
while(Condition1):
#code
i+=1

The above example says that I is initialised with value 0, and n with value 10. The while
condition is then checked. According to the example, if I <= n, which in this case is true, it
enters the loop. It prints Hello for the first time, and goes to the next line. i+=1 means that I
is incremented. Now the value of I changes from 0 to 1. Again, the while loop is checked. If
the condition I <= n is satisfied, then the statements inside the loop are executed again.
Since it is true, hello is printed the second time and I is incremented again. This continues
until the value of I become 11. In that case, the condition I <= n will not be satisfied because
11 is not less than 10. Thus the loop will end there.
Other examples where while loop can be used:
1. To keep printing numbers from 1 to 100.
2. To print prime numbers between 1 and 500.
3. To print multiples for 18 between 200 and 500
4. Printing factorials of numbers in descending order, etc.
tushar.1801@gmail.com
Example:
D0OLHR8SGA

range() function:
before doing for loops, one must know what the range() function do. The range() function is
an in-built python function. In a range(n,m), the code will run from the n th element to the
(m-1)th element.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
We can also increment the variables by different integers in a range by specifying it in the
range. For example, the statement I in range(1,20,2) will run from 1 to 20 and will increment
by 2.
The above example says that I is initialised with value 0, and n with value 10. The while
condition is then checked. According to the example, if I <= n, which in this case is true, it
enters the loop. It prints Hello for the first time, and goes to the next line. i+=1 means that I
is incremented. Now the value of I changes from 0 to 1. Again, the while loop is checked. If
the condition I <= n is satisfied, then the statements inside the loop are executed again.
Since it is true, hello is printed the second time and I is incremented again. This continues
until the value of I become 11. In that case, the condition I <= n will not be satisfied because
11 is not less than 10. Thus the loop will end there.
For loop:
Like any other conditional statement, the for loop is used to keep repeating a block of
statements multiple times. The number of iterations in the for loop is known, that is the
advantage of using for loops over other conditional statements.
You usually use a sequence or range or a data structure like a list, or tuple.
Syntax of a for loop:
I =0
for I in sequence/datastructue :
tushar.1801@gmail.com
D0OLHR8SGA Block of statements.
….
Statements.
Parts of the code:
1. I = 0 : it is called the iterator variable. It is a variable initialised before the for loop.
2. for I in seq/data_structure : in is a keyword in python. The statement reads as ‘for
loop with iteration variable I in the sequence specified’. Here I begins from the
initialised element position in the sequence and then the interpreter enters the
block of codes within the loop, the iteration variable increments after every loop
until the condition specified is false.
3. Set of codes: as long as the iterative variables satisfy the range/sequence mentioned,
the set of codes inside the for loop is executed.
Example:

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
In the above example, I is initialised as 0. Then the next line containing the for loop is
executed. I starts from the sequence mentioned and executes the block of codes within the
for loop. After the loop is over, I increments and repeats executing the code inside the loop
until the iterative variable exceeds the last index number of range/sequence mentioned. For
the given loop, the execution will be done 10 times beginning from 0 to 9. The loop runs
until the (n-1)th number, which in this case is 9.

Break statement:
The break statement is used when the condition of the loop is specified but one wants to
terminate the loop in between.
Syntax:
for I in range/sequence_Name/list_Name:
set of codes
break
statements.
tushar.1801@gmail.com
D0OLHR8SGA
According to the above mentioned syntax, the for loop runs per usual but when it
encounters a break statement then it exits the loop without completing all its iterations and
starts executing the statements mentioned after the loop. Break is a keyword to break the
flow of statements inside a loop.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
In the above example, the iterative variable is I, the loop begins from 1 and has to be
repeated until 20. When it enters the code, the ith iteration number is printed. Then the if
block is checked. If the ith number is divisible by 7 then the interpreter enter that block,
otherwise it enters the else block. Note that the keyword continue is used here to continue
the flow of the loop without passing any other statements. This loop will continue until 7,
after which when it satisfies the if-statement, it enters the block. First it prints “code ends
here” then it reads break. The break statement ends the loop. the interpreter exits the loop
even if the iterative variable is within the sequence/range limit. It will print the codes that
are written after the loop.
Thus, break terminates the loop.
Nested loops:
A loop within a loop is called a nested loop.
Example:

tushar.1801@gmail.com
D0OLHR8SGA

In the above example, I is initialised at 1. According to the first while loop, 1<=30 is true,
hence the interpreter enters the loop. The second while loop is checked. Since j <= 15, the
block of statements inside the loop are executed. i+2 and j are printed and then both the
variables are incremented. These types of loops- one within another, are called nested
loops.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
In the above example, the i and j variables are the iterative variables. They are initialised at
0. When the first for loop condition is satisfied, the interpreter enters the loop and then the
codes within the loop are executed. When the second loop condition is satisfied, then the
codes within the loop are executed. when the condition for j is no longer satisfied, the loop
terminates and then the outer loop runs until the specified condition is no longer satisfied.
Loops within loops are called nested loops.s

Difference between While and For loop:

Factor While Loop For loop


Syntax i=0 #or any iterative variable I =0
while(Condition1): for I in sequence/datastructue :
Block of statements.
#code ….
i+=1 Statements.
tushar.1801@gmail.com
D0OLHR8SGA Format Variable initialisation, condition Variable initialisation, condition
checking and iteration statements checking are written at the
are written at the beginning. beginning.

Condition The iterations continue infinite If the condition is not mentioned it


times if it is not mentioned. will return an error. The condition is
essential.

Iterations The number of iterations is The number of iterations is


known. unknown.

Speed For loop is faster than while loop. While loop is slower than for loop.

Modules:
Python modules are files that contain Python definitions and statements. Functions, classes,
and variables can all be defined by a module. A module may also contain executable code.
Grouping related code into modules makes it easier to understand and use the code. It also
helps to organise the code logically.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Python Module Import
Using the import statement in another Python source file, we can import the functions and
classes defined in one module into another.
When the interpreter comes across an import statement, it imports the module if it is in the
search path. A search path is a directory list that the interpreter looks through when
importing a module. To import the module calc.py, for example, place the following
command at the top of the script.
Syntax:

import module

This does not directly import the functions or classes, but rather the module. The dot(.)
operator is used to access the functions within the module.
Example:

tushar.1801@gmail.com
D0OLHR8SGA

Python’s from-import Statement

Lets consider a module called math which can be used to perform math problems. Sqrt
returns the square-root of a number and pi returns . We get the following output.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
The from statement in Python allows you to import specific attributes from a module
without importing the entire module.

tushar.1801@gmail.com
D0OLHR8SGA

Output:

The from import statement’s * symbol is used to import all the names from a module into
the current namespace.
Locating Python Modules:

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
When a module is imported into Python, the interpreter looks in several places. It will first
look for the built-in module, and if it is not found, it will look for a list of directories defined
in the sys.path. The Python interpreter looks for the module in the following way:
It begins by looking for the module in the current directory.
If the module is not found in the current directory, Python searches the shell variable
PYTHONPATH. PYTHONPATH is an environment variable that contains a list of directories.
If that fails as well, Python checks the installation-dependent list of directories that was
configured when Python was installed.
Here, sys.path is a built-in variable in the sys module. It includes a list of directories in which
the interpreter will look for the required module.
.sys module
Python’s sys module contains a number of functions and variables that can be used to
manipulate various aspects of the Python runtime environment. It allows you to operate on
the interpreter because it gives you access to variables and functions that interact heavily
with the interpreter. Sys.path is a built-in variable in the sys module that returns a list of
directories through which the interpreter will look for the required module.
When a module is imported into a Python file, the interpreter first searches its built-in
modules for the specified module. If none are found, it searches the list of directories
tushar.1801@gmail.com
defined by sys.path.
D0OLHR8SGA
It should be noted that sys.path is a regular list that can be manipulated.

To get the location of a particular module, one has to use the syntax help(moduleName).

In the preceding example, sys.version is used to return a string containing the Python
Interpreter version along with some additional information. This demonstrates how the sys
module communicates with the interpreter.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
The name of the Python modules that the current shell has imported is returned by
sys.modules.
Variables are provided by the sys modules for greater control over input or output. We can
even route the input and output to different devices. This can be accomplished by utilising
three variables:
stdin
stdout
stderr
stdin: It can be used to directly receive input from the command line. It accepts standard
input. It uses the input() method internally. It also adds ‘n’ at the end of each sentence.

tushar.1801@gmail.com
D0OLHR8SGA

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
In Python, stdout is a built-in file object that corresponds to the interpreter’s standard
output stream. Stdout is used to direct output to the screen console. Output can take any
form; it can come from a print statement, an expression statement, or even a direct input
prompt. Streams are in text mode by default. In fact, whenever a print function is called
within the code, it is first written to sys.stdout before being displayed on the screen.

Stderr: In Python, whenever an exception occurs, it is written to sys.stderr.


When used in interactive mode, sys.stderr.write() performs the same function as the object
it represents, with the addition of printing the text’s letter count.

tushar.1801@gmail.com
D0OLHR8SGA

To exit the programme, use sys.exit([arg]). Optionally, arg can be an integer indicating the
exit or another type of object. If it’s an integer, zero means “successful termination.”
It should be noted that a string can also be passed to the sys.exit() method.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
Working with modules:
1. sys.getrefcount():
To obtain the reference count for any given object, use the sys.getrefcount() method.
Python uses this value because when it reaches zero, the memory for that particular
value is deleted. The method returns the reference count for any given object. Python
uses this value because when it reaches zero, the memory for that particular value is
deleted.

tushar.1801@gmail.com
D0OLHR8SGA

2. sys.setcursionlimit() – The sys.setrecursionlimit() method is used to limit the


maximum depth of the Python interpreter stack. This limit prevents any programme
from entering infinite recursion; otherwise, infinite recursion will cause the C stack
to overflow and crash Python.
We first import the sys module and find the current recursion limit using
sys.getrecursionlimit(). We print the current limit and set the new limit ‘nlim’. We
then use the sys.setrecursionlimit for new limit. We then use it to find and print the
current recursion limit.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
3. sys.settrace() – It is used to build debuggers, profilers, and coverage tools. This is
thread-specific, and the trace must be registered using threading. A traceback is
simply the information returned when an event occurs in the code. You've probably
seen traceback when your code makes an error or throws an exception.
What sys.settrace does is register a global trace that is called whenever a frame is
created and returns our local trace function my trace whenever any of the above
events occurs.
In the below code we first define a local trace that returns itself. Then we define a
global trace function that is invoked which returns a local trace function called
‘interesting()’. Then a reference to local trace function (my_tracer) is made.

tushar.1801@gmail.com
D0OLHR8SGA

4. sys.settrace(). On a higher level, sys.settrace() notifies the Python interpreter of the


traceback.
The sys.setswitchinterval() method is used to set the thread switch interval of the
interpreter (in seconds). This floating-point value determines the optimal duration of
the timeslices allotted to Python threads running concurrently. The true value may

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
be higher, particularly if long-running internal functions or methods are used.
Furthermore, the operating system decides which thread is scheduled at the end of
the interval. The interpreter lacks its own scheduler. This controls how frequently
the interpreter checks for thread switches.

tushar.1801@gmail.com
D0OLHR8SGA

5. sys.maxsize() – It returns the largest value that a Py ssize t variable can store.
The maximum size of lists and strings in Python is determined by the Python
platform's pointer. The size returned by maxsize is determined by the platform
architecture:
32-bit: the value is 231 - 1, or 2147483647.
64-bit: the value will be 9223372036854775807, which is 263 - 1.
As an example, we first import the module and fetch the max value. We then create
a list with the maximum size and display the length of the list and print that the list is
created successfully.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
6. sys.maxint() – maxint/INT MAX denotes the maximum value that an integer can
represent. In some cases, we may need to assign a value that is greater than any
other integer value while programming. Normally, such values are assigned by hand.
Here, we first initialise the list and manually assign a larger value to variable ‘c_min’.
we then run a loop to find the minimum value, we then update c_min when a
smaller value is found in the loop and then finally the minimum value is printed.

tushar.1801@gmail.com
D0OLHR8SGA

7. sys.getdefaultencoding() – The sys.getdefaultencoding() module gives you access to


some variables used or maintained by the interpreter, as well as functions that
interact heavily with it. It contains information about the Python interpreter's
constants, functions, and methods. It is capable of manipulating the Python runtime
environment.
The sys.getdefaultencoding() method is used to retrieve the Unicode
implementation's current default string encoding.
We import the sys module, and use the sys.getdefaultencoding() method and print
the string encoding.

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.
tushar.1801@gmail.com
D0OLHR8SGA

Proprietary content. All rights reserved. Unauthorized use or distribution prohibited.


This file is meant for personal use by tushar.1801@gmail.com only.
Sharing or publishing the contents in part or full is liable for legal action.

You might also like