SlideShare una empresa de Scribd logo
1 de 134
Descargar para leer sin conexión
Dr. C. Sreedhar, Associate Professor, CSE Dept., GPREC
PYTHON PROGRAMMING
Unit 1
 Introduction to Python Programming: Overview of Programming
Languages, History of Python, Installing Python, Executing Python Programs,
Commenting in Python, Internal Working of Python.
 Basics of Python Programming: Python Character Set, Token, Python Core
Data Type, I/O functions, Assigning Value to a Variable, Multiple
Assignments, Writing Simple Programs in Python, Formatting Number and
Strings, Python Inbuilt Functions.
 Operators and Expressions: Operators and Expressions, Arithmetic
Operators, Operator Precedence and Associativity, Changing Precedence
and Associativity of Arithmetic Operators, Translating Mathematical
Formulae into Equivalent Python Expressions, Bitwise Operator, The
Compound Assignment Operator
Dr. C. Sreedhar
Overview of Prog.Languagess
Python is a high-level general-
purpose programming language.
Translation of HLL into Machine
Language: Compiler, Interpreter
Compiler takes entire program as
input
Interpreter takes single instruction
as i/p
Guido van Rossum.
Python is interpreted
Python 3.0, released in 2008.
Machine / Low
level language
Assembly
Language
High level
Language
Compiler Interpreter
History of Python
 Invented in the Netherlands, early 90s by
Guido van Rossum
 Named after Monty Python
 Open sourced from the beginning
 Considered a scripting language, but is much more
 Scalable, object oriented and functional
 Used by Google
 Python 2.0 was released on 16 October 2000
 Python 3.0, released on 3 December 2008
 Currently Python 3.10.2 is the stable version
Dr. C. Sreedhar
Introduction to Python
 Object oriented language: Class, Object, Inheritance, Encapsulation, Polymorphism
 Interpreted language: is a layer of s/w logic b/w code and computer h/w on machine
 Supports dynamic data type: no variable declaration as in C
 Independent from platforms: Python code can run on virtually all operating systems and platforms
 Focused on development time: focuses mainly on software development and
deployment, enabling programmers to run data analysis and machine learning
 Simple and easy grammar
 Garbage collector: helps by avoiding memory leaks
 It’s free (open source)
Dr. C. Sreedhar
Installing Python
 Step 1: Visit www.python.org
 Step 2: Visit download section
 Step 3: Browse versions, latest stable version (3.10)
 Step 4: Click on Python 3.4.2 and download it
 Step 5: Double click on downloaded file
 Step 6: Click on setup
 Step 7: Click on Next (location to save)
 Step 8: Click on finish to complete installation
 Step 9: To check for python, in search box type python (Windows 10)
Dr. C. Sreedhar
Python modes
 Two modes: Command line and IDLE
 Command Line
 Press Start  Click on Python 3.4
 Click on Command line 32 bit
 IDLE
Executing Python Programs
Dr. C. Sreedhar
Commenting in Python
 # ie., hash symbol is used as a single line
comment
 ' ' ' ie., three consecutive single quotation
marks used as multiple comments or multi
line comments
Dr. C. Sreedhar
Internal working of python
Step 1: Interpreter reads python code or instruction, checks for syntax of each line
Step 2: Interpreter translates it into its equivalent form in byte code
Step 3: Byte code is sent and executed by Python Virtual Machine (PVM)
Dr. C. Sreedhar
Unit 1
 Introduction to Python Programming: Overview of Programming Languages, History of Python, Installing Python,
Executing Python Programs, Commenting in Python, Internal Working of Python.
 Basics of Python Programming: Python Character Set, Token, Python Core
Data Type, I/O functions, Assigning Value to a Variable, Multiple
Assignments, Writing Simple Programs in Python, Formatting Number and
Strings, Python Inbuilt Functions.
 Operators and Expressions: Operators and Expressions, Arithmetic
Operators, Operator Precedence and Associativity, Changing Precedence
and Associativity of Arithmetic Operators, Translating Mathematical
Formulae into Equivalent Python Expressions, Bitwise Operator, The
Compound Assignment Operator
Dr. C. Sreedhar
Python Character Set
Letters: Upper case and lower case letters
Digits: 0,1,2,3,4,5,6,7,8,9
Special Symbols: _ ( ) [ ] { } +, -, *, &, ^,
%, $, #, !, ' " "  Colon(:), and Semi
Colon (;)
White Spaces: (‘tnx0bx0cr’), Space,
Tab
Dr. C. Sreedhar
Python Token
 Python has the following tokens:
 Keyword
 Identifiers
 Literals
 Operators
 Delimiters/Punctuators
Dr. C. Sreedhar
Keywords in Python 3
and except nonlocal
as finally not
assert for or
break from pass
class global raise
continue if return
def import try
del in while
elif is with
Keyword Description
and logical operator
as create an alias
assert Used in debugging
break break out of a loop
class define a class
continue
continue to the next iteration of a loop
def define a function
del delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception
occurs
false
Boolean value, result of comparison operations
Keyword Description
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
none Represents a null value
nonlocal
To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
Dr. C. Sreedhar
 Rules for Identifier:
· It consist of letters and digits in any order except that the first
character must be a letter.
· The underscore (_) counts as a character.
· Spaces are not allowed.
· Special Characters are not allowed. Such as @,$ etc.
· An identifier must not be a keyword of Python.
· Variable names should be meaningful which easily depicts the logic
Dr. C. Sreedhar
int(12.456)
12
int(‘123’)
123
type(True)
<class ‘bool’>
type(False)
<class ‘bool’>
Dr. C. Sreedhar
Python Operators
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
Dr. C. Sreedhar
Arithmetic Operators
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
= X=6
+= x += 3
-= x -= 3
*= x *= 3
/= x /= 3
%= x %= 3
//= x //= 3
**= x **= 3
&= x &= 3
|= x |= 3
^= x ^= 3
>>= x >>= 3
Comparison Operators
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>=
Greater than or
equal to
x >= y
<=
Less than or
x <= y
Bitwise operators
& AND
| OR
^ XOR
~ NOT
<< Zero fill left shift
>> Signed right shift
Logical Operators
and x < 10 and x < 14
or x < 10 or x < 14
not not(x < 24 and x < 8)
Identity Operators
is x is y
is not x is not y
Python Core Data types
a = 10
b = 4+8j
c = 3.4
# List is an ordered sequence of items. (mutable)
li = [ 10, 2.6, 'Welcome' ]
# Tuple is ordered sequence of items(immutable)
t1 = ( 24, '4CSEA', 10+4j )
# Set is an unordered collection of unique items.
s2 = { 5,2,3,1,4 }
s4 = { 2.4, "4CSEA", (10, 20, 30) }
# Dictionary is unordered collection of key-value pairs.
d = { 'name':'Sree', 'Age':22 }
S4=“Welcome to 4CSEA”
I/O functions: print()
 print(1, 2, 3, 4) 1 2 3 4
 print(1, 2, 3, 4, sep='*') 1*2*3*4
 print(1, 2, 3, 4, sep='#', end='&') 1#2#3#4&
 print('The value of x is { } and y is { }'.format(x,y))
 print('The value of x is {0} and y is {1}'.format(x,y))
 print('The value of x is {1} and y is {0}'.format(x,y))
 print('The value of x is %3.2f ' %x)
 print('The value of x is %3.4f ' %x)
 print("a =", a, sep='0000', end='nnn')
 print(" Area of Circle is: ",format(Area,".2f"))
Dr. C. Sreedhar
I/O functions: print()
Example Output
print(format(10.345,”10.2f ”)) 10.35
print(format(10,”10.2f ”)) 10.00
print(format(10.32245,”10.2f ”)) 10.32
print(format(10.234566,”<10.2f ”)) #Left Justification Example
print(format(20,”10x”)) # Hexadecimal
print(format(20,”<10x”))
print(format(“Hello World!”,”20s”) # width
print(format(0.31456,”10.2%”)) # 31.46%
print(format(31.2345,”10.2e”)) # 3.12e+01
I/O functions: input()
Example
name = input("Enter your name: ")
inputString = input()
user_input = input()
a = int(input(“Enter your age:”))
val2 = float(input("Enter float number: "))
name, age, marks = input("Enter your Name, Age,
Percentage separated by space ").split()
Assigning Value to a Variable, Multiple
Assignments
 Assigning value to a variable
P = 100
Q = 100
R = 100
P = Q = R = 100
 Multiple assignments
P, Q = Q, P #Swap P with Q & Q with P
Dr. C. Sreedhar
Writing simple Programs in Python
 1. Program to accept student details such as name, age, rollno,
branch, semester, grade, address etc and display the same.
 2. Program to compute and print the perimeter and area of
different shapes such as rectangle, triangle, square, circle etc.,
 3. Program to check whether the given number is even or odd.
 4. Program to check whether the given integer is both divisible
by 4 and 9.
Dr. C. Sreedhar
1. Accept student details and print the same
name=input("Enter your name:")
age=int(input("Enter your age:"))
address=input("Enter your address:")
grade=float(input("Enter cgpa:"))
print('Your name is: {0}'.format(name))
print('Your age is: {0}'.format(age))
print('Your address is:
{0}'.format(address))
print('Your grade is:
{0}'.format(grade))
Dr. C. Sreedhar
2. Perimeter and area of shapes
 Rectangle
 area=l*b
 perimeter=2*(l+b)
 Triangle
 area=1/2*(b*h)
 perimeter=(s1+s2+s3)
 Square
 area=s*s
 perimeter=4*s
 Circle
 area = pi*r*r
 perimeter = 2*pi*r
Dr. C. Sreedhar
from math import pi
# Rectangle
l=int(input("Enter length of the rectangle: "))
b=int(input("Enter breadth of the rectangle: "))
area=l*b
perimeter=2*(l+b)
print("Perimeter of rectangle = " +str(perimeter))
print("Area of rectangle = " +str(area))
# Square
s=int(input("Enter side of the square: "))
area=s*s
perimeter=4*s
print("Perimeter of square = " +str(perimeter) )
print("Area of square = " +str(area))
Dr. C. Sreedhar
# Triangle
b=int(input("Enter base of the triangle: "))
h=int(input("Enter height of the triangle: "))
area=1/2*(b*h)
print("Area of rectangle = " +str(area))
s1=int(input("Enter side1 of triangle"))
s2=int(input("Enter side2 of triangle"))
s3=int(input("Enter side3 of triangle"))
perimeter=(s1+s2+s3)
print("Perimeter of rectangle = " +str(perimeter))
# Circle
r=float(input("Enter the radius of the circle:"))
print("Area of the circle is: "+str(pi*r**2))
print("Perimeter of the circle is: "+str(2*pi*r))
Dr. C. Sreedhar
3. Even or Odd
number=input("Enter a number")
x=int(number)%2
if x ==0:
print("Given number "+str(number)+" is even no.")
else:
print("Given number "+str(number)+" is odd no.“)
Dr. C. Sreedhar
4. Divisible by both
# Program to check whether given integer is both divisible by
4 and 9
number=int(input("Enter a number: "))
if((number%4==0) and (number%9==0)):
print("{0} is divisble by both 4 and 9".format(number))
else:
print("{0} is NOT divisble by both 4 and 9".format(number))
Dr. C. Sreedhar
Sum of digits using while loop
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Dr. C. Sreedhar
Multiplication table using loop
for i in range(1, 11):
print(num, '*', i, '=', num*i)
Dr. C. Sreedhar
lower = int(input("Enter start number in the range:"))
upper = int(input("Enter last number in the range:"))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Dr. C. Sreedhar
Accept Multiline input From a User
data = [ ]
print("Enter input, press Enter twice to exit")
while True:
line = input()
if line:
data.append(line)
else:
break
finalText = 'n'.join(data)
print("n")
print("You have entered:")
print(finalText)
Dr. C. Sreedhar
PYTHON INBUILT FUNCTIONS
 X = int(input()) #Convert it to int
X = float(input()) #Convert it to float
 The full form of eval function is to evaluate. It takes a string as
parameter and returns it as if it is a Python expression.
 eval(‘print(“Hello”)’)
 print(format(10.234566,”10.2f”)) #Right Justification Example
 print(format(10.234566,”<10.2f”)) #Left Justification Example
 print(format(20,”10x”)) #Integer formatted to Hexadecimal
Integer
 print(format(20,”<10x”))
Dr. C. Sreedhar
 Formatting Scientific Notation
 print(format(31.2345,”10.2e”))
 3.12e+01
 print(format(131.2345,”10.2e”))
 1.31e+02
Dr. C. Sreedhar
PYTHON INBUILT FUNCTIONS
 abs(x) Returns absolute value of x
 Example: abs(-2) returns 2
 abs(4) returns 4
 tan(X) : Return the tangent of X, where X is the value in radians
 math.tan(3.14/4)
 0.9992039901050427
 degrees(X) : Convert angle X from to radians to degrees
 math.degrees(1.57)
 89.95437383553924
 Radians(X) >>> math.
 radians(89.99999)
 1.5707961522619713
Dr. C. Sreedhar
High-level data types
 Numbers: int, long, float, complex
 Strings: immutable
 Lists and dictionaries: containers
 Other types for e.g. binary data, regular expressions,
introspection
 Extension modules can define new “built-in” data types
Dr. C. Sreedhar
History of Python
 Created in 1990 by Guido van Rossum
 Named after Monty Python
 First public release in 1991
 comp.lang.python founded in 1994
 Open source from the start
Dr. C. Sreedhar
Python features
no compiling or linking rapid development cycle
no type declarations simpler, shorter, more flexible
automatic memory management garbage collection
high-level data types and operations fast development
object-oriented programming code structuring and reuse, C++
embedding and extending in C mixed language systems
classes, modules, exceptions "programming-in-the-large" support
dynamic loading of C modules simplified extensions, smaller binaries
dynamic reloading of C modules programs can be modified without
stopping
Dr. C. Sreedhar
Python features
universal "first-class" object model fewer restrictions and rules
run-time program construction handles unforeseen needs, end-user
coding
interactive, dynamic nature incremental development and testing
access to interpreter information metaprogramming, introspective objects
wide portability cross-platform programming without
ports
compilation to portable byte-code execution speed, protecting source code
built-in interfaces to external services system tools, GUIs, persistence,
databases, etc.
Dr. C. Sreedhar
Where to use python?
 System management (i.e., scripting)
 Graphic User Interface (GUI)
 Internet programming
 Database (DB) programming
 Text data processing
 Distributed processing
 Numerical operations
 Graphics
 And so on…
Dr. C. Sreedhar
 Google in its web search systems
 YouTube video sharing service is largely written in Python.
 BitTorrent peer-to-peer file sharing system.
 Google’s popular App Engine web development framework
uses Python as its application language.
 EVE Online, a Massively Multiplayer Online Game (MMOG).
 Maya, a powerful integrated 3D modeling and animation
system, provides a Python scripting API.
Dr. C. Sreedhar
 Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use
Python for hardware testing.
 Industrial Light & Magic, Pixar, and others use Python in the
production of animated movies.
 JPMorgan Chase, UBS, Getco, and Citadel apply Python for
financial market forecasting.
 NASA, Los Alamos, Fermilab, JPL, and others use Python for
scientific programming tasks.
 iRobot uses Python to develop commercial robotic devices.
Dr. C. Sreedhar
 ESRI uses Python as an end-user customization tool for its
popular GIS mapping products.
 NSA uses Python for cryptography and intelligence analysis.
 The IronPort email server product uses more than 1 million lines
of Python code to do its job.
 The One Laptop Per Child (OLPC) project builds its user
interface and activity model in Python.
Dr. C. Sreedhar
Strings
 "hello"+"world" "helloworld" # concatenation
 "hello"*3 "hellohellohello" # repetition
 "hello"[0] "h" # indexing
 "hello"[-1] "o" # (from end)
 "hello"[1:4] "ell" # slicing
 len("hello") 5 # size
 "hello" < "jello" 1 # comparison
 "e" in "hello" 1 # search
 "escapes: n etc, 033 etc, if etc"
 'single quotes' """triple quotes""" r"raw strings"
Dr. C. Sreedhar
Lists
 Flexible arrays, not Lisp-like linked lists
 a = [99, "bottles of beer", ["on", "the", "wall"]]
 Same operators as for strings
 a+b, a*3, a[0], a[-1], a[1:], len(a)
 Item and slice assignment
 a[0] = 98
 a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]
 del a[-1] # -> [98, "bottles", "of", "beer"]
Dr. C. Sreedhar
Dictionaries
 Hash tables, "associative arrays"
 d = {"duck": "eend", "water": "water"}
 Lookup:
 d["duck"] -> "eend"
 d["back"] # raises KeyError exception
 Delete, insert, overwrite:
 del d["water"] # {"duck": "eend", "back": "rug"}
 d["back"] = "rug" # {"duck": "eend", "back": "rug"}
 d["duck"] = "duik" # {"duck": "duik", "back": "rug“}
Dr. C. Sreedhar
Tuples
 key = (lastname, firstname)
 point = x, y, z # parentheses optional
 x, y, z = point # unpack
 lastname = key[0]
 singleton = (1,) # trailing comma!!!
 empty = () # parentheses!
 tuples vs. lists; tuples immutable
Dr. C. Sreedhar
Variables
 No need to declare
 Need to assign (initialize)
 use of uninitialized variable raises exception
 Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
 Everything is a "variable":
 Even functions, classes, modules
Dr. C. Sreedhar
Comments
 Syntax:
# comment text (one line)
swallows2.py
1
2
3
4
5
6
# Suzy Student, CSE 142, Fall 2097
# This program prints important messages.
print("Hello, world!")
print() # blank line
print("Suppose two swallows "carry" it together.")
print('African or "European" swallows?')
Dr. C. Sreedhar
Functions
 Function: Equivalent to a static method in Java.
 Syntax:
def name():
statement
statement
...
statement
 Must be declared above the 'main' code
 Statements inside the function must be indented
hello2.py
1
2
3
4
5
6
7
# Prints a helpful message.
def hello():
print("Hello, world!")
# main (calls hello twice)
hello()
hello()
Dr. C. Sreedhar
Whitespace Significance
 Python uses indentation to indicate blocks, instead of {}
 Makes the code simpler and more readable
 In Java, indenting is optional. In Python, you must indent.
hello3.py
1
2
3
4
5
6
7
8
# Prints a helpful message.
def hello():
print("Hello, world!")
print("How are you?")
# main (calls hello twice)
hello()
hello()
Dr. C. Sreedhar
Python’s Core Data Types
 Numbers: Ex: 1234, 3.1415, 3+4j, Decimal, Fraction
 Strings: Ex: 'spam', "guido's", b'ax01c'
 Lists: Ex: [1, [2, 'three'], 4]
 Dictionaries: Ex: {'food': 'spam', 'taste': 'yum'}
 Tuples: Ex: (1, 'spam', 4, 'U')
 Files: Ex: myfile = open('eggs', 'r')
 Sets: Ex: set('abc'), {'a', 'b', 'c'}
Dr. C. Sreedhar
Builtin Data type: Number
 >>> 123 + 222 # Integer addition
 345 >>> 1.5 * 4 # Floating-point multiplication 6.0
 >>> 2 ** 100 # 2 to the power 100
1267650600228229401496703205376
 >>> 3.1415 * 2 # repr: as code 6.2830000000000004
 >>> print(3.1415 * 2) # str: user-friendly 6.283
Dr. C. Sreedhar
Builtin Data type: Number
 >>> import math
 >>> math.pi 3.1415926535897931
 >>> math.sqrt(85
 >>> import random
 >>> random.random() 0.59268735266273953
 >>> random.choice([1, 2, 3, 4]) 1) 9.2195444572928871
Dr. C. Sreedhar
Builtin Data type: String
 Strings are used to record textual information
 strings are sequences of one-character strings; other types of
sequences include lists and tuples.
 >>> S = 'Spam'
 >>> len(S) # Length 4
 >>> S[0] # The first item in S, indexing by zero-based position 'S'
 >>> S[1] # The second item from the left 'p'
 >>> S[-1] # The last item from the end in S 'm'
 >>> S[-2] # The second to last item from the end 'a'
Dr. C. Sreedhar
 >>> S[-1] # The last item in S 'm'
 >>> S[len(S)-1] # Negative indexing, the hard way 'm'
 >>> S # A 4-character string 'Spam'
 >>> S[1:3] # Slice of S from offsets 1 through 2 (not 3) 'pa'
Dr. C. Sreedhar
 >>> S[1:] # Everything past the first (1:len(S)) 'pam'
 >>> S # S itself hasn't changed 'Spam'
 >>> S[0:3] # Everything but the last 'Spa'
 >>> S[:3] # Same as S[0:3] 'Spa'
 >>> S[:-1] # Everything but the last again, but simpler (0:-1)
'Spa'
 >>> S[:] # All of S as a top-level copy (0:len(S)) 'Spam'
Dr. C. Sreedhar
 >>> S Spam'
 >>> S + 'xyz' # Concatenation
 'Spamxyz'
 >>> S # S is unchanged 'Spam'
 >>> S * 8 # Repetition
'SpamSpamSpamSpamSpamSpamSpamSpam'
Dr. C. Sreedhar
 Immutable:
 immutable in Python—they cannot be changed in-place after they
are created.
 >>> S 'Spam'
 >>> S[0] = 'z' # Immutable objects cannot be changed ...error text
omitted... TypeError: 'str' object does not support item assignment
 >>> S = 'z' + S[1:] # But we can run expressions to make new
objects
 >>> S 'zpam'
Dr. C. Sreedhar
 >>> S.find('pa') # Find the offset of a substring 1
 >>> S 'Spam'
 >>> S.replace('pa', 'XYZ') # Replace occurrences of a
substring with another 'SXYZm'
 >>> S 'Spam'
Dr. C. Sreedhar
 >>> line = 'aaa,bbb,ccccc,dd'
 >>> line.split(',') # Split on a delimiter into a list of substrings ['aaa',
'bbb', 'ccccc', 'dd']
 >>> S = 'spam'
 >>> S.upper() # Upper- and lowercase conversions 'SPAM'
 >>> S.isalpha() # Content tests: isalpha, isdigit, etc. True
 >>> line = 'aaa,bbb,ccccc,ddn'
 >>> line = line.rstrip() # Remove whitespace characters on the right side
 >>> line 'aaa,bbb,ccccc,dd'
Dr. C. Sreedhar
 >>> '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting
expression (all) 'spam, eggs, and SPAM!'
 >>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting
method (2.6, 3.0) 'spam, eggs, and SPAM!'
Dr. C. Sreedhar
 >>> S = 'AnBtC' # n is end-of-line, t is tab >>> len(S) #
Each stands for just one character 5
 >>> ord('n') # n is a byte with the binary value 10 in ASCII
10
 >>> S = 'A0B0C' # 0, a binary zero byte, does not
terminate string
 >>> len(S) 5
Dr. C. Sreedhar
Pattern Matching
 to do pattern matching in Python, we import a module called
re.
 This module has analogous calls for searching, splitting, and
replacement.
 >>> import re
 >>> match = re.match('Hello[ t]*(.*)world', 'Hello Python
world')
 >>> match.group(1) 'Python '
Dr. C. Sreedhar
Python vs. Java
 Code 5-10 times more concise
 Dynamic typing
 Much quicker development
 no compilation phase
 less typing
 Yes, it runs slower
 but development is so much faster!
 Similar (but more so) for C/C++
 Use Python with Java: JPython!
Dr. C. Sreedhar
Installing Python: Linux/Ubuntu
 Install Python 3.6:
 1. To follow the installation procedure, you need to be connected to the Internet.
 2. Open the terminal by pressing Ctrl + Alt + T keys together.
 3. Install Python 3.6:
 a. For Ubuntu 16.04 and Ubuntu 17.04:
 i. In the terminal, run the command sudo apt-get install python3.6
 ii. Press Enter.
 iii. The terminal will prompt you for your password, type it in to the terminal.
 iv. Press Enter.
 b. For Ubuntu 17.10 and above, the system already comes with Python 3.6installed by default.
 To check Python is installed or not, open terminal and enter command: python3 --version
Dr. C. Sreedhar
Installing Python: Windows
 Install Python 3.6:
 1. To follow the installation procedure, you need to be connected to the Internet.
 2. Visit https://www.python.org/downloads/release/python-368/
 3. At the bottom locate Windows x86-64 executable installer for 64 bits OS and
 Windows x86 executable installer for 32 bits OS
 4. Click on the located installer file to download.
 5. After download completes, double click on the installer file to start the
installation procedure.
 6. Follow the instructions as per the installer
Dr. C. Sreedhar
Executing Python Programs
 Linux
 Open text editor, type the source code and save the program with .py
extension (Ex: ex1.py)
 Open terminal, run the command python
 Run the program using the command, python ex1.py
 Google Colab
 Instructions to execute python program is sent to your official email id
 Jupyter Notebook
 Run Jupyter Notebook and copy paste URL in the browser
 Type the source code in the cell and press CTRL+Enter
Dr. C. Sreedhar
Unit 2
 Decision Statements: Boolean Type, Boolean Operators, Using
Numbers with Boolean Operators, Using String with Boolean
Operators, Boolean Expressions and Relational Operators,
Decision Making Statements, Conditional Expressions.
 Loop Control Statements: while Loop, range() Function, for Loop,
Nested Loops, break, continue.
 Functions: Syntax and Basics of a Function, Use of a Function,
Parameters and Arguments in a Function, The Local and Global
Scope of a Variable, The return Statement, Recursive Functions,
The Lambda Function.
Dr. C. Sreedhar
Boolean type
Python boolean data type has two values: True and False.
bool() function is used to test if a value is True or False.
a = True
type(a)
bool
b = False
type(b)
bool
branch = "CSE"
sem = 4
section =''
print(bool(branch))
print(bool(sem))
print(bool(section))
print(bool(["app", “bat", “mat"]))
True
True
False
True
Dr. C. Sreedhar
Boolean operators
not
and
or
A=True
B=False
print(A and B)
print(A or B)
print(not A)
False
True
False
A=True
B=False
C=False
D= True
print((A and D) and (B or C))
print((A and D) or (B or C))
False
True
Dr. C. Sreedhar
Write code that counts the number of words in
sentence that contain either an “a” or an “e”.
sentence=input()
words = sentence.split(" ")
count = 0
for i in words:
if (('a' in i) or ('e' in i)) :
count +=1
print(count)
Welcome to Computer Science and Engineering
5
Dr. C. Sreedhar
BOOLEAN EXPRESSIONS AND RELATIONAL
OPERATORS
2 < 4 or 2
True
2 < 4 or [ ]
True
5 > 10 or 8
8
print(1 <= 1)
print(1 != 1)
print(1 != 2)
print("CSEA" != "csea")
print("python" != "python")
print(123 == "123")
True
False
True
True
False
False
Dr. C. Sreedhar
x = 84
y = 17
print(x >= y)
print(y <= x)
print(y < x)
print(x <= y)
print(x < y)
print(x % y == 0)
True
True
True
False
False
False
x = True
y = False
print(not y)
print(x or y)
print(x and not y)
print(not x)
print(x and y)
print(not x or y)
True
True
True
False
False
False
Dr. C. Sreedhar
Decision statements
Python supports the following decision-
making statements.
if statements
if-else statements
Nested if statements
Multi-way if-elif-else statements
Dr. C. Sreedhar
if
 Write a program that prompts a user to enter two integer values.
Print the message ‘Equals’ if both the entered values are equal.
 if num1- num2==0: print(“Both the numbers entered are Equal”)
 Write a program which prompts a user to enter the radius of a circle.
If the radius is greater than zero then calculate and print the area
and circumference of the circle
if Radius>0:
Area=Radius*Radius*pi
.........
Dr. C. Sreedhar
 Write a program to calculate the salary of a medical
representative considering the sales bonus and incentives
offered to him are based on the total sales. If the sales
exceed or equal to 1,00,000 follow the particulars of
Column 1, else follow Column 2.
Dr. C. Sreedhar
Sales=float(input(‘Enter Total Sales of the Month:’))
if Sales >= 100000:
basic = 4000
hra = 20 * basic/100
da = 110 * basic/100
incentive = Sales * 10/100
bonus = 1000
conveyance = 500
else:
basic = 4000
hra = 10 * basic/100
da = 110 * basic/100
incentive = Sales * 4/100
bonus = 500
conveyance = 500
salary= basic+hra+da+incentive+bonus+conveyance
# print Sales,basic,hra,da,incentive,bonus,conveyance,sal
Dr. C. Sreedhar
Write a program to read three numbers from a user and
check if the first number is greater or less than the other
two numbers.
if num1>num2:
if num2>num3:
print(num1,”is greater than “,num2,”and “,num3)
else:
print(num1,” is less than “,num2,”and”,num3)
Dr. C. Sreedhar
Finding the Number of Days in a Month
flag = 1
month = (int(input(‘Enter the month(1-12):’)))
if month == 2:
year = int(input(‘Enter year:’))
if (year % 4 == 0) and (not(year % 100 == 0)) or (year % 400 == 0):
num_days = 29
else:
num_days = 28
elif month in (1,3,5,7,8,10,12):
num_days = 31
elif month in (4, 6, 9, 11):
num_days = 30
else:
print(‘Please Enter Valid Month’)
flag = 0
if flag == 1:
print(‘There are ‘,num_days, ‘days in’, month,’ month’)
Dr. C. Sreedhar
Write a program that prompts a user to enter two different
numbers. Perform basic arithmetic operations based on the
choices.
.......
if choice==1:
print(“ Sum=,”is:”,num1+num2)
elif choice==2:
print(“ Difference=:”,num1-num2)
elif choice==3:
print(“ Product=:”,num1*num2)
elif choice==4:
print(“ Division:”,num1/num2)
else:
print(“Invalid Choice”)
Dr. C. Sreedhar
Multi-way if-elif-else Statements: Syntax
If Boolean-expression1:
statement1
elif Boolean-expression2 :
statement2
elif Boolean-expression3 :
statement3
- - - - - - - - - - - - - -
- - - - - - - - - - - -- -
elif Boolean-expression n :
statement N
else :
Statement(s)
Dr. C. Sreedhar
CONDITIONAL EXPRESSIONS
if x%2==0:
x = x*x
else:
x = x*x*x
x=x*x if x % 2 == 0 else x*x*x
min=print(‘min=‘,n1) if n1<n2 else print(‘min = ‘,n2)
a=int(input(“Enter number: “)
print(‘even’) if(a%2) ==0 else print(‘Odd’)
Dr. C. Sreedhar
Loop Controlled Statements
while Loop
range() Function
for Loop
Nested Loops
break Statement
continue Statement
Dr. C. Sreedhar
Multiplication table using while in reverse order
num=int(input("Enter no: "))
count = 10
while count >= 1:
prod = num * count
print(num, "x", count, "=", prod)
count = count - 1
Enter no: 4
4 x 10 = 40
4 x 9 = 36
4 x 8 = 32
4 x 7 = 28
4 x 6 = 24
4 x 5 = 20
4 x 4 = 16
4 x 3 = 12
4 x 2 = 8
4 x 1 = 4
Dr. C. Sreedhar
num=int(input(“Enter the number:”))
fact=1
ans=1
while fact<=num:
ans*=fact
fact=fact+1
print(“Factorial of”,num,” is: “,ans)
Factorial of a given number
Dr. C. Sreedhar
text = "Engineering"
for character in text:
print(character)
E
n
g
i
n
e
e
r
i
n
g
courses = ["Python", "Computer Networks", "DBMS"]
for course in courses:
print(course)
Python
Computer Networks
DBMS
Dr. C. Sreedhar
for i in range(10,0,-1):
print(i,end=" ")
# 10 9 8 7 6 5 4 3 2 1
range(start,stop,step size)
Dr. C. Sreedhar
Program which iterates through integers from 1 to 50 (using for loop).
For an integer that is even, append it to the list even numbers.
For an integer that is odd, append it the list odd numbers
even = []
odd = []
for number in range(1,51):
if number % 2 == 0:
even.append(number)
else:
odd.append(number)
print("Even Numbers: ", even)
print("Odd Numbers: ", odd)
Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
Dr. C. Sreedhar
matrix=[]
for i in range(2):
row=[]
for j in range(2):
num=int(input())
row.append(num)
matrix.append(row)
print(matrix)
Accept matrix elements and display
Dr. C. Sreedhar
for i in range(1,100,1):
if(i==11):
break
else:
print(i, end=” “)
1 2 3 4 5 6 7 8 9 10
break
Dr. C. Sreedhar
for i in range(1,11,1):
if i == 5:
continue
print(i, end=” “)
1 2 3 4 6 7 8 9 10
continue
Dr. C. Sreedhar
function Dr. C. Sreedhar
def square(num):
return num**2
print (square(2))
print (square(3))
Function: Example
Dr. C. Sreedhar
def disp_values(a,b=10,c=20):
print(“ a = “,a,” b = “,b,”c= “,c)
disp_values(15)
disp_values(50,b=30)
disp_values(c=80,a=25,b=35)
a = 15 b = 10 c= 20
a = 50 b = 30 c= 20
a = 25 b = 35 c= 80
Dr. C. Sreedhar
LOCAL AND GLOBAL SCOPE OF A VARIABLE
p = 20 #global variable p
def Demo():
q = 10 #Local variable q
print(‘Local variable q:’,q)
print(‘Global Variable p:’,p)
Demo()
print(‘global variable p:’,p)
Local variable q: 10
Global Variable p: 20
global variable p: 20
Dr. C. Sreedhar
a = 20
def Display():
a = 30
print(‘a in function:’,a)
Display()
print(‘a outside function:’,a)
a in function: 30
a outside function: 20
Dr. C. Sreedhar
Write a function calc_Distance(x1, y1, x2, y2) to calculate the distance
between two points represented by Point1(x1, y1) and Point2 (x2, y2).
The formula for calculating distance is:
import math
def EuclD (x1, y1, x2, y2):
dx=x2-x1
dx=math.pow(dx,2)
dy=y2-y1
dy=math.pow(dy,2)
z = math.pow((dx + dy), 0.5)
return z
print("Distance = ",(format(EuclD(4,4,2,2),".2f")))
Dr. C. Sreedhar
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
print(factorial(4))
Dr. C. Sreedhar
def test2():
return 'cse4a', 68, [0, 1, 2]
a, b, c = test2()
print(a)
print(b)
print(c) cse4a
68
[0, 1, 2]
Returning multiple values
Dr. C. Sreedhar
def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n-1)
print(factorial(4))
Recursion: Factorial
Dr. C. Sreedhar
def power(x, y):
if y == 0:
return 1
else:
return x * power(x,y-1)
power(2,4)
Recursion: power(x,y)
Dr. C. Sreedhar
A lambda function is a small anonymous function with no name.
Lambda functions reduce the number of lines of code
when compared to normal python function defined using def
lambda function
(lambda x: x + 1)(2) #3
(lambda x, y: x + y)(2, 3) #5
Dr. C. Sreedhar
Dr. C. Sreedhar
Strings
 "hello"+"world" "helloworld" # concatenation
 "hello"*3 "hellohellohello" # repetition
 "hello"[0] "h" # indexing
 "hello"[-1] "o" # (from end)
 "hello"[1:4] "ell" # slicing
 len("hello") 5 # size
 "hello" < "jello" 1 # comparison
 "e" in "hello" 1 # search
 "escapes: n etc, 033 etc, if etc"
 'single quotes' """triple quotes""" r"raw strings"
Dr. C. Sreedhar
Functions
 Function: Equivalent to a static method in Java.
 Syntax:
def name():
statement
statement
...
statement
 Must be declared above the 'main' code
 Statements inside the function must be indented
hello2.py
1
2
3
4
5
6
7
# Prints a helpful message.
def hello():
print("Hello, world!")
# main (calls hello twice)
hello()
hello()
Dr. C. Sreedhar
Whitespace Significance
 Python uses indentation to indicate blocks, instead of {}
 Makes the code simpler and more readable
 In Java, indenting is optional. In Python, you must indent.
hello3.py
1
2
3
4
5
6
7
8
# Prints a helpful message.
def hello():
print("Hello, world!")
print("How are you?")
# main (calls hello twice)
hello()
hello()
Dr. C. Sreedhar
Python’s Core Data Types
 Numbers: Ex: 1234, 3.1415, 3+4j, Decimal, Fraction
 Strings: Ex: 'spam', "guido's", b'ax01c'
 Lists: Ex: [1, [2, 'three'], 4]
 Dictionaries: Ex: {'food': 'spam', 'taste': 'yum'}
 Tuples: Ex: (1, 'spam', 4, 'U')
 Files: Ex: myfile = open('eggs', 'r')
 Sets: Ex: set('abc'), {'a', 'b', 'c'}
Dr. C. Sreedhar
Unit 4
 Exceptions: When Something Goes Wrong, Classes of
Exceptions, A Final Note on Pythonic Exception Handling.
 File Handling: Need of File Handling, Text Input and Output,
The seek() Function, Binary Files, Accessing and Manipulating
Files and Directories on a Disk.
 Modules: Reusing Code with Modules and Packages,
Understanding Python Modules, Everyday Module Usage,
Advanced Module Behavior, Combining Modules into Packages
Dr. C. Sreedhar
Unit 4
• Modules: Reusing Code with Modules and Packages,
Understanding Python Modules, Everyday Module
Usage, Advanced Module Behavior, Combining
Modules into Packages
• Exceptions: When Something Goes Wrong, Classes of
Exceptions, A Final Note on Pythonic Exception
Handling.
• File Handling: Need of File Handling, Text Input and
Output, The seek() Function, Binary Files, Accessing
and Manipulating Files and Directories on a Disk.
Dr. C. Sreedhar
• os
– os.getcwd()
– os.fspath(path)
– os.getlogin()
• ipaddress:
–ipaddress.IPv4Address(addres
s)
–ipaddress.IPv6Address(addres
s)
• math:
– math.factorial(x)
– math.gcd(n1,n2)
– math.lcm(n1,n2)
– math.trunc(x)
– math.pow(x, y)
– math.pi
• random:
– random.randint(a,b)
– random.uniform(a,b)
• time:
– time.clock_gettime()
– time.clock_gettime_ns(
)
Module: Builtin Modules
Dr. C. Sreedhar
Modules: Create and import
• 1. Open Python IDLE (Start --> Python IDLE)
• 2. File --> New File
• 3. ---- type the following code----
def greeting(name):
print("Hello, " + name)
• 4. Save with module1.py (in Desktop or any folder)
• 5. Pyhton IDLE ==> File --> New File
• 6. ------ type the following code ----
import module1
module1.greeting("CSE4A")
• 7. Save as runmodule.py (in Desktop or any folder)
• 8. In Python IDLE, click on Run --> Run Module
from <module_name> import *
from <module_name> import <name> as
<alt_name>
Dr. C. Sreedhar
module2.py
----------------------------------------------
def sum_list(lst):
print('Sum=',sum(lst))
---------------------------------------------
summodule.py
---------------------------------------------
import module2
l1=[10,20,30,40]
module2.sum_list(l1)
Modules: Create and import
Dr. C. Sreedhar
In python, the inbuilt __import__() function helps to import modules
in runtime
Syntax:
__import__(name, globals, locals, fromlist, level)
Ex:
math_score = __import__('math', globals(), locals(), [],
0)
print(math_score.fabs(17.4))
Dr. C. Sreedhar
Package
• A package is basically a directory with Python
file and file with the extension as _init_.py.
• Steps to create package:
– create a package (folder). The name of package, say, My _ First _ Package
– Create _ init _ .py file inside the created package My_First_Package.
– The directory should contain a file named _init_.py. This file can be empty or
it may contain valid Python code.
– create two different .py files, i.e. a.py and b.py with code
a.py
def call_A():
print(“This is first
program”)
b.py
def call_B():
print(“This is second”)
>>> My_First_Package.a.call_A()
This is first program
>>> My_First_Package.b.call_B()
This is second
_init_.py
import My_First_Package.a
import My_First_Package.b
Dr. C. Sreedhar
# GPREC/CSBS/__init__.py (Empty
file)
# GPREC/CSBS/csbs4sem.py
print("In CSBS branch")
# GPREC/CSE/__init__.py
from . import cse4a
from . import cse4b
# GPREC/CSE/cse4a.py
print("In CSE 4A Class")
# GPREC/CSE/cse4b.py
print("In CSE 4B Class")
# GPREC/CSE/cse4c.py
print("In CSE 4C Class")
# world/__init__.py
from . import CSBS
from GPREC import CSE
import GPREC.CSE.cse4a
from GPREC.CSE import cse4b
Dr. C. Sreedhar
Exceptions
• An exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's instructions.
• Exception: Base class for all exceptions
• ArithmeticError: Base class for all errors that occur for numeric calculation.
• OverflowError: Raised when a calculation exceeds maximum limit for a numeric type.
• FloatingPointError: Raised when a floating point calculation fails.
• ZeroDivisionError: Raised when division or modulo by zero takes place for numeric
• AttributeError: Raised in case of failure of attribute reference or assignment.
• EOFError: Raised when end of file is reached.
• ImportError: Raised when an import statement fails.
• IndexError: Raised when an index is not found in a sequence.
• EnvironmentError: Base class for all exceptions that occur outside Python
environment.
• SyntaxError: Raised when there is an error in Python syntax.
• TypeError: Raised when an operation is attempted that is invalid for specified data type.
Dr. C. Sreedhar
try:
<body>
except <ExceptionType1>:
<handler1>
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
Dr. C. Sreedhar
try:
num1,num2 = eval(input("Enter two numbers,separated by a comma:"))
result = num1 / num2
print("Result is", result)
except ZeroDivisionError:
print("Division by zero is error !!")
except SyntaxError:
print("Comma is missing. Enter nos separated by comma like this 1,
2")
except:
print("Wrong input")
else:
print("No exceptions")
finally:
print("This will execute no matter what“)
Dr. C. Sreedhar
try:
a = [1, 2, 3]
print (a[3])
except LookupError:
print ("Index out of bound error.")
else:
print ("Success")
Dr. C. Sreedhar
try:
age= int(input())
assert (age>0 and age<100)
# True: moves to the next line ie., print age; False: returns Assertion Error
except AssertionError:
print("Not valid age.")
except:
print("Invalid data entered")
else:
print("Age is:",age)
Dr. C. Sreedhar
try:
age= int(input("Enter your age:"))
if age<0:
raise ValueError
except ValueError:
print("Age cannot be less than zero.")
else:
print("Age is:",age)
Dr. C. Sreedhar
Format:
<file variable> = open(<file name>, "r")
Example:
filename = input("Enter name of input file: ")
inputFile = open(filename, "r")
Python File handling Dr. C. Sreedhar
Modes Description
r Opens a file for reading only, default mode.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing
rb+ Opens a file for both reading and writing in binary format
w Opens a file for writing only. Overwrites the file if the file exists.
Wb Opens a file for writing only in binary format. Overwrites the file if the file
exists
w+ Opens a file for both writing and reading, Overwrites file if file
exists
Dr. C. Sreedhar
Example:
file2 = open(“cse4a.txt", "wb")
print ("Name of the file: ", file2.name)
print ("Closed or not : ", file2.closed)
print ("Opening mode : ", file2.mode)
This would produce following result:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Dr. C. Sreedhar
Reading contents from file
inputFileName = input("Enter name of input file:")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")
for line in inputFile:
sys.stdout.write(line)
inputFile.close()
print("Completed reading of file", inputFileName)
Dr. C. Sreedhar
Alternate way to read contents from file
inputFileName = input ("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")
line = inputFile.readline()
while (line != ""):
sys.stdout.write(line)
line = inputFile.readline()
inputFile.close()
print("Completed reading of file", inputFileName)
Dr. C. Sreedhar
Writing contents
fo = open(“cse4a.txt", "wb")
fo.write("Welcome to CSE4A n");
fo.close()
Dr. C. Sreedhar
Writing contents from one file into
another
inputFileName = input("Enter file name to read grades from:
")
outputFileName = input("output filename to write GPA's to:
")
inputFile = open(inputFileName, "r")
outputFile = open(outputFileName, "w")
print("Opening file", inputFileName, " for reading.")
print("Opening file", outputFileName, " for writing.")
gpa = 0
Dr. C. Sreedhar
seek()
• seek() function is used to change the
position of the File Handle to a given
specific position.
Dr. C. Sreedhar
Dr. C. Sreedhar

Más contenido relacionado

La actualidad más candente

Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentationVedaGayathri1
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
 
Queue data structure
Queue data structureQueue data structure
Queue data structureanooppjoseph
 
python Function
python Function python Function
python Function Ronak Rathi
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 

La actualidad más candente (20)

Python list
Python listPython list
Python list
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Python strings
Python stringsPython strings
Python strings
 
Python basic
Python basicPython basic
Python basic
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Python
PythonPython
Python
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
python Function
python Function python Function
python Function
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 

Similar a Python Programming by Dr. C. Sreedhar.pdf

FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptxNileshBorkar12
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha BaliAkanksha Bali
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data sciencedeepak teja
 
Python Basics
Python BasicsPython Basics
Python BasicsPooja B S
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...manikamr074
 
An overview on python commands for solving the problems
An overview on python commands for solving the problemsAn overview on python commands for solving the problems
An overview on python commands for solving the problemsRavikiran708913
 

Similar a Python Programming by Dr. C. Sreedhar.pdf (20)

Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Python ppt
Python pptPython ppt
Python ppt
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
Python basics
Python basicsPython basics
Python basics
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
Python
PythonPython
Python
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
 
Python Basics
Python BasicsPython Basics
Python Basics
 
C
CC
C
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python Session - 2
Python Session - 2Python Session - 2
Python Session - 2
 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
 
An overview on python commands for solving the problems
An overview on python commands for solving the problemsAn overview on python commands for solving the problems
An overview on python commands for solving the problems
 

Más de Sreedhar Chowdam

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesSreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPSreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer NetworksSreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer NetworksSreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operationsSreedhar Chowdam
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesSreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library databaseSreedhar Chowdam
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library databaseSreedhar Chowdam
 

Más de Sreedhar Chowdam (20)

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library database
 
Dbms ER Model
Dbms ER ModelDbms ER Model
Dbms ER Model
 
DBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCLDBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCL
 

Último

Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Último (20)

Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 

Python Programming by Dr. C. Sreedhar.pdf

  • 1. Dr. C. Sreedhar, Associate Professor, CSE Dept., GPREC PYTHON PROGRAMMING
  • 2. Unit 1  Introduction to Python Programming: Overview of Programming Languages, History of Python, Installing Python, Executing Python Programs, Commenting in Python, Internal Working of Python.  Basics of Python Programming: Python Character Set, Token, Python Core Data Type, I/O functions, Assigning Value to a Variable, Multiple Assignments, Writing Simple Programs in Python, Formatting Number and Strings, Python Inbuilt Functions.  Operators and Expressions: Operators and Expressions, Arithmetic Operators, Operator Precedence and Associativity, Changing Precedence and Associativity of Arithmetic Operators, Translating Mathematical Formulae into Equivalent Python Expressions, Bitwise Operator, The Compound Assignment Operator Dr. C. Sreedhar
  • 3. Overview of Prog.Languagess Python is a high-level general- purpose programming language. Translation of HLL into Machine Language: Compiler, Interpreter Compiler takes entire program as input Interpreter takes single instruction as i/p Guido van Rossum. Python is interpreted Python 3.0, released in 2008. Machine / Low level language Assembly Language High level Language Compiler Interpreter
  • 4. History of Python  Invented in the Netherlands, early 90s by Guido van Rossum  Named after Monty Python  Open sourced from the beginning  Considered a scripting language, but is much more  Scalable, object oriented and functional  Used by Google  Python 2.0 was released on 16 October 2000  Python 3.0, released on 3 December 2008  Currently Python 3.10.2 is the stable version Dr. C. Sreedhar
  • 5. Introduction to Python  Object oriented language: Class, Object, Inheritance, Encapsulation, Polymorphism  Interpreted language: is a layer of s/w logic b/w code and computer h/w on machine  Supports dynamic data type: no variable declaration as in C  Independent from platforms: Python code can run on virtually all operating systems and platforms  Focused on development time: focuses mainly on software development and deployment, enabling programmers to run data analysis and machine learning  Simple and easy grammar  Garbage collector: helps by avoiding memory leaks  It’s free (open source) Dr. C. Sreedhar
  • 6.
  • 7. Installing Python  Step 1: Visit www.python.org  Step 2: Visit download section  Step 3: Browse versions, latest stable version (3.10)  Step 4: Click on Python 3.4.2 and download it  Step 5: Double click on downloaded file  Step 6: Click on setup  Step 7: Click on Next (location to save)  Step 8: Click on finish to complete installation  Step 9: To check for python, in search box type python (Windows 10) Dr. C. Sreedhar
  • 8. Python modes  Two modes: Command line and IDLE  Command Line  Press Start  Click on Python 3.4  Click on Command line 32 bit  IDLE
  • 10. Commenting in Python  # ie., hash symbol is used as a single line comment  ' ' ' ie., three consecutive single quotation marks used as multiple comments or multi line comments Dr. C. Sreedhar
  • 11. Internal working of python Step 1: Interpreter reads python code or instruction, checks for syntax of each line Step 2: Interpreter translates it into its equivalent form in byte code Step 3: Byte code is sent and executed by Python Virtual Machine (PVM) Dr. C. Sreedhar
  • 12. Unit 1  Introduction to Python Programming: Overview of Programming Languages, History of Python, Installing Python, Executing Python Programs, Commenting in Python, Internal Working of Python.  Basics of Python Programming: Python Character Set, Token, Python Core Data Type, I/O functions, Assigning Value to a Variable, Multiple Assignments, Writing Simple Programs in Python, Formatting Number and Strings, Python Inbuilt Functions.  Operators and Expressions: Operators and Expressions, Arithmetic Operators, Operator Precedence and Associativity, Changing Precedence and Associativity of Arithmetic Operators, Translating Mathematical Formulae into Equivalent Python Expressions, Bitwise Operator, The Compound Assignment Operator Dr. C. Sreedhar
  • 13. Python Character Set Letters: Upper case and lower case letters Digits: 0,1,2,3,4,5,6,7,8,9 Special Symbols: _ ( ) [ ] { } +, -, *, &, ^, %, $, #, !, ' " " Colon(:), and Semi Colon (;) White Spaces: (‘tnx0bx0cr’), Space, Tab Dr. C. Sreedhar
  • 14. Python Token  Python has the following tokens:  Keyword  Identifiers  Literals  Operators  Delimiters/Punctuators Dr. C. Sreedhar
  • 15. Keywords in Python 3 and except nonlocal as finally not assert for or break from pass class global raise continue if return def import try del in while elif is with Keyword Description and logical operator as create an alias assert Used in debugging break break out of a loop class define a class continue continue to the next iteration of a loop def define a function del delete an object elif Used in conditional statements, same as else if else Used in conditional statements except Used with exceptions, what to do when an exception occurs false Boolean value, result of comparison operations Keyword Description from To import specific parts of a module global To declare a global variable if To make a conditional statement import To import a module in To check if a value is present in a list, tuple, etc. is To test if two variables are equal lambda To create an anonymous function none Represents a null value nonlocal To declare a non-local variable not A logical operator or A logical operator pass A null statement, a statement that will do nothing raise To raise an exception Dr. C. Sreedhar
  • 16.  Rules for Identifier: · It consist of letters and digits in any order except that the first character must be a letter. · The underscore (_) counts as a character. · Spaces are not allowed. · Special Characters are not allowed. Such as @,$ etc. · An identifier must not be a keyword of Python. · Variable names should be meaningful which easily depicts the logic Dr. C. Sreedhar
  • 18. Python Operators  Arithmetic operators  Assignment operators  Comparison operators  Logical operators  Identity operators  Membership operators  Bitwise operators Dr. C. Sreedhar
  • 19. Arithmetic Operators + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y Assignment Operators = X=6 += x += 3 -= x -= 3 *= x *= 3 /= x /= 3 %= x %= 3 //= x //= 3 **= x **= 3 &= x &= 3 |= x |= 3 ^= x ^= 3 >>= x >>= 3 Comparison Operators == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or x <= y Bitwise operators & AND | OR ^ XOR ~ NOT << Zero fill left shift >> Signed right shift Logical Operators and x < 10 and x < 14 or x < 10 or x < 14 not not(x < 24 and x < 8) Identity Operators is x is y is not x is not y
  • 20. Python Core Data types a = 10 b = 4+8j c = 3.4 # List is an ordered sequence of items. (mutable) li = [ 10, 2.6, 'Welcome' ] # Tuple is ordered sequence of items(immutable) t1 = ( 24, '4CSEA', 10+4j ) # Set is an unordered collection of unique items. s2 = { 5,2,3,1,4 } s4 = { 2.4, "4CSEA", (10, 20, 30) } # Dictionary is unordered collection of key-value pairs. d = { 'name':'Sree', 'Age':22 } S4=“Welcome to 4CSEA”
  • 21. I/O functions: print()  print(1, 2, 3, 4) 1 2 3 4  print(1, 2, 3, 4, sep='*') 1*2*3*4  print(1, 2, 3, 4, sep='#', end='&') 1#2#3#4&  print('The value of x is { } and y is { }'.format(x,y))  print('The value of x is {0} and y is {1}'.format(x,y))  print('The value of x is {1} and y is {0}'.format(x,y))  print('The value of x is %3.2f ' %x)  print('The value of x is %3.4f ' %x)  print("a =", a, sep='0000', end='nnn')  print(" Area of Circle is: ",format(Area,".2f")) Dr. C. Sreedhar
  • 22. I/O functions: print() Example Output print(format(10.345,”10.2f ”)) 10.35 print(format(10,”10.2f ”)) 10.00 print(format(10.32245,”10.2f ”)) 10.32 print(format(10.234566,”<10.2f ”)) #Left Justification Example print(format(20,”10x”)) # Hexadecimal print(format(20,”<10x”)) print(format(“Hello World!”,”20s”) # width print(format(0.31456,”10.2%”)) # 31.46% print(format(31.2345,”10.2e”)) # 3.12e+01
  • 23. I/O functions: input() Example name = input("Enter your name: ") inputString = input() user_input = input() a = int(input(“Enter your age:”)) val2 = float(input("Enter float number: ")) name, age, marks = input("Enter your Name, Age, Percentage separated by space ").split()
  • 24. Assigning Value to a Variable, Multiple Assignments  Assigning value to a variable P = 100 Q = 100 R = 100 P = Q = R = 100  Multiple assignments P, Q = Q, P #Swap P with Q & Q with P Dr. C. Sreedhar
  • 25. Writing simple Programs in Python  1. Program to accept student details such as name, age, rollno, branch, semester, grade, address etc and display the same.  2. Program to compute and print the perimeter and area of different shapes such as rectangle, triangle, square, circle etc.,  3. Program to check whether the given number is even or odd.  4. Program to check whether the given integer is both divisible by 4 and 9. Dr. C. Sreedhar
  • 26. 1. Accept student details and print the same name=input("Enter your name:") age=int(input("Enter your age:")) address=input("Enter your address:") grade=float(input("Enter cgpa:")) print('Your name is: {0}'.format(name)) print('Your age is: {0}'.format(age)) print('Your address is: {0}'.format(address)) print('Your grade is: {0}'.format(grade)) Dr. C. Sreedhar
  • 27. 2. Perimeter and area of shapes  Rectangle  area=l*b  perimeter=2*(l+b)  Triangle  area=1/2*(b*h)  perimeter=(s1+s2+s3)  Square  area=s*s  perimeter=4*s  Circle  area = pi*r*r  perimeter = 2*pi*r Dr. C. Sreedhar
  • 28. from math import pi # Rectangle l=int(input("Enter length of the rectangle: ")) b=int(input("Enter breadth of the rectangle: ")) area=l*b perimeter=2*(l+b) print("Perimeter of rectangle = " +str(perimeter)) print("Area of rectangle = " +str(area)) # Square s=int(input("Enter side of the square: ")) area=s*s perimeter=4*s print("Perimeter of square = " +str(perimeter) ) print("Area of square = " +str(area)) Dr. C. Sreedhar
  • 29. # Triangle b=int(input("Enter base of the triangle: ")) h=int(input("Enter height of the triangle: ")) area=1/2*(b*h) print("Area of rectangle = " +str(area)) s1=int(input("Enter side1 of triangle")) s2=int(input("Enter side2 of triangle")) s3=int(input("Enter side3 of triangle")) perimeter=(s1+s2+s3) print("Perimeter of rectangle = " +str(perimeter)) # Circle r=float(input("Enter the radius of the circle:")) print("Area of the circle is: "+str(pi*r**2)) print("Perimeter of the circle is: "+str(2*pi*r)) Dr. C. Sreedhar
  • 30. 3. Even or Odd number=input("Enter a number") x=int(number)%2 if x ==0: print("Given number "+str(number)+" is even no.") else: print("Given number "+str(number)+" is odd no.“) Dr. C. Sreedhar
  • 31. 4. Divisible by both # Program to check whether given integer is both divisible by 4 and 9 number=int(input("Enter a number: ")) if((number%4==0) and (number%9==0)): print("{0} is divisble by both 4 and 9".format(number)) else: print("{0} is NOT divisble by both 4 and 9".format(number)) Dr. C. Sreedhar
  • 32. Sum of digits using while loop n=int(input("Enter a number:")) tot=0 while(n>0): dig=n%10 tot=tot+dig n=n//10 print("The total sum of digits is:",tot) Dr. C. Sreedhar
  • 33. Multiplication table using loop for i in range(1, 11): print(num, '*', i, '=', num*i) Dr. C. Sreedhar
  • 34. lower = int(input("Enter start number in the range:")) upper = int(input("Enter last number in the range:")) print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) Dr. C. Sreedhar
  • 35. Accept Multiline input From a User data = [ ] print("Enter input, press Enter twice to exit") while True: line = input() if line: data.append(line) else: break finalText = 'n'.join(data) print("n") print("You have entered:") print(finalText) Dr. C. Sreedhar
  • 36. PYTHON INBUILT FUNCTIONS  X = int(input()) #Convert it to int X = float(input()) #Convert it to float  The full form of eval function is to evaluate. It takes a string as parameter and returns it as if it is a Python expression.  eval(‘print(“Hello”)’)  print(format(10.234566,”10.2f”)) #Right Justification Example  print(format(10.234566,”<10.2f”)) #Left Justification Example  print(format(20,”10x”)) #Integer formatted to Hexadecimal Integer  print(format(20,”<10x”)) Dr. C. Sreedhar
  • 37.  Formatting Scientific Notation  print(format(31.2345,”10.2e”))  3.12e+01  print(format(131.2345,”10.2e”))  1.31e+02 Dr. C. Sreedhar
  • 38. PYTHON INBUILT FUNCTIONS  abs(x) Returns absolute value of x  Example: abs(-2) returns 2  abs(4) returns 4  tan(X) : Return the tangent of X, where X is the value in radians  math.tan(3.14/4)  0.9992039901050427  degrees(X) : Convert angle X from to radians to degrees  math.degrees(1.57)  89.95437383553924  Radians(X) >>> math.  radians(89.99999)  1.5707961522619713 Dr. C. Sreedhar
  • 39. High-level data types  Numbers: int, long, float, complex  Strings: immutable  Lists and dictionaries: containers  Other types for e.g. binary data, regular expressions, introspection  Extension modules can define new “built-in” data types Dr. C. Sreedhar
  • 40. History of Python  Created in 1990 by Guido van Rossum  Named after Monty Python  First public release in 1991  comp.lang.python founded in 1994  Open source from the start Dr. C. Sreedhar
  • 41. Python features no compiling or linking rapid development cycle no type declarations simpler, shorter, more flexible automatic memory management garbage collection high-level data types and operations fast development object-oriented programming code structuring and reuse, C++ embedding and extending in C mixed language systems classes, modules, exceptions "programming-in-the-large" support dynamic loading of C modules simplified extensions, smaller binaries dynamic reloading of C modules programs can be modified without stopping Dr. C. Sreedhar
  • 42. Python features universal "first-class" object model fewer restrictions and rules run-time program construction handles unforeseen needs, end-user coding interactive, dynamic nature incremental development and testing access to interpreter information metaprogramming, introspective objects wide portability cross-platform programming without ports compilation to portable byte-code execution speed, protecting source code built-in interfaces to external services system tools, GUIs, persistence, databases, etc. Dr. C. Sreedhar
  • 43. Where to use python?  System management (i.e., scripting)  Graphic User Interface (GUI)  Internet programming  Database (DB) programming  Text data processing  Distributed processing  Numerical operations  Graphics  And so on… Dr. C. Sreedhar
  • 44.  Google in its web search systems  YouTube video sharing service is largely written in Python.  BitTorrent peer-to-peer file sharing system.  Google’s popular App Engine web development framework uses Python as its application language.  EVE Online, a Massively Multiplayer Online Game (MMOG).  Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API. Dr. C. Sreedhar
  • 45.  Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.  Industrial Light & Magic, Pixar, and others use Python in the production of animated movies.  JPMorgan Chase, UBS, Getco, and Citadel apply Python for financial market forecasting.  NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming tasks.  iRobot uses Python to develop commercial robotic devices. Dr. C. Sreedhar
  • 46.  ESRI uses Python as an end-user customization tool for its popular GIS mapping products.  NSA uses Python for cryptography and intelligence analysis.  The IronPort email server product uses more than 1 million lines of Python code to do its job.  The One Laptop Per Child (OLPC) project builds its user interface and activity model in Python. Dr. C. Sreedhar
  • 47. Strings  "hello"+"world" "helloworld" # concatenation  "hello"*3 "hellohellohello" # repetition  "hello"[0] "h" # indexing  "hello"[-1] "o" # (from end)  "hello"[1:4] "ell" # slicing  len("hello") 5 # size  "hello" < "jello" 1 # comparison  "e" in "hello" 1 # search  "escapes: n etc, 033 etc, if etc"  'single quotes' """triple quotes""" r"raw strings" Dr. C. Sreedhar
  • 48. Lists  Flexible arrays, not Lisp-like linked lists  a = [99, "bottles of beer", ["on", "the", "wall"]]  Same operators as for strings  a+b, a*3, a[0], a[-1], a[1:], len(a)  Item and slice assignment  a[0] = 98  a[1:2] = ["bottles", "of", "beer"] -> [98, "bottles", "of", "beer", ["on", "the", "wall"]]  del a[-1] # -> [98, "bottles", "of", "beer"] Dr. C. Sreedhar
  • 49. Dictionaries  Hash tables, "associative arrays"  d = {"duck": "eend", "water": "water"}  Lookup:  d["duck"] -> "eend"  d["back"] # raises KeyError exception  Delete, insert, overwrite:  del d["water"] # {"duck": "eend", "back": "rug"}  d["back"] = "rug" # {"duck": "eend", "back": "rug"}  d["duck"] = "duik" # {"duck": "duik", "back": "rug“} Dr. C. Sreedhar
  • 50. Tuples  key = (lastname, firstname)  point = x, y, z # parentheses optional  x, y, z = point # unpack  lastname = key[0]  singleton = (1,) # trailing comma!!!  empty = () # parentheses!  tuples vs. lists; tuples immutable Dr. C. Sreedhar
  • 51. Variables  No need to declare  Need to assign (initialize)  use of uninitialized variable raises exception  Not typed if friendly: greeting = "hello world" else: greeting = 12**2 print greeting  Everything is a "variable":  Even functions, classes, modules Dr. C. Sreedhar
  • 52. Comments  Syntax: # comment text (one line) swallows2.py 1 2 3 4 5 6 # Suzy Student, CSE 142, Fall 2097 # This program prints important messages. print("Hello, world!") print() # blank line print("Suppose two swallows "carry" it together.") print('African or "European" swallows?') Dr. C. Sreedhar
  • 53. Functions  Function: Equivalent to a static method in Java.  Syntax: def name(): statement statement ... statement  Must be declared above the 'main' code  Statements inside the function must be indented hello2.py 1 2 3 4 5 6 7 # Prints a helpful message. def hello(): print("Hello, world!") # main (calls hello twice) hello() hello() Dr. C. Sreedhar
  • 54. Whitespace Significance  Python uses indentation to indicate blocks, instead of {}  Makes the code simpler and more readable  In Java, indenting is optional. In Python, you must indent. hello3.py 1 2 3 4 5 6 7 8 # Prints a helpful message. def hello(): print("Hello, world!") print("How are you?") # main (calls hello twice) hello() hello() Dr. C. Sreedhar
  • 55. Python’s Core Data Types  Numbers: Ex: 1234, 3.1415, 3+4j, Decimal, Fraction  Strings: Ex: 'spam', "guido's", b'ax01c'  Lists: Ex: [1, [2, 'three'], 4]  Dictionaries: Ex: {'food': 'spam', 'taste': 'yum'}  Tuples: Ex: (1, 'spam', 4, 'U')  Files: Ex: myfile = open('eggs', 'r')  Sets: Ex: set('abc'), {'a', 'b', 'c'} Dr. C. Sreedhar
  • 56. Builtin Data type: Number  >>> 123 + 222 # Integer addition  345 >>> 1.5 * 4 # Floating-point multiplication 6.0  >>> 2 ** 100 # 2 to the power 100 1267650600228229401496703205376  >>> 3.1415 * 2 # repr: as code 6.2830000000000004  >>> print(3.1415 * 2) # str: user-friendly 6.283 Dr. C. Sreedhar
  • 57. Builtin Data type: Number  >>> import math  >>> math.pi 3.1415926535897931  >>> math.sqrt(85  >>> import random  >>> random.random() 0.59268735266273953  >>> random.choice([1, 2, 3, 4]) 1) 9.2195444572928871 Dr. C. Sreedhar
  • 58. Builtin Data type: String  Strings are used to record textual information  strings are sequences of one-character strings; other types of sequences include lists and tuples.  >>> S = 'Spam'  >>> len(S) # Length 4  >>> S[0] # The first item in S, indexing by zero-based position 'S'  >>> S[1] # The second item from the left 'p'  >>> S[-1] # The last item from the end in S 'm'  >>> S[-2] # The second to last item from the end 'a' Dr. C. Sreedhar
  • 59.  >>> S[-1] # The last item in S 'm'  >>> S[len(S)-1] # Negative indexing, the hard way 'm'  >>> S # A 4-character string 'Spam'  >>> S[1:3] # Slice of S from offsets 1 through 2 (not 3) 'pa' Dr. C. Sreedhar
  • 60.  >>> S[1:] # Everything past the first (1:len(S)) 'pam'  >>> S # S itself hasn't changed 'Spam'  >>> S[0:3] # Everything but the last 'Spa'  >>> S[:3] # Same as S[0:3] 'Spa'  >>> S[:-1] # Everything but the last again, but simpler (0:-1) 'Spa'  >>> S[:] # All of S as a top-level copy (0:len(S)) 'Spam' Dr. C. Sreedhar
  • 61.  >>> S Spam'  >>> S + 'xyz' # Concatenation  'Spamxyz'  >>> S # S is unchanged 'Spam'  >>> S * 8 # Repetition 'SpamSpamSpamSpamSpamSpamSpamSpam' Dr. C. Sreedhar
  • 62.  Immutable:  immutable in Python—they cannot be changed in-place after they are created.  >>> S 'Spam'  >>> S[0] = 'z' # Immutable objects cannot be changed ...error text omitted... TypeError: 'str' object does not support item assignment  >>> S = 'z' + S[1:] # But we can run expressions to make new objects  >>> S 'zpam' Dr. C. Sreedhar
  • 63.  >>> S.find('pa') # Find the offset of a substring 1  >>> S 'Spam'  >>> S.replace('pa', 'XYZ') # Replace occurrences of a substring with another 'SXYZm'  >>> S 'Spam' Dr. C. Sreedhar
  • 64.  >>> line = 'aaa,bbb,ccccc,dd'  >>> line.split(',') # Split on a delimiter into a list of substrings ['aaa', 'bbb', 'ccccc', 'dd']  >>> S = 'spam'  >>> S.upper() # Upper- and lowercase conversions 'SPAM'  >>> S.isalpha() # Content tests: isalpha, isdigit, etc. True  >>> line = 'aaa,bbb,ccccc,ddn'  >>> line = line.rstrip() # Remove whitespace characters on the right side  >>> line 'aaa,bbb,ccccc,dd' Dr. C. Sreedhar
  • 65.  >>> '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting expression (all) 'spam, eggs, and SPAM!'  >>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting method (2.6, 3.0) 'spam, eggs, and SPAM!' Dr. C. Sreedhar
  • 66.  >>> S = 'AnBtC' # n is end-of-line, t is tab >>> len(S) # Each stands for just one character 5  >>> ord('n') # n is a byte with the binary value 10 in ASCII 10  >>> S = 'A0B0C' # 0, a binary zero byte, does not terminate string  >>> len(S) 5 Dr. C. Sreedhar
  • 67. Pattern Matching  to do pattern matching in Python, we import a module called re.  This module has analogous calls for searching, splitting, and replacement.  >>> import re  >>> match = re.match('Hello[ t]*(.*)world', 'Hello Python world')  >>> match.group(1) 'Python ' Dr. C. Sreedhar
  • 68. Python vs. Java  Code 5-10 times more concise  Dynamic typing  Much quicker development  no compilation phase  less typing  Yes, it runs slower  but development is so much faster!  Similar (but more so) for C/C++  Use Python with Java: JPython! Dr. C. Sreedhar
  • 69. Installing Python: Linux/Ubuntu  Install Python 3.6:  1. To follow the installation procedure, you need to be connected to the Internet.  2. Open the terminal by pressing Ctrl + Alt + T keys together.  3. Install Python 3.6:  a. For Ubuntu 16.04 and Ubuntu 17.04:  i. In the terminal, run the command sudo apt-get install python3.6  ii. Press Enter.  iii. The terminal will prompt you for your password, type it in to the terminal.  iv. Press Enter.  b. For Ubuntu 17.10 and above, the system already comes with Python 3.6installed by default.  To check Python is installed or not, open terminal and enter command: python3 --version Dr. C. Sreedhar
  • 70. Installing Python: Windows  Install Python 3.6:  1. To follow the installation procedure, you need to be connected to the Internet.  2. Visit https://www.python.org/downloads/release/python-368/  3. At the bottom locate Windows x86-64 executable installer for 64 bits OS and  Windows x86 executable installer for 32 bits OS  4. Click on the located installer file to download.  5. After download completes, double click on the installer file to start the installation procedure.  6. Follow the instructions as per the installer Dr. C. Sreedhar
  • 71. Executing Python Programs  Linux  Open text editor, type the source code and save the program with .py extension (Ex: ex1.py)  Open terminal, run the command python  Run the program using the command, python ex1.py  Google Colab  Instructions to execute python program is sent to your official email id  Jupyter Notebook  Run Jupyter Notebook and copy paste URL in the browser  Type the source code in the cell and press CTRL+Enter Dr. C. Sreedhar
  • 72. Unit 2  Decision Statements: Boolean Type, Boolean Operators, Using Numbers with Boolean Operators, Using String with Boolean Operators, Boolean Expressions and Relational Operators, Decision Making Statements, Conditional Expressions.  Loop Control Statements: while Loop, range() Function, for Loop, Nested Loops, break, continue.  Functions: Syntax and Basics of a Function, Use of a Function, Parameters and Arguments in a Function, The Local and Global Scope of a Variable, The return Statement, Recursive Functions, The Lambda Function. Dr. C. Sreedhar
  • 73. Boolean type Python boolean data type has two values: True and False. bool() function is used to test if a value is True or False. a = True type(a) bool b = False type(b) bool branch = "CSE" sem = 4 section ='' print(bool(branch)) print(bool(sem)) print(bool(section)) print(bool(["app", “bat", “mat"])) True True False True Dr. C. Sreedhar
  • 74. Boolean operators not and or A=True B=False print(A and B) print(A or B) print(not A) False True False A=True B=False C=False D= True print((A and D) and (B or C)) print((A and D) or (B or C)) False True Dr. C. Sreedhar
  • 75. Write code that counts the number of words in sentence that contain either an “a” or an “e”. sentence=input() words = sentence.split(" ") count = 0 for i in words: if (('a' in i) or ('e' in i)) : count +=1 print(count) Welcome to Computer Science and Engineering 5 Dr. C. Sreedhar
  • 76. BOOLEAN EXPRESSIONS AND RELATIONAL OPERATORS 2 < 4 or 2 True 2 < 4 or [ ] True 5 > 10 or 8 8 print(1 <= 1) print(1 != 1) print(1 != 2) print("CSEA" != "csea") print("python" != "python") print(123 == "123") True False True True False False Dr. C. Sreedhar
  • 77. x = 84 y = 17 print(x >= y) print(y <= x) print(y < x) print(x <= y) print(x < y) print(x % y == 0) True True True False False False x = True y = False print(not y) print(x or y) print(x and not y) print(not x) print(x and y) print(not x or y) True True True False False False Dr. C. Sreedhar
  • 78. Decision statements Python supports the following decision- making statements. if statements if-else statements Nested if statements Multi-way if-elif-else statements Dr. C. Sreedhar
  • 79. if  Write a program that prompts a user to enter two integer values. Print the message ‘Equals’ if both the entered values are equal.  if num1- num2==0: print(“Both the numbers entered are Equal”)  Write a program which prompts a user to enter the radius of a circle. If the radius is greater than zero then calculate and print the area and circumference of the circle if Radius>0: Area=Radius*Radius*pi ......... Dr. C. Sreedhar
  • 80.  Write a program to calculate the salary of a medical representative considering the sales bonus and incentives offered to him are based on the total sales. If the sales exceed or equal to 1,00,000 follow the particulars of Column 1, else follow Column 2. Dr. C. Sreedhar
  • 81. Sales=float(input(‘Enter Total Sales of the Month:’)) if Sales >= 100000: basic = 4000 hra = 20 * basic/100 da = 110 * basic/100 incentive = Sales * 10/100 bonus = 1000 conveyance = 500 else: basic = 4000 hra = 10 * basic/100 da = 110 * basic/100 incentive = Sales * 4/100 bonus = 500 conveyance = 500 salary= basic+hra+da+incentive+bonus+conveyance # print Sales,basic,hra,da,incentive,bonus,conveyance,sal Dr. C. Sreedhar
  • 82. Write a program to read three numbers from a user and check if the first number is greater or less than the other two numbers. if num1>num2: if num2>num3: print(num1,”is greater than “,num2,”and “,num3) else: print(num1,” is less than “,num2,”and”,num3) Dr. C. Sreedhar
  • 83. Finding the Number of Days in a Month flag = 1 month = (int(input(‘Enter the month(1-12):’))) if month == 2: year = int(input(‘Enter year:’)) if (year % 4 == 0) and (not(year % 100 == 0)) or (year % 400 == 0): num_days = 29 else: num_days = 28 elif month in (1,3,5,7,8,10,12): num_days = 31 elif month in (4, 6, 9, 11): num_days = 30 else: print(‘Please Enter Valid Month’) flag = 0 if flag == 1: print(‘There are ‘,num_days, ‘days in’, month,’ month’) Dr. C. Sreedhar
  • 84. Write a program that prompts a user to enter two different numbers. Perform basic arithmetic operations based on the choices. ....... if choice==1: print(“ Sum=,”is:”,num1+num2) elif choice==2: print(“ Difference=:”,num1-num2) elif choice==3: print(“ Product=:”,num1*num2) elif choice==4: print(“ Division:”,num1/num2) else: print(“Invalid Choice”) Dr. C. Sreedhar
  • 85. Multi-way if-elif-else Statements: Syntax If Boolean-expression1: statement1 elif Boolean-expression2 : statement2 elif Boolean-expression3 : statement3 - - - - - - - - - - - - - - - - - - - - - - - - - -- - elif Boolean-expression n : statement N else : Statement(s) Dr. C. Sreedhar
  • 86. CONDITIONAL EXPRESSIONS if x%2==0: x = x*x else: x = x*x*x x=x*x if x % 2 == 0 else x*x*x min=print(‘min=‘,n1) if n1<n2 else print(‘min = ‘,n2) a=int(input(“Enter number: “) print(‘even’) if(a%2) ==0 else print(‘Odd’) Dr. C. Sreedhar
  • 87. Loop Controlled Statements while Loop range() Function for Loop Nested Loops break Statement continue Statement Dr. C. Sreedhar
  • 88. Multiplication table using while in reverse order num=int(input("Enter no: ")) count = 10 while count >= 1: prod = num * count print(num, "x", count, "=", prod) count = count - 1 Enter no: 4 4 x 10 = 40 4 x 9 = 36 4 x 8 = 32 4 x 7 = 28 4 x 6 = 24 4 x 5 = 20 4 x 4 = 16 4 x 3 = 12 4 x 2 = 8 4 x 1 = 4 Dr. C. Sreedhar
  • 89. num=int(input(“Enter the number:”)) fact=1 ans=1 while fact<=num: ans*=fact fact=fact+1 print(“Factorial of”,num,” is: “,ans) Factorial of a given number Dr. C. Sreedhar
  • 90. text = "Engineering" for character in text: print(character) E n g i n e e r i n g courses = ["Python", "Computer Networks", "DBMS"] for course in courses: print(course) Python Computer Networks DBMS Dr. C. Sreedhar
  • 91. for i in range(10,0,-1): print(i,end=" ") # 10 9 8 7 6 5 4 3 2 1 range(start,stop,step size) Dr. C. Sreedhar
  • 92. Program which iterates through integers from 1 to 50 (using for loop). For an integer that is even, append it to the list even numbers. For an integer that is odd, append it the list odd numbers even = [] odd = [] for number in range(1,51): if number % 2 == 0: even.append(number) else: odd.append(number) print("Even Numbers: ", even) print("Odd Numbers: ", odd) Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50] Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49] Dr. C. Sreedhar
  • 93. matrix=[] for i in range(2): row=[] for j in range(2): num=int(input()) row.append(num) matrix.append(row) print(matrix) Accept matrix elements and display Dr. C. Sreedhar
  • 94. for i in range(1,100,1): if(i==11): break else: print(i, end=” “) 1 2 3 4 5 6 7 8 9 10 break Dr. C. Sreedhar
  • 95. for i in range(1,11,1): if i == 5: continue print(i, end=” “) 1 2 3 4 6 7 8 9 10 continue Dr. C. Sreedhar
  • 96. function Dr. C. Sreedhar
  • 97. def square(num): return num**2 print (square(2)) print (square(3)) Function: Example Dr. C. Sreedhar
  • 98. def disp_values(a,b=10,c=20): print(“ a = “,a,” b = “,b,”c= “,c) disp_values(15) disp_values(50,b=30) disp_values(c=80,a=25,b=35) a = 15 b = 10 c= 20 a = 50 b = 30 c= 20 a = 25 b = 35 c= 80 Dr. C. Sreedhar
  • 99. LOCAL AND GLOBAL SCOPE OF A VARIABLE p = 20 #global variable p def Demo(): q = 10 #Local variable q print(‘Local variable q:’,q) print(‘Global Variable p:’,p) Demo() print(‘global variable p:’,p) Local variable q: 10 Global Variable p: 20 global variable p: 20 Dr. C. Sreedhar
  • 100. a = 20 def Display(): a = 30 print(‘a in function:’,a) Display() print(‘a outside function:’,a) a in function: 30 a outside function: 20 Dr. C. Sreedhar
  • 101. Write a function calc_Distance(x1, y1, x2, y2) to calculate the distance between two points represented by Point1(x1, y1) and Point2 (x2, y2). The formula for calculating distance is: import math def EuclD (x1, y1, x2, y2): dx=x2-x1 dx=math.pow(dx,2) dy=y2-y1 dy=math.pow(dy,2) z = math.pow((dx + dy), 0.5) return z print("Distance = ",(format(EuclD(4,4,2,2),".2f"))) Dr. C. Sreedhar
  • 102. def factorial(n): if n==0: return 1 return n*factorial(n-1) print(factorial(4)) Dr. C. Sreedhar
  • 103. def test2(): return 'cse4a', 68, [0, 1, 2] a, b, c = test2() print(a) print(b) print(c) cse4a 68 [0, 1, 2] Returning multiple values Dr. C. Sreedhar
  • 104. def factorial(n): if n < 1: return 1 else: return n * factorial(n-1) print(factorial(4)) Recursion: Factorial Dr. C. Sreedhar
  • 105. def power(x, y): if y == 0: return 1 else: return x * power(x,y-1) power(2,4) Recursion: power(x,y) Dr. C. Sreedhar
  • 106. A lambda function is a small anonymous function with no name. Lambda functions reduce the number of lines of code when compared to normal python function defined using def lambda function (lambda x: x + 1)(2) #3 (lambda x, y: x + y)(2, 3) #5 Dr. C. Sreedhar
  • 108. Strings  "hello"+"world" "helloworld" # concatenation  "hello"*3 "hellohellohello" # repetition  "hello"[0] "h" # indexing  "hello"[-1] "o" # (from end)  "hello"[1:4] "ell" # slicing  len("hello") 5 # size  "hello" < "jello" 1 # comparison  "e" in "hello" 1 # search  "escapes: n etc, 033 etc, if etc"  'single quotes' """triple quotes""" r"raw strings" Dr. C. Sreedhar
  • 109. Functions  Function: Equivalent to a static method in Java.  Syntax: def name(): statement statement ... statement  Must be declared above the 'main' code  Statements inside the function must be indented hello2.py 1 2 3 4 5 6 7 # Prints a helpful message. def hello(): print("Hello, world!") # main (calls hello twice) hello() hello() Dr. C. Sreedhar
  • 110. Whitespace Significance  Python uses indentation to indicate blocks, instead of {}  Makes the code simpler and more readable  In Java, indenting is optional. In Python, you must indent. hello3.py 1 2 3 4 5 6 7 8 # Prints a helpful message. def hello(): print("Hello, world!") print("How are you?") # main (calls hello twice) hello() hello() Dr. C. Sreedhar
  • 111. Python’s Core Data Types  Numbers: Ex: 1234, 3.1415, 3+4j, Decimal, Fraction  Strings: Ex: 'spam', "guido's", b'ax01c'  Lists: Ex: [1, [2, 'three'], 4]  Dictionaries: Ex: {'food': 'spam', 'taste': 'yum'}  Tuples: Ex: (1, 'spam', 4, 'U')  Files: Ex: myfile = open('eggs', 'r')  Sets: Ex: set('abc'), {'a', 'b', 'c'} Dr. C. Sreedhar
  • 112. Unit 4  Exceptions: When Something Goes Wrong, Classes of Exceptions, A Final Note on Pythonic Exception Handling.  File Handling: Need of File Handling, Text Input and Output, The seek() Function, Binary Files, Accessing and Manipulating Files and Directories on a Disk.  Modules: Reusing Code with Modules and Packages, Understanding Python Modules, Everyday Module Usage, Advanced Module Behavior, Combining Modules into Packages Dr. C. Sreedhar
  • 113. Unit 4 • Modules: Reusing Code with Modules and Packages, Understanding Python Modules, Everyday Module Usage, Advanced Module Behavior, Combining Modules into Packages • Exceptions: When Something Goes Wrong, Classes of Exceptions, A Final Note on Pythonic Exception Handling. • File Handling: Need of File Handling, Text Input and Output, The seek() Function, Binary Files, Accessing and Manipulating Files and Directories on a Disk. Dr. C. Sreedhar
  • 114. • os – os.getcwd() – os.fspath(path) – os.getlogin() • ipaddress: –ipaddress.IPv4Address(addres s) –ipaddress.IPv6Address(addres s) • math: – math.factorial(x) – math.gcd(n1,n2) – math.lcm(n1,n2) – math.trunc(x) – math.pow(x, y) – math.pi • random: – random.randint(a,b) – random.uniform(a,b) • time: – time.clock_gettime() – time.clock_gettime_ns( ) Module: Builtin Modules Dr. C. Sreedhar
  • 115. Modules: Create and import • 1. Open Python IDLE (Start --> Python IDLE) • 2. File --> New File • 3. ---- type the following code---- def greeting(name): print("Hello, " + name) • 4. Save with module1.py (in Desktop or any folder) • 5. Pyhton IDLE ==> File --> New File • 6. ------ type the following code ---- import module1 module1.greeting("CSE4A") • 7. Save as runmodule.py (in Desktop or any folder) • 8. In Python IDLE, click on Run --> Run Module from <module_name> import * from <module_name> import <name> as <alt_name> Dr. C. Sreedhar
  • 117. In python, the inbuilt __import__() function helps to import modules in runtime Syntax: __import__(name, globals, locals, fromlist, level) Ex: math_score = __import__('math', globals(), locals(), [], 0) print(math_score.fabs(17.4)) Dr. C. Sreedhar
  • 118. Package • A package is basically a directory with Python file and file with the extension as _init_.py. • Steps to create package: – create a package (folder). The name of package, say, My _ First _ Package – Create _ init _ .py file inside the created package My_First_Package. – The directory should contain a file named _init_.py. This file can be empty or it may contain valid Python code. – create two different .py files, i.e. a.py and b.py with code a.py def call_A(): print(“This is first program”) b.py def call_B(): print(“This is second”) >>> My_First_Package.a.call_A() This is first program >>> My_First_Package.b.call_B() This is second _init_.py import My_First_Package.a import My_First_Package.b Dr. C. Sreedhar
  • 119. # GPREC/CSBS/__init__.py (Empty file) # GPREC/CSBS/csbs4sem.py print("In CSBS branch") # GPREC/CSE/__init__.py from . import cse4a from . import cse4b # GPREC/CSE/cse4a.py print("In CSE 4A Class") # GPREC/CSE/cse4b.py print("In CSE 4B Class") # GPREC/CSE/cse4c.py print("In CSE 4C Class") # world/__init__.py from . import CSBS from GPREC import CSE import GPREC.CSE.cse4a from GPREC.CSE import cse4b Dr. C. Sreedhar
  • 120. Exceptions • An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. • Exception: Base class for all exceptions • ArithmeticError: Base class for all errors that occur for numeric calculation. • OverflowError: Raised when a calculation exceeds maximum limit for a numeric type. • FloatingPointError: Raised when a floating point calculation fails. • ZeroDivisionError: Raised when division or modulo by zero takes place for numeric • AttributeError: Raised in case of failure of attribute reference or assignment. • EOFError: Raised when end of file is reached. • ImportError: Raised when an import statement fails. • IndexError: Raised when an index is not found in a sequence. • EnvironmentError: Base class for all exceptions that occur outside Python environment. • SyntaxError: Raised when there is an error in Python syntax. • TypeError: Raised when an operation is attempted that is invalid for specified data type. Dr. C. Sreedhar
  • 122. try: num1,num2 = eval(input("Enter two numbers,separated by a comma:")) result = num1 / num2 print("Result is", result) except ZeroDivisionError: print("Division by zero is error !!") except SyntaxError: print("Comma is missing. Enter nos separated by comma like this 1, 2") except: print("Wrong input") else: print("No exceptions") finally: print("This will execute no matter what“) Dr. C. Sreedhar
  • 123. try: a = [1, 2, 3] print (a[3]) except LookupError: print ("Index out of bound error.") else: print ("Success") Dr. C. Sreedhar
  • 124. try: age= int(input()) assert (age>0 and age<100) # True: moves to the next line ie., print age; False: returns Assertion Error except AssertionError: print("Not valid age.") except: print("Invalid data entered") else: print("Age is:",age) Dr. C. Sreedhar
  • 125. try: age= int(input("Enter your age:")) if age<0: raise ValueError except ValueError: print("Age cannot be less than zero.") else: print("Age is:",age) Dr. C. Sreedhar
  • 126. Format: <file variable> = open(<file name>, "r") Example: filename = input("Enter name of input file: ") inputFile = open(filename, "r") Python File handling Dr. C. Sreedhar
  • 127. Modes Description r Opens a file for reading only, default mode. rb Opens a file for reading only in binary format. r+ Opens a file for both reading and writing rb+ Opens a file for both reading and writing in binary format w Opens a file for writing only. Overwrites the file if the file exists. Wb Opens a file for writing only in binary format. Overwrites the file if the file exists w+ Opens a file for both writing and reading, Overwrites file if file exists Dr. C. Sreedhar
  • 128. Example: file2 = open(“cse4a.txt", "wb") print ("Name of the file: ", file2.name) print ("Closed or not : ", file2.closed) print ("Opening mode : ", file2.mode) This would produce following result: Name of the file: foo.txt Closed or not : False Opening mode : wb Dr. C. Sreedhar
  • 129. Reading contents from file inputFileName = input("Enter name of input file:") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") for line in inputFile: sys.stdout.write(line) inputFile.close() print("Completed reading of file", inputFileName) Dr. C. Sreedhar
  • 130. Alternate way to read contents from file inputFileName = input ("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") line = inputFile.readline() while (line != ""): sys.stdout.write(line) line = inputFile.readline() inputFile.close() print("Completed reading of file", inputFileName) Dr. C. Sreedhar
  • 131. Writing contents fo = open(“cse4a.txt", "wb") fo.write("Welcome to CSE4A n"); fo.close() Dr. C. Sreedhar
  • 132. Writing contents from one file into another inputFileName = input("Enter file name to read grades from: ") outputFileName = input("output filename to write GPA's to: ") inputFile = open(inputFileName, "r") outputFile = open(outputFileName, "w") print("Opening file", inputFileName, " for reading.") print("Opening file", outputFileName, " for writing.") gpa = 0 Dr. C. Sreedhar
  • 133. seek() • seek() function is used to change the position of the File Handle to a given specific position. Dr. C. Sreedhar