7/29/2021
CA-277 Python Programming
Birla Institute of Technology, Mesra
Jaipur Campus, Jaipur
S.C. Gupta, BIT, Jaipur 1
Books
TEXT BOOK
Y. Daniel Liang, “Introduction to programming using python”, Pearson
Education; First edition (2017).
REFERENCE BOOK
Martin C. Brown, “Python: The Complete Reference”, McGraw Hill
Education; Forth edition (2018)
Mark Lutz, “Learning Python” O′Reilly Fifth edition (2013)
Mark Summerfield, “Programming in Python 3: A Complete Introduction to
the Python Language” Pearson Education; Second edition (2018)
S.C. Gupta, BIT, Jaipur 2
1
7/29/2021
Operating System
• OS is the system software (computer program) that runs
on a computer.
• The major tasks of an operating system are:
Providing user interface to users
Controlling and monitoring system activities
Allocating and assigning system resources
Scheduling operations
Maintaining File and directory system
S.C. Gupta, BIT, Jaipur 4
History of Python(1985-1991)
• Created by Guido Van Rossum at CWI (Centrum
Wiskunde & Informatica) a National Research
Institute for Maths and Com. Sc. in Netherlands,
during 1985- 1991.
• Python got its name from a BBC comedy series
from seventies- “Monty Python‟s Flying Circus”.
• Follow both Procedural approach and OOP
approach (Also Monolithic approach)
• Python is derived language (from ABC, Modula,
C, C++ Algol etc), open source language and
free to use and Python source code is also
available under the GNU General Public License
(GPL).
• Being used by Google from the beginning
S.C. Gupta, BIT, Jaipur 5
2
7/29/2021
Brief History of Python
Major Versions of Python
• “Python” or “CPython” is written in C/C++
- Version 2.7 came out in mid-2010
- Version 3.1.2 came out in early 2010
Note: Python 3.x code is backward incompitable.
• “Jython” is written in Java for the JVM
• “IronPython” is written in C# for the .Net environment
S.C. Gupta, BIT, Jaipur 6
Features of python language
1 Python is a Beginner's Language, coz, Easy-to-read, learn and Maintain.
2 A broad standard library with nos. of modules.
3 Python has both the modes: Interactive and scripting.
4 Follow both Procedural approach and OOP approach, so it is Scalable and
Extendable.
5 It is slower and portable coz, Python is interpreted. (PERL, PHP etc).
6 High-level dynamic data types: Every literal or value is object And Every variable is
reference variable.
7 It provides modules for handling Databases like MySQL, networking etc
8 It provides modules to develop GUI based applications. Pyqt module.
9 Automatic garbage collection.
10 Cpython provides parallel computing
S.C. Gupta, BIT, Jaipur 7
3
7/29/2021
Installation and running of Python
-Install the Anaconda python distribution
-How to run python
a) [Link]
b) [Link]
c) [Link] (in case of Anaconda)
d) geany editor
e) Jupyter Python notebook
To check python installation:
C:\>python –V (v is in capital)
-Running the Script written using some editor
c:\>python your_script.py
S.C. Gupta, BIT, Jaipur 8
Programming style and documentation
• Good programming style and proper documentation make a
program easy to read and prevent errors.
• Proper spacing and indenting in the programming is must. E.g.
if (x > 10):
print(“hello, world”)
S.C. Gupta, BIT, Jaipur 9
4
7/29/2021
Programming Errors
Programming errors can be categorized into three types:
a) syntax errors :
These error introduces at the time of programming writing. E.g. mistyping a
statement, incorrect indentation, omitting some necessary punctuation, or using
an opening parenthesis without a corresponding closing parenthesis.
b) Runtime errors:
Runtime errors are errors that cause a program to terminate abnormally. E.g.
division by zero error.
c) Logic errors:
Logic errors occur when a program does not perform the way it was intended to.
i.e. the programming logic is not correct.
S.C. Gupta, BIT, Jaipur 10
Anatomy of Python program
• Documentation section:
Single line or multi line : Using triple quotes ( single or
double type)
• Comment Section : As and when required
Using hash # sign
Using Triple quotes (single or double)
• Import section :
• import math [Link]() [Link](), [Link]()
• from math import *
sin(), cos(), tan()
• Global variable section : (Explicitly global, by using global keyword)
• Class, function or imperative section:
S.C. Gupta, BIT, Jaipur 11
5
7/29/2021
Elementary programming
• Introduction
• Writing a Simple Program
• Reading Input from the Console
• Identifiers
• Variables
• Assignment Statements, and Expressions
• Simultaneous Assignments
• Named Constants
• Numeric Data Types and Operators
• Evaluating Expressions and Operator Precedence
• Augmented Assignment Operators
• Type Conversions and Rounding.
S.C. Gupta, BIT, Jaipur 12
Simple program
# Computation of circle area: [Link]
import math
# Assign a value to radius
radius = 20 # radius is now 20 radius 20
# Compute area
area = radius * radius * [Link] #3.14159
# Display results
print("The area for the circle of radius", radius, "is", area)
S.C. Gupta, BIT, Jaipur 13
6
7/29/2021
Reading Input from the Console
Reading input from the console enables the program to accept
Input
variable = input("Enter a value: ")
radius = eval(input("Enter a value for radius: "))
Input function by default reads strings
S.C. Gupta, BIT, Jaipur 14
Vocabulary of Python:
• Keywords (reserved words) in Python:
and, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise,
return, try, while.
S.C. Gupta, BIT, Jaipur 15
7
7/29/2021
Whitespace
Whitespace is meaningful in Python: especially indentation and
placement of newlines
•Use a newline to end a line of code
Use \ when must go to next line prematurely
•No braces {} to mark blocks of code, use consistent indentation
instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
•Colons start of a new block in many constructs, e.g. function
definitions, then clauses
S.C. Gupta, BIT, Jaipur 16
Naming conventions for Python identifiers:
• 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).
• Punctuation characters such as @, $, and % within identifiers are not allowed
• Identifiers name are case sensitive.
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Keywords are not allowed as identifiers.
S.C. Gupta, BIT, Jaipur 17
8
7/29/2021
Named Constants
A named constant is an identifier that represents a permanent value.
e.g.
PI = 3.14
To distinguish a constant from a variable, use all uppercase letters to name a
constant
There are three benefits of using constants:
1. You don’t have to repeatedly type the same value if it is used multiple times.
2. If you have to change the constant’s value (e.g., from 3.14 to 3.14159 for PI), you
need to change it only in a single location in the source code.
3. Descriptive names make the program easy to read.
S.C. Gupta, BIT, Jaipur 18
Variable assignment in Python:
• Binding a variable in Python means setting a name to hold a reference to some
object
– Assignment creates references, not copies
• Variable Names in Python do not have an intrinsic type so no need to declare it.
They become the references to values assigned to them.
• Values(or Objects) have types. Python determines the type of the reference
variable automatically based on what data is assigned to it.
• A reference is deleted via garbage collection after any names bound to it have
passed out of scope.
S.C. Gupta, BIT, Jaipur 19
9
7/29/2021
Assignments
>>> y Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-y
NameError: name „y' is not defined
1 Single assignment >>> x = 10
Multiple Assignment >>> x, y, z = 2, 3, 4
2 Swapping values >>> x, y = y, x
3 Chained Assignment >>> a = b = x = 2
4. Expression Assignment >>>x = (3*a-2*b-c)
Note: Expression may opened or
closed inside the round braces
S.C. Gupta, BIT, Jaipur 20
Expression Evaluation
A variable is a memory location
used to store a value (0.6). X= 0.6
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
Right side is an expression. 0.93
Once expression is evaluated, the result X= 0.93
is placed in (assigned to) x.
S.C. Gupta, BIT, Jaipur 21
10
7/29/2021
Data (Literal or values) type in Python:
Type Description
Integer: Number -It is single value,
xIntDec = 436 -No indexing available, so no access on
xIntOct = 0o436 individual digit via index or key etc, and
xIntHex = 0x4A5 immutable digit-wise in its place
print(type(xInt)) # <class 'int'> -4 bytes to unlimited range
Float: Number -It as single value,
xFlt = 3456.565 # fractional form -No indexing available, so no access on
xFlt = 0.1725E2 # Exponent/Scientific individual digit via index or key etc,
15E5 == 1.5E6 -Immutable digit-wise in its place coz, treated as
E or e i.e. 1.5E+2 = 15000e-2 single value
print(type(xFlt)) # <class 'float'> -Precision 15 digits,
-4 bytes to limited range (10.0 ***300 overflow)
Complex: Number [Link] returns real part and
c = a +bj [Link] returns imaginary part.
xCmpx = 3+5j or 1j or 0+1j
print(type(xCmpx)) # <class 'complex'>
S.C. Gupta, BIT, Jaipur 22
Overflow and underflow of values
Overflow:
When a variable is assigned a value that is too large (in size) to be
stored, it causes overflow. For example, executing the following
statement causes overflow.
>>>245.0 ** 1000
OverflowError: 'Result too large'
Underflow:
When a floating-point number is too small (i.e., too close to zero) to
be stored, it causes underflow. Python approximates it to zero.
So normally you should not be concerned with underflow.
S.C. Gupta,
23BIT, Jaipur
11
7/29/2021
Data (Literal or values) type in Python:
Type Description
None: x = None #eq. to Null X is referring to None object. It is similar to null.
print(type(x)) # <class 'NoneType'> A function return nothing is None.
Boolean: -It is a single value. True (1) and False (0)
xBool = True/False -Convert Boolean value to Integer value
print(type(a)) # <class 'bool'> print(int(True), int(False) ) => 1, 0
-Convert a numeric value to a Boolean value.
print(bool(n)) => False If n == 0
print(bool(p)) => True If p != 0
String: Str0 = ‘’ # empty string -Counted in sequence and as a data type
Str1 = “Python” or „python‟ -Immutable character wise in its place coz, treated as
Str3 = "guido's" single value
type(str1) # <class „str‟> -All escape sequence are string type. But the slash put
# In single line using „..‟ or “..” special meaning there. E.g. „\n‟ „\t‟ etc
Str6 = „fdgdf g gf \
just break or escape sequence of a line‟s characters.
Dgdgdgdg dg‟
# In multiple lines using triple „‟‟… „‟‟ or “”” print(“hello \n world”) => displayed in two lines
….“”” print(„‟\n\n‟) will introduce two lines
Strr = “ ” ” dfgdgdfg gdfg dgd
S.C. Gupta, BIT, Jaipur 24
Dgdfgdgd g dgdg” ” ”
Various type casting operators in python
int(7.8) => 7
int(‘34’) => 34
float(7) => 7.0
float(‘34’) => 34.0
float(’34.5’) => 34.5
complex(7) => 7 + 0.j
complex(3, -2) => 3 -2j
str(3) => ‘3’
str(5.78) => ‘5.78’
str(0o17) => ‘15’
bool(number) => True # Number may be pos. or neg. but not equal to zero
bool(0) => False
bool(‘’) => False
bool(‘a’) => True
S.C. Gupta, BIT, Jaipur 25
12
7/29/2021
eval vs int
The int function can also be used to convert an integer string into an integer.
For example, int("34") returns 34.
So we can use the eval or int function to convert a string into an integer.
The int function performs a Simple conversion. It does not work for a non-integer string.
For example, int("3.4") will cause an error.
The eval function does more than a simple conversion. It can be used to evaluate an expression.
For example, eval("3 + 4.0") returns 7.
However, there is a subtle “gotcha” for using the eval function.
The eval function will produce an error for a numeric string that contains leading zeros. In
contrast, the int function works fine for this case.
For example, eval("003") causes an error, but int("003") returns 3.
S.C. Gupta, BIT, Jaipur 26
Rounding the values
round() operator covert the number to nearest whole number.
round(7.5) => 8
round(7.499) => 7
round(7.8563543, 2) => 7.86
round(7.8553543, 2) => 7.86
S.C. Gupta, BIT, Jaipur 27
13
7/29/2021
Numeric Operators
S.C. Gupta,
28BIT, Jaipur
String concatenation and replication operators
# String concatenation using + operator
# Adding strings
s = 'jaipur ' + 'city'
print(s) => ‘jaipurcity’
# String Replication using * operator
s = 3*'$' # or '$'*3 # but '3' * '$' is invaild
print (s) => '$$$'
S.C. Gupta, BIT, Jaipur 29
14
7/29/2021
Augmented Assignment Operators
S.C. Gupta,
30BIT, Jaipur
Remainder Operator
Remainder is very useful in programming.
For example, an even number % 2 is always 0 and an odd number % 2 is always 1.
So you can use this property to determine whether a number is even or odd.
Suppose today is Saturday and you and your friends are going to meet in 10 days.
What day is in 10 days? You can find that day is Tuesday using the following
expression:
Saturday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days
S.C. Gupta,
31BIT, Jaipur
15
7/29/2021
Operator Precedence Rules
Highest precedence to lowest precedence
-Parenthesis are always respected
-Exponentiation (raise to a power) 1 + 2 ** 3 / 4 * 5
-Multiplication, Division, and Remainder
-Addition and Subtraction
-Left to right
1+8/4*5
>>> x = 1 + 2 ** 3 / 4 * 5 Note 8/4 goes before
1+2*5
>>> print(x) 4*5 because of the
11 left-right rule.
1 + 10
-When writing code - use parenthesis 11
-When writing code - keep mathematical expressions simple
enough that they are easy to understand
-Break up long series of mathematical operations to make
them more clear
S.C. Gupta, BIT, Jaipur 32
Operator Precedence
• Parenthesis +(2*3)
• +, - (Unary plus and minus)
• ** (Exponentiation)
• not
• *, /, //, % (Multiplication, division, integer division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Comparison)
• ==, != (Equality)
• and
• or
• =, +=, -=, *=, /=, //=, %= (Augmented Assignment operator)
33
16
7/29/2021
Operator Associativity
When two operators with the same precedence are evaluated, the
associativity of the operators determines the order of evaluation.
All binary operators except assignment operators are left-associative.
a – b + c – d is equivalent to ((a – b) + c) – d
Assignment operators are right-associative. Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))
34
Arithmetic Expressions
3 4 x 10( y 5)(a b c) 4 9 x
9( )
5 x x y
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
3+4*x/5
S.C. Gupta,
35BIT, Jaipur
17
7/29/2021
How to Evaluate an Expression
Though Python has its own way to evaluate an expression behind the scene, the
result of a Python expression and its corresponding arithmetic expression are the
same.
Therefore, you can safely apply the arithmetic rule for evaluating a Python expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
36 S.C. Gupta, BIT, Jaipur
Relational (Comparison) operators
# <, >
x=2<3 # True
x = 'jaipur' < 'jodhpur' # True
x = [1, 2, 3] < [10, 20] # True
x = [1, 2, 3] < [1, 2] # False
x = (1, 2, 3) < (1, 2, 4) # True
# <=, >=
x = 2<=2 # True
x = 3>=4 # False
# ==, !=
x = 2 == 3 # False
x = 2 != 3 # True
x = (True == 4) # Result is False coz, the Boolean True is equivalent 1
x = (False == 4) # Result is False coz, the Boolean False is equivalent 0
x = 2<3<4 # equivalent to 2<3 and 3<4 # True
S.C. Gupta, BIT, Jaipur 37
18
7/29/2021
Logical Operators : not, or, and
Used to create a composite condition.
not (unary opr) or( binary opr) and (binary opr)
x = True
y = not x x = 2>3 or 4>5 x = 2>3 and 4<5
x = not 5 x = 3 or 4 x = 3 and 4
x = not 0 x = 'str1' or 'str2‘ x = 'str1' and 'str2'
x = not(5>2)
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print( year, “It is a leap year”)
x = 25/5.0 or 2.0 - 20/10
print (x)
S.C. Gupta, BIT, Jaipur 38
Thanks
S.C. Gupta, BIT, Jaipur 39
19