(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
Stu_Unit1_CSE1.pdf
1. PROGRAMMING IN PYTHON(AGCS-21403)
UNIT- 1
Er. Neha Chadha
Assistant Professor
Department of Computer Science and Engineering
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
1
Amritsar Group of Colleges
NAAC - A grade, NBA accredited courses(2009-12, 2016-18), UGC Autonomous College
2. Part-I
Part- I
Basics of Python Programming: Features, History, future of python,
writing and executing first python program, literal constants, variables
and identifiers, data types, input operation, comments, reserved words,
indentation, operators and expressions, expressions, type conversion.
Decision control statements: Introduction, selection/conditional
branching statements, basic loop structures/iterative statements, nested
loops, break, continue and pass statements.
Functions and Modules: Introduction, function declaration and
definition, function definition, function call, variable scope and lifetime,
the return statement, recursive functions, lambda functions with map,
reduce & filter, modules, packages in python, import and reload
module, module random, os, math, sys.
2
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
3. Introduction
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
3
Python is
Interpreted
Object Oriented
High Level Programming with dynamic semantics
Compressed Code
4. Python : Compiled or Interpreted ?
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
4
5. PVM
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
5
The role of Python Virtual Machine (PVM) is to
convert the byte code instructions into machine code
so that the computer can execute those machine code
instructions and display the final output. To carry out
this conversion, PVM is equipped with an interpreter.
7. History & Versions
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
7
Python laid its foundation in the late 1980s.
The implementation of Python was started in December 1989 by GuidoVan Rossum at CWI in Netherland.
In February 1991, GuidoVan Rossum published the code (labeled version 0.9.0) to alt.sources.
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
Python 2.0 added new features such as list comprehensions, garbage collection systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the fundamental
flaw of the language.
ABC programming language is said to be the predecessor of Python language, which was capable of Exception
Handling and interfacing with theAmoeba Operating System.
The following programming languages influence Python:
✓ ABC language
✓ Modula-3
8. How was Python named?
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
8
When Guido van Rossum began implementing Python, He
was also reading the published scripts from “Monty Python's
Flying Circus”, a BBC comedy series from the 1970s. Van
Rossum thought he needed a name that was short, unique, and
slightly mysterious, so he decided to call the language Python.
9. Features
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
9
Features
Easy to Learn and Use
Expressive Language
Interpreted Language
Cross-platform Language
Free and Open Source
Object-Oriented Language
Extensible
Large Standard Library
GUI Programming Supporte
Integrated
Embeddable
Dynamic Memory Allocation
13. print function
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
13
the print keyword in Python 2.x is replaced by
the print() function in Python 3.x.
However, parentheses work in Python 2 if space is added
after the print keyword because the interpreter evaluates it
as an expression.
2.X 3.X
print(‘Hello’)
print ‘Hello’
Result: Hello
Hello
print(‘Hello’)
print ‘Hello’
Result: Hello
Syntax Error
14. Unicode
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
14
In Python 2, an implicit str type is ASCII.
But in Python 3.x implicit str type is Unicode
2.X 3.X
print(type(‘Hello’))
print(type(b‘Hello’))
Result: <type‘str’>
<type‘str’>
print(type(u‘Hello’))
Result: <type‘unicode’>
print(type(‘Hello’))
print(type(b‘Hello’))
Result: <class‘str’>
<class‘bytes’>
print(type(u‘Hello’))
Result: <class‘str’>
15. xrange
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
15
In Python 2.x, range and xrange both exist.
In Python 3.x, the only range function exist.
2.X 3.X
for i in xrange(3):
print(i)
Result: 0 1 2
for i in range(3):
print(i)
Result: 0 1 2
for i in xrange(3):
print(i)
Result: NameError
for i in range(3):
print(i)
Result: 0 1 2
16. Error Handling
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
16
There is a small change in error handling in both versions.
In python 3.x,‘as’ keyword is required.
2.X 3.X
try:
trying_to_check_error
except NameError as err:
print (err, 'Error Caused')
Result: (NameError("name
'trying_to_check_error' is not defined",),
'Error Caused')
try:
trying_to_check_error
except NameError as err:
print (err, 'Error Caused')
Result: name 'trying_to_check_error' is not
defined Error Caused
17. Setting Up the Python Development
Environment
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
17
Open a terminal window and type "python" to find out if it
is already installed and which version is installed.
18. Unix/Linux Installation
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
18
Open a Web browser and go
to https://www.python.org/downloads/.
Follow the link to download zipped source code available for
Unix/Linux.
Download and extract files.
Editing the Modules/Setup file if you want to customize some
options.
run ./configure script
make install
19. Windows Installation
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
19
Open a Web browser and go
to https://www.python.org/downloads/.
Follow the link for the Windows installer python-XYZ.msi file
where XYZ is the version you need to install.
Save the installer file to your local machine and then run it to
find out if your machine supports MSI.
Run the downloaded file.
21. Basic Syntax
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
21
Python Identifiers
A Python identifier is a name used to identify a variable,
function, class, module or other object. An identifier starts
with a letter A to Z or a to z or an underscore (_) followed
by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $,
and % within identifiers. Python is a case sensitive
programming language.
Thus, Manpower and manpower are two different
identifiers in Python.
22. Keywords
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
22
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
and exec Not
else is with
except lambda yield
else is with
23. Lines and Indentation
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
23
Python provides no braces to indicate blocks of code for class
and function definitions or flow control.
Blocks of code are denoted by line indentation
24. Multi-Line Statements
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
24
Statements in Python typically end with a new line. Python
does, however, allow the use of the line continuation
character () to denote that the line should continue.
25. Quotation in Python
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
25
Python accepts single ('), double (") quotes to denote string
literals, as long as the same type of quote starts and ends the
string.
26. Comments in Python
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
26
A hash sign (#) that is not inside a string literal begins a
comment.
""" Multiline Comment
27. Multiple Statement Groups as Suites
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
27
A group of individual statements, which make a single code
block are called suites in Python.
if expression :
suite
elif expression :
suite
else :
suite
28. Assigning Values to Variables
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
28
The equal sign (=) is used to assign values to variables.
MultipleAssignment
a=b=c=1
a,b,c=1,2.3, “Hello”
29. Data Types
Numbers
String
List
Tuple
Dictionary
Set
29 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
30. Number
Number data types store numeric values.
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and
hexadecimal)
float (floating point real values)
complex
30 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
31. String
Strings in Python are identified as a contiguous set of
characters represented in the quotation marks.
Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ]
and [:] ) with indexes starting at 0 in the beginning of the
string
The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator.
31 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
32. List
A list contains items separated by commas and enclosed
within square brackets ([]). To some extent, lists are similar
to arrays in C. One difference between them is that all the
items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list.
The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.
32 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
33. Tuple
A tuple is another sequence data type that is similar to the
list.
A tuple consists of a number of values separated by commas.
Unlike lists, however, tuples are enclosed within
parentheses().
33 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
34. Dictionary
Python's dictionaries are kind of hash table type.
They consist of key-value pairs.
A dictionary key can be numbers or strings.
Dictionaries are enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces ([]).
34 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
35. Set
Sets are used to store multiple items in a
single variable.
Sets are written with curly brackets.
Set items are unchangeable, but you can
remove items and add new items.
35 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
36. Types of Operator
36
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Bitwise Operators
Logical Operators
Membership Operators
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
39. Membership Operator
39
in
Eg :
a=(1,2,3,4)
4 in a
True
a=(1,2,3,4)
5 in a
False
not in
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
40. Identity Operator
40
is
Eg: a=10
b=15
a is b
False
is not
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
45. Conditional Statements
45
if statements
if....else statements
if..elif..else statements
nested if statements
not operator in if statement
and operator in if statement
in operator in if statement
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
46. Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
46
WAP to make simple calculator.
WAP to test whether a number is divisible by 5 and 10 or by
5 or 10.
WAP to accept marks of three subjects from the user and
print it accordingly
Marks Grade
>=90 A Grade
>=80 and <=89 B Grade
>=70 and <=79 C Grade
<70 D Grade
47. not operator in if statement
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
47
• if not – Boolean
• if not – String
• if not – List
• if not – Dictionary
• if not – Set
• if not – Tuple
Syntax:
if not value:
statement(s)
48. Control Structures
48
while
Else clause on Python while statement
Nested while Loops
One-Line while Loops
Python while loop: break and continue
Infinite while Loop
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
49. 49
for
for
Else clause on Python for statement
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
50. Using for loop
50
With list
With tuple
With Dictionary
With String
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
51. Python for loop range() function
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
51
range(stop)
range(start,stop)
range(start,stop,step)
52. Python range() function with one
parameter
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
52
Syntax: range(stop)
for n in range(4):
print(n)
53. Python range() function with two
parameters
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
53
Syntax : range(start,stop)
➢ start: Starting number of the sequence.
➢ stop: Generate numbers up to, but not including this
number.
for n in range(5,10):
print(n)
54. Python range() function with three
parameters
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
54
Syntax: range(start,stop,step)
➢ start: Starting number of the sequence.
➢ stop: Generate numbers up to, but not including this
number.
➢ step: Difference between each number in the sequence.
for n in range(0,10,3):
print(n)
55. Python range() for repeat some action
several times
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
55
for i in range(2 ** 2):
print('Python range()!!')
56. Decrementing for loops
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
56
If you want a decrementing for loops , you need to give the
range a -1 step
for i in range(5,0,-1):
print (i)
57. Nested for loop in Python
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
57
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
58. Break Statement
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
58
The break statement allows you to exit a loop from any point
within its body, bypassing its normal termination expression.
break statement in while loop
n=1
whileTrue:
print (n)
n+=1
if n==5:
break
print("After Break")
59. Continue Statement
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
59
Continue statement works like break but instead of forcing
termination, it forces the next iteration of the loop to take
place and skipping the rest of the code.
continue statement in while loop
continue statement in for loop
60. Pass Statement
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
60
It is used when a statement is required syntactically but you
do not want any command or code to execute.
The pass statement is a null operation; nothing happens
when it executes. The pass is also useful in places where
your code will eventually go, but has not been written yet.
61. Function
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
61
Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
63. Function Calling
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
63
Once the basic structure of a function is finalized, you can execute it
by calling it from another function or directly from the Python
prompt.
64. Function Argument
Call a function by using the following types of formal
arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
64 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
65. Required arguments are the arguments passed to a
function in correct positional order. Here, the number of
arguments in the function call should match exactly with the
function definition.
65 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
66. Keyword arguments are related to the function calls.
When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords
provided to match the values with parameters.
66 Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
67. Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
67
Default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument.
68. Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
68
You may need to process a function for more arguments than
you specified while defining the function. These arguments are
called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
69. Syntax
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
69
def functionname(*parameter):
"function_docstring“
function_suite
return [expression]
An asterisk (*) is placed before the variable name
that holds the values of all nonkeyword variable
arguments.
This tuple remains empty if no additional
arguments are specified during the function call.
70. Anonymous Function(Lambda)
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
70
In Python, anonymous function means that a function is without a
name.
As we already know that def keyword is used to define the normal
functions and the lambda keyword is used to create anonymous
functions.
You might want to use lambdas when you don’t want to use a
function twice in a program. They are just like normal functions
and even behave like them.
lambda function can take any number of arguments, but can only
have one expression.
Syntax
lambda arguments: expression
71. lambda()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
71
Write a function to print square of number.
Write a function to print cube of number.
Write a function to add three numbers.
Write a function to add 10 in given number.
Write a function to find the maximum of two integers.
72. Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
72
With lambda function Without lambda function
Supports single line statements
that returns some value.
Supports any number of lines
inside a function block
Good for performing short
operations/data manipulations.
Good for any cases that require
multiple lines of code.
Using lambda function can
sometime reduce the readability
of code.
We can use comments and
function descriptions for easy
readability.
73. Higher-order functions
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
73
In functional programming, higher-order functions are our
primary tool for defining computation. These are functions
that take a function as a parameter and return a function as
the result.
They can be used to do complex operations when paired
with simpler functions.
Map, Filter, and Reduce are paradigms of functional
programming.
They allow the programmer to write simpler, shorter code,
without necessarily needing to bother about loops and
branching.
74. map()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
74
The map() function is a higher-order function. As previously
stated, this function accepts another function and a sequence
of ‘iterables’ as parameters and provides output after applying
the function to each iterable in the sequence. It has the
following syntax:
SYNTAX: map(function, iterables)
75. Using map()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
75
Write a function to print square of iterables.
Write a function to print cube of iterables.
Write a function to add 10 to iterables.
Write a Python program to add two given lists using map
and lambda.
76. filter()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
76
While map() passes each element in the iterable through a
function and returns the result of all elements having passed
through the function, filter(), first of all, requires the
function to return boolean values (true or false) and then
passes each element in the iterable through the function,
"filtering" away those that are false.
SYNTAX: filter(func, iterables)
77. Using filter()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
77
Write a function to print even numbers of iterables.
Write a function to print values of iterables which are greater than
5.
Write a function to print values of iterables which are divided by 5
only.
Write a function to print scores of only those students who have
scored more than 75 in Python subject.
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]
Write a function to print palindrome in given list.
l=['666', '909', '559', '676', '560', '888', '174', '181', '165’]
Write a Python program to filter a given list to determine if the
values in the list have a length of 6 using Lambda.
78. Using reduce()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
78
The reduce() function, as the name describes, applies a given
function to the iterables and returns a single value.
reduce function works like an aggregation function.
Map and filter are in built functions in python, but we need
to import functools to use reduce function.
79. Modules
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
79
In Python, Modules are simply files with the “.py” extension
containing Python code that can be imported inside another
Python Program.
In simple terms, we can consider a module to be the same as
a code library or a file that contains a set of functions that you
want to include in your application.
80. Reload()
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
80
reload() reloads a previously imported module. This is
useful if you have edited the module source file using an
external editor and want to try out the new version without
leaving the Python interpreter.
The return value is the module object. Note: The argument
should be a module which has been successfully imported.
81. pip
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
81
pip is a package-management system written in Python used to
install and manage software packages. It connects to an online
repository of public packages, called the Python Package Index.
82. Global Variable
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
82
In Python, a variable declared outside of the function or in
global scope is known as a global variable. This means that a
global variable can be accessed inside or outside of the
function.
83. global keyword
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
83
Any variable which is changed or created inside of a
function is local if it hasn’t been declared as a global
variable. To tell Python, that we want to use the global
variable, we have to use the keyword “global”
84. Recursion
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
84
In Python, we know that a function can call other functions.
It is even possible for the function to call itself.These types of
construct are termed as recursive functions.
The following code shows the working of a recursive
function called recurse.
def recurse():
recurse()
recurse()
85. Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
85
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1
3 * 2 # return from 2nd call
6 # return from 1st call
87. Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
87
Our recursion ends when the number reduces to 1.This is
called the base condition.
Every recursive function must have a base condition that
stops the recursion or else the function calls itself infinitely.
The Python interpreter limits the depths of recursion to help
avoid infinite recursions, resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the
limit is crossed, it results in RecursionError
88. Advantages of Recursion
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
88
1. Recursive functions make the code look clean and
elegant.
2. A complex task can be broken down into simpler sub-
problems using recursion.
3. Sequence generation is easier with recursion than
using some nested iteration.
89. Disadvantages of Recursion
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
89
1. Sometimes the logic behind recursion is hard to follow
through.
2. Recursive calls are expensive (inefficient) as they take
up a lot of memory and time.
3. Recursive functions are hard to debug.
90. Formatting
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
90
91. OS Module in Python
The OS module in Python provides a way of using operating
system dependent functionality.
The functions that the OS module provides allows you to
interface with the underlying operating system
that Python is running on
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
91
92. Python OS File/Directory Methods
The os module provides a big range of useful methods to manipulate files and
directories.
Command Meaning
os.name() Returns platform name that you are working on.
os.getcwd() Return a string representing the current working directory.
os.listdir() Check the content of current working directory
os.mkdir() Make Directory
os.mkdir('C:Test') # For directory
os.mkdir('C:TestTest1') # For subdirectory
os.rmdir() Remove subdirectory or directory provided if you delete main directory
its subdirectories should be deleted first.
os.removedirs() Remove all the directories and subdirectories collectively
os.removedirs('C:TestTest1')
os.environ.get('HOME') Captured the first time the os module is imported
'C:UsersASUS'
os.rename(filename) Rename the existing directory with new .
os.rename('C:T','C:R')
os.chdir() Change directory
92
93. Sys module
Python sys module provides easy functions that allow us to
interact with the interpreter directly.
Import sys module to use sys function
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
93
94. Sys module functions
Command Meaning
sys.version Tells the version of python with details
sys.stderr.write(“Text”) Return text in red color
sys. stdout.write(“Text") Return text in blue color
sys.platform Return platform name
sys.argv() To run command line arguments
import sys
print("name"+sys.argv[0])
print("n"+sys.argv[1])
sys.copyright Gives copyright information
sys.exit() Exit function
import sys
print("hello1")
sys.exit()
print("hello2“)
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
94
95. sys.argv
import sys
print (sys.argv)
for i in range(len(sys.argv)):
if i == 0:
print ("Function name: %s" % sys.argv[0])
else:
print( "%d. argument: %s" % (i,sys.argv[i]))
Er. Neha Chadha neha.cse@acetedu.in CSE1 4thSem. Prog. In Python
95