0% found this document useful (0 votes)
8 views150 pages

Unit-1 Python Programming

The document outlines the syllabus for a Python Programming course offered by the School of Computing for the academic year 2022-23. It includes course outcomes, a correlation of course outcomes with program outcomes, detailed syllabus content divided into units, and recommended textbooks and online resources. The course covers various aspects of Python programming including data types, file manipulation, exception handling, data analysis, and game design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views150 pages

Unit-1 Python Programming

The document outlines the syllabus for a Python Programming course offered by the School of Computing for the academic year 2022-23. It includes course outcomes, a correlation of course outcomes with program outcomes, detailed syllabus content divided into units, and recommended textbooks and online resources. The course covers various aspects of Python programming including data types, file manipulation, exception handling, data analysis, and game design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

SCHOOL OF COMPUTING

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND


MACHINE LEARNING

Academic Year 2022-23 : Winter Semester


10211AD213 / PYTHON PROGRAMMING
Pre-requisites

Sl. No Course Code Course Name

1 1150CS201 Problem Solving using C

1/19/2023 1
Course Outcomes
CO Level of learning
Course Outcomes
Nos. domain
Experiment with data types, operators, statements
CO1 K2
and functions in python.
Construct the file handling, string handling and
CO2 K3
regular expression functions in python
Use the Exception handling to handle errors and
CO3 K3
multithreading mechanism for parallel execution .
Demonstrate the use of python libraries for data
CO4 K3
analysis.
Apply python modules for Graphical User
CO5 K3
Interface and game design

1/19/2023 2
Correlation of COs with POs and PSOs

PO PO PO PO PO PO PSO PSO PSO


Cos PO1 PO2 PO3 PO4 PO5 PO6
7 8 9 10 11 12 1 2 3

CO1 2 2 2 2
2
CO2 2 2
2
CO3 2 2 2
2 3 2
CO4 2 2 3 3 3
2
CO5 2 3 3

1– High; 2 – Medium; 3 - Low

1/19/2023 3
Syllabus Content
Unit I Introduction 6
Python Basics:variables-data types-operators and expressions-control
statements-comments in the program-python collections (List, Tuple, Set,
Dictionary)-modules-packages and composition-python functions-build-in
functions-Lambda functions-python iterator and generator.
Case Study: Shuffling a Deck of Card
Unit II File Manipulation, String Handling and Regular
Expression 6
Manipulating files and directories, os and sys modules; text files:
reading/writing text and binary files; creating and reading a formatted file
(csv or tab-separated); String manipulations: indexing, slicing a string-
string operations-number system-Regular expressions- match and search
functions; modifiers and patterns-python Decorators.
Case Studies: Creating a Hash File (or a message digest of a file) and
pattern recognition

1/19/2023 4
Syllabus Content
Unit – III Exception Handling and Multi-Threading in python
6
Exception handling: try, except and finally block, handling multiple
exceptions, raise an exception, User defined exception- python
multithreading- thread and threading module-Synchronizing Threads in
Python.
Case Study: Development of student performance evaluation report

Unit IV Data Analysis using Python libraries 6


NumPy: Introduction, NdArray object, Data Types, Array Attributes,
Indexing and Slicing, Array manipulation, mathematical functions,
Matplotlib; Pandas: Introduction to pandas data structures-series-Data
Frame-Panel-basic functions-descriptive statistics function-iterating data
frames-statistical functions-aggregations-visualization- plotting graphs
using plotly Library.
Case Study: Sales Forecasting
1/19/2023 5
Syllabus Content
Unit V UI and Game design using Python libraries 6
Tkinter module: introduction, widgets, standard attributes, Geometry
management, Tkinter Event Handling; Database connectivity with MySQL.
PyGame Module - PyGame Concepts- Basic Game Design-Sprites-Sprite
Groups-Custom Events-Collision Detection-Sprite Images-Game Speed-
Sound Effects.
Case Studies: Angry bird game and UI design

Text Books:
• Guido van Rossum, Learning Python: Crash Course Tutorial, The Python
development team publishers, 2020. [Unit-1,2,3]
• Bharti Motwani, Data Analytics using Python, paperback edition, Wiley
Publishing Ltd, 2020. [Unit-4]
• James R. Parker, Game Development Using Python, 2nd edition, Mercury
Learning and Information publishers,, 2021. [Unit-5]

1/19/2023 6
Syllabus Content
Reference Books:
• David M.Baezly , Python Essential Reference, 5th edition, Addison-
Wesley Professional;, 2021.
• John Shovic, Alan Simpson, Python for dummies. John Wiley & Sons,
2020.
Online References:
• Programming for Everybody (Getting Started with Python), Accessed on
02, April 2021 [Online] Available: https://www.coursera.org/learn/python
• Learn Python, Accessed on 02, April 2021 [Online] Available:
https://www.udemy.com/course/python-the-complete-python-developer-
course
• Introduction to Python Programming, Accessed on 02, April 2021 [Online]
Available: https://www.edx.org/professional-certificate/introduction-to-
python-programming
• The Python Standard Library, Accessed on 02, April 2021 [Online]
Available: https://docs.python.org/3/library
1/19/2023 7
Introduction to Python Programming

What is Python?
• Python is a general purpose, high level,
interpreted language with easy syntax and
dynamic semantics.
• Created by Guido Van Rossum in 1989

1/19/2023 8
Introduction to Python Programming
• Free and open-source

• Easy to learn

• Portable
Why Python?
• Different platforms
• Simple syntax
• Interpreter system
• Treated in a procedural or object-oriented or functional way.

1/19/2023 9
Python Syntax compared to other programming
languages

• New lines to complete a command

• indentation

Python is used for:


• web development (server-side),
• software development,
• mathematics,
• system scripting.

1/19/2023 10
How to Install Python IDE
• Integrated Development Environment:
• Thonny
• Pycharm
• Netbeans or Eclipse

• Web Application
• Jupyter
• Google Colab

1/19/2023 11
How to Install Python
• Step 1:
https://www.python.org/
downloads/

• Step 2:

1/19/2023 12
How to Install Python
• Step 3:

1/19/2023 13
How to Install Pycharm
• Step 1:
https://www.jetbrains.co
m/pycharm/download/

• Step 2:

1/19/2023 14
How to Install Pycharm
• Step 3:

• Step 4:

1/19/2023 15
How to Install Thonny
• Download Thonny IDE.
• Run the installer to install Thonny.
• Go to: File > New. Then save the file with .py extension.

1/19/2023 16
Different modes of programming

• Interactive Mode
Programming

• Script Mode Programming

1/19/2023 17
2.Basic Syntax in Python
Syntax:
 The set of rules / structure which defines how a Python program will
be written.
 Designed to be a highly readable language.
Basic Syntax:
 Python statement ends with the token NEWLINE character.
 Backslash character \ to join a statement span over multiple lines.
Expressions in parentheses (), square brackets [ ], or curly braces {
} can be spread over multiple lines without using backslashes.

1/19/2023 18
Indentation in Python
Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Python uses indentation to indicate a block of code.

Indentation Rules
 Use the colon : to start a block and press Enter.
 All the lines in a block must use the same indentation, either space
or a tab.
 A block can have inner blocks with next level indentation.

1/19/2023 19
Comments in Python
 Used to explain python code.
 Used to make the code more readable.
 Used to prevent execution when testing code.
 Any line starting with a # symbol, the Python interpreter will ignore
them.
 Does not really have a syntax for multi line comments.
 To add a multiline comment you could insert a # for each line.
 Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code,
and place your comment inside it.

1/19/2023 20
Python Naming Conventions

• Identifiers in Python are case sensitive


• Class names should use the TitleCase convention
• Function names should be in lowercase.
• Variable names in the function should be in lowercase
• Module and package names should be in lowercase
• Constant variable names should be in uppercase
• Two leading and trailing underscores are used in Python itself for a
special purpose

1/19/2023 21
Display Output
The print() serves as an output statement in Python.

Multiple values can be displayed by the single print() function


separated by comma.

1/19/2023 22
Getting User's Input
• The input() function is a part of the core library of standard Python
distribution.

The type() function used earlier confirms this behavior.

1/19/2023 23
Keywords in Python

 Keywords are the reserved words in Python.


 Keywords are case sensitive.

1/19/2023 24
5.Variables
 Variables are containers for storing data values.
 Unlike other programming languages, Python has no command for
declaring a variable.
 A variable is created the moment you first assign a value to it.
 Variables created inside a function is normally local, and can only be
used inside that function.
 To create a global variable inside a function, you can use
the global keyword.

1/19/2023 25
Assigning multiple values to multiple variables

Constants
• A constant is a type of variable whose value cannot be changed.

Unpack a Collection
• If you have a collection of values in a list, tuple etc. Python allows
you extract the values into variables. This is called unpacking.

1/19/2023 26
Rules for naming Variables
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three
different variables)

1/19/2023 27
Literals
 Literal is a raw data given in a variable or constant.
Numeric Literals
 Numeric Literals are immutable
 Integer, Float, and Complex
String literals
 Single Line String Literal
 Character Literal
 Multi-Line String Literal
Boolean literals
 True
 False
Special literals
 None
1/19/2023 28
Immutable Vs Mutable Variables

 Immutable Variables - An immutable object can't be changed after it


is created. In-built types like int, float, bool, string, unicode, tuple.
 Mutable Variables - An mutable object can be changed after it is
created. These are of type list, dict, set.
 Every object in python has identity(id), type and value.
 id() - returns an integer representing its identity.
 type() – returns the data type of the object.
 Value – Objects whose value changes are called Mutable and those
whose value doesn’t change is called Immutable.

1/19/2023 29
id() ?
 Why is it True for 3 but False for 261?
 The reason is that Python keeps an array of integer objects for all
integers between -5 and 256.
 When you create an integer in that range, you get back a reference to
the already existing object.

1/19/2023 30
Aliasing Vs Cloning
 Aliasing - Variables refer to objects and if we assign one variable to
another, both variables refer to the same object.
 Cloning - If we want to modify a list and also keep a copy of the
original, we need to make a copy of the list.

1/19/2023 31
type() ?
 All data is stored in the form of an object. An object has three
things: id, type, and value.
 The type function will provide the type of the object that’s provided
as its argument.

1/19/2023 32
Data types in Python
• Every value in Python has a datatype.
• Data types are actually classes and variables are instance (object) of
these classes.

Text Type : str


Numeric Types : int, float, complex
Sequence Types : list, tuple, range
Mapping Type : dict
Set Types : set, frozenset
Boolean Type : bool
Binary Types : bytes, bytearray, memoryview

1/19/2023 33
Data types in Python
• Python Numbers
• Integers, floating point numbers and complex numbers fall
under Python numbers category
 a=5 #Integer
 a = 2.0 # Float
 a = 1+2j #Complex
• type() function to know which class a variable or a value belongs to.
isinstance() function is used to check if an object belongs to a
particular class.

1/19/2023 34
Data types in Python
• Python List
• Lists are used to store multiple items in a single variable.
a = [1, 2.2, ‘veltech']
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item
has index [1] etc.
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
• To determine how many items a list has, use the len() function
print(len(a))

1/19/2023 35
Data types in Python
Python List
Access Items
• List items are indexed and you can access them by referring to the
index number
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
print(a[1])
• Negative indexing means start from the end. -1 refers to the last
item, -2 refers to the second last item etc.
print(a[-1])
• Range of Indexes Specifies where to start and where to end the
range.
print(a[2:5])
print(a[:4])
print(a[2:])
1/19/2023 print(a[-4:-1]) 36
Data types in Python
Python List
• To determine if a specified item is present in a list use
the in keyword
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
for “veltech” in a:
print(“yes”)
• To change the value of a specific item, refer to the index number
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
a[5]=“university”
print(a)
• To change the value of items within a specific range
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
a[1:3]=[3.8,“university”]
print(a)
1/19/2023 37
Data types in Python
Python List
• To insert a new list item, without replacing any of the existing
values, we can use the insert() method
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
a.insert(5.”CSE”)
• To add an item to the end of the list, use the append() method
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
a.append(”University”)
• To append elements from another list to the current list, use
the extend() method
a = [1, 2.2, ‘veltech‘]
b = [2, 3.4, ‘IIT‘]
a.extend(b)
1/19/2023 38
Data types in Python
Python List
• The remove() method removes the specified item
a = [1, 2.2, ‘veltech‘]
a.remove(”veltech”)
• The pop() method removes the specified index.
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
a.pop(2)
a.pop()
• The del keyword also removes the specified index
a = [1, 2.2, ‘veltech‘, 1, 2.2, ‘veltech']
del a[2]
• The clear() method empties the list
a.clear()
1/19/2023 39
Data types in Python
Python List
• Loop through the list items by using a for loop
for i in a:
print(i)
• Loop through the list items by using a while loop.
i=0
while(i < len(a)):
print(a[i])
i=i+1
• List comprehension offers a shorter syntax when you want to create
a new list based on the values of an existing list.
newlist = [expression for item in iterable if condition == True]

1/19/2023 40
Data types in Python
Python List
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default
a.sort()
• To sort descending, use the keyword argument reverse = True
a.sort(reverse=True)
• The reverse() method reverses the current sorting order of the
elements.
a.reverse()

1/19/2023 41
Data types in Python
Python Tuple
• Tuple is an ordered sequence of items same as a list. The only
difference is that tuples are immutable. Tuples once created cannot
be modified.
• Tuples are used to write-protect data and are usually faster than lists
as they cannot change dynamically.
• It is defined within parentheses () where items are separated by
commas.
t = (5,'program', 1+3j)
Access Tuple Items
• You can access tuple items by referring to the index number, inside
square brackets
print(t[1])
print(t[-1])
print(t[1:2])
1/19/2023 42
Data types in Python
Python Tuple
Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
x = (5,'program', 1+3j)
y = list(x)
y[1] = “CSE"
x = tuple(y)
print(x)

Unpacking a Tuple
• To extract the values back into variables from tuple is called
"unpacking“
x = (5,'program', 1+3j)
1/19/2023 (a, b, c)=x 43
Data types in Python
Python Set
• A set is a collection which is both unordered and unindexed.
• Set items are unordered, unchangeable, and do not allow duplicate
values
• Sets are written with curly brackets.
• To determine how many items a set has, use the len() method.
s = {“veltech", “cse", 1,3.5,2+3j}

Access Items
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.
for x in s:
print(x)
1/19/2023 44
Data types in Python
Python Set
Add Items
• Once a set is created, you cannot change its items, but you can add
new items.
• To add one item to a set use the add() method.
s = {“veltech", “cse", 1,3.5,2+3j}
s.add(“university")
print(s)
Add Sets
• To add items from another set into the current set, use
the update() method.
s.update(s1)
Remove Item
• To remove an item in a set, use the remove(), or the discard() method.
1/19/2023 45
Data types in Python
Python Set
Join Two Sets
• There are several ways to join two or more sets in Python.
• You can use the union() method that returns a new set containing all
items from both sets, or the update() method that inserts all the items
from one set into another:
set3 = set1.union(set2)
set1.update(set2)
• The intersection_update() method will keep only the items that are
present in both sets.
x.intersection_update(y)
• The symmetric_difference_update() method will keep only the
elements that are NOT present in both sets.
x.symmetric_difference_update(y)
1/19/2023 46
Data types in Python
Python Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and does
not allow duplicates.
d={
“name": “veltech",
“dept": “cse",
"year": 1990
}
print(d)
Accessing Items
• You can access the items of a dictionary by referring to its key name,
inside square brackets
x = d[“name"]

1/19/2023 47
Data types in Python
Python Dictionary
Get Keys
• The keys() method will return a list of all the keys in the dictionary.
x = thisdict.keys()
Get Values
• The values() method will return a list of all the values in the
dictionary.
x = thisdict.values()
Get Items
• The items() method will return each item in a dictionary, as tuples in a
list.
x = thisdict.items()

1/19/2023 48
Data types in Python
Python Dictionary
Change Values
• You can change the value of a specific item by referring to its key
name:
d["year"] = 2018
• The update() method will update the dictionary with the items from
the given argument.
d.update({"year": 2020})
Adding Items
• Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
d["color"] = "red"

1/19/2023 49
Data types in Python
Python Dictionary
Removing Items
• The pop() method removes the item with the specified key name
d.pop(“name")
• The popitem() method removes the last inserted item
d.popitem()
• The del keyword removes the item with the specified key name
del d[“name"]
• The clear() method empties the dictionary
d.clear()

1/19/2023 50
Conversion between data types
Type Conversion
The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion
• Implicit Type Conversion
• Explicit Type Conversion
Implicit Type Conversion
• In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("Value of num_new:",num_new)
1/19/2023
print("datatype of num_new:",type(num_new)) 51
Conversion between data types
Type Conversion
• Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.
• This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax
<required_datatype>(expression)

num_int = 123 num_str = "456“


num_str = int(num_str)
num_sum = num_int + num_str

1/19/2023 52
Python Operators
• Operators are used to perform operations on variables and values.
• Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is
called the operand.
>>> 2+3
5
• Python divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
1/19/2023
 Bitwise operators 53
Python Operators
Python Arithmetic Operators
• Arithmetic operators are used with numeric values to perform
common mathematical operations
Operator Meaning Example
+ Add two operands or unary plus x + y+ 2
- Subtract right operand from the left or unary minus x - y- 2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
x%y
Modulus - remainder of the division of left operand by the
% (remainder of
right
x/y)
Floor division - division that results into whole number
// x // y
adjusted to the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
1/19/2023 54
Python Operators
Comparison operators
• Comparison operators are used to compare values. It returns
either True or False according to the condition.

Operator Meaning Example


> Greater than - True if left operand is greater than the right x>y

< Less than - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greater


>= x >= y
than or equal to the right

Less than or equal to - True if left operand is less than or


<= x <= y
equal to the right

1/19/2023 55
Python Operators
Logical operators
• Logical operators are the and, or, not operators.

Operator Meaning Example


and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

1/19/2023 56
Python Operators
Bitwise operators
• Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary) and y = 4
(0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)


1/19/2023 57
Python Operators
Assignment operators
• Assignment operators are used in Python to assign values to
variables.

1/19/2023 58
Python Operators
Special operators
• Python language offers some special types of operators like the
identity operator or the membership operator.
Identity operators
• is and is not are the identity operators in Python. They are used to
check if two values (or variables) are located on the same part of the
memory.

Operator Meaning Example


True if the operands are identical (refer to
is x is True
the same object)

True if the operands are not identical (do


is not x is not True
not refer to the same object)

1/19/2023 59
Python Operators
Special operators
• Membership operators
• in and not in are the membership operators in Python. They are used
to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary)

Operator Meaning Example


True if value/variable is found in the
in 5 in x
sequence

True if value/variable is not found in the


not in 5 not in x
sequence

1/19/2023 60
9.Operators & its precedence

1/19/2023 61
11.Understanding Error Messages
 In Python 3.x, print is a built-in function and requires parentheses.

 IndexError is thrown when trying to access an item at an invalid


index.

 ModuleNotFoundError is thrown when a module could not be


found.

1/19/2023 62
Understanding Error Messages
 KeyError is thrown when a key is not found.

 ImportError is thrown when a specified function can not be found.

1/19/2023 63
Understanding Error Messages
 StopIteration is thrown when the next() function goes beyond the
iterator items.

 TypeError is thrown when an operation or function is applied to an


object of an inappropriate type.

1/19/2023 64
Understanding Error Messages
 ValueError is thrown when a function's argument is of an
inappropriate type.

 NameError is thrown when an object could not be found.

1/19/2023 65
Understanding Error Messages

 ZeroDivisionError is thrown when the second operator in the


division is zero.

 KeyboardInterrupt is thrown when the user hits the interrupt key


(normally Control-C) during the execution of the program.

1/19/2023 66
Understanding Error Messages

1/19/2023 67
Understanding Error Messages

1/19/2023 68
Basic Python Programs
1. Sum of two numbers.
2. Finding square root of a number.
3. Swap two variables.
4. Generate a random number.
5. Temperature conversion from celcius to fahrenheit.
6. ASCII value of a character.
7. Display calendar.
8. Vowel count in a sentence.

1/19/2023 69
Sum of two numbers
Program
a = int(input('Enter value of a:'))
b = int(input('Enter value of b:'))
c=a+b
print('The sum of ',a,' and ',b,' is = ',c)

Output
Enter value of a:5
Enter value of b:3
The sum of 5 and 3 is = 8

1/19/2023 70
Finding square root of a number
Program
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f' %(num, num_sqrt))

Output
Enter a number: 3
The square root of 3.000 is 1.732

1/19/2023 71
Swap two variables
Program
a = int(input('Enter value of a:'))
b = int(input('Enter value of b:'))
(a,b) = (b,a)
print('The value of a = ', a)
print('The value of b = ', b)

Output
Enter value of a:3
Enter value of b:2
The value of a = 2
The value of b = 3

1/19/2023 72
Generate a random number
Program
import random
print(random.randint(0,6))

Output
5

1/19/2023 73
Temperature conversion from celcius to fahrenheit.
Program
celsius = float(input('Enter temperature in celcius : '))
fahrenheit = (celsius * 1.8) + 32
print('%0.2f degree Celsius is equal to %0.2f degree Fahrenheit'
%(celsius,fahrenheit))

Output
Enter temperature in celcius : 37.5
37.50 degree Celsius is equal to 99.50 degree Fahrenheit

1/19/2023 74
ASCII value of a character
Program
c = input('Enter any character : ')
print("The ASCII value of '" + c + "' is", ord(c))

Output
Enter any character : A
The ASCII value of 'A' is 65

1/19/2023 75
Display Calendar
Program
import calendar
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))

Output

1/19/2023 76
Vowel count in a sentence
Program
vowels = 'aeiou'
ip_str = 'Hello, Welcome you all for python programming'
ip_str = ip_str.casefold()
count = {}.fromkeys(vowels,0)
for char in ip_str:
if char in count:
count[char] += 1
print(count)

Output
{'a': 2, 'e': 3, 'i': 1, 'o': 6, 'u': 1}

1/19/2023 77
range()
 Returns an immutable sequence of numbers between the given start
integer to the stop integer.
 Takes mainly three arguments having the same use in both
definitions:
 start - integer starting from which the sequence of integers is to be
returned. Default is 0.
 stop - integer before which the sequence of integers is to be
returned. The range of integers ends at stop -1.
 step (Optional) - integer value which determines the increment
between each integer in the sequence. Default is 1.

1/19/2023 78
Execution with range()

1/19/2023 79
3.Control Statements
 A control structure (or flow of control) is a block of programming
that analyses variables and chooses a direction in which to go based
on given parameters.
 Three basic types of control structures: Sequential, Selection and
Repetition.
 In addition to this there is break, continue and pass which changes
the usual order of execution.

1/19/2023 80
Control Statements
I. Sequential – Occurs when statements are executed one after another
in order. You don't need to do anything more for this to happen.
II. Selection - used for decisions, branching that is choosing between 2
or more alternative paths.
1. If 2. if…else 3. Nested if
4. if…Elif else Ladder 5. Switch
III. Iterative / Repetition - used for looping, i.e. repeating a piece of
code multiple times in a row.
1. while 2. do…while 3. for
IV. Loop control statements: break - breaks out of the innermost loop
and terminates the loop.
continue - continues with the next iteration of the loop by skipping
the current iteration.
pass - used when a statement is required syntactically but the
program requires no action.
1/19/2023 81
I.Sequential Statements
 Set of statements where the execution process will happen in
sequence manner.
 If the logic gets broken in any one of the line, then complete source
code execution will get broken.

1/19/2023 82
II.Selection / Conditional / Decision Making
Statements
 Decides the direction of flow of program execution.
 Evaluate multiple expressions which produce True or False as
outcome.
 You need to determine which action to take and which statements to
execute if outcome is True or False.
 Following are different types and constraints for building a good
decision making statements.

1/19/2023 83
if, if…else Statements
 If statement evaluates the test expression inside parenthesis. If test
expression is evaluated to True, statements inside the body of if is
executed.
 If the test expression is evaluated to False, statements inside the
body of else is executed.
 The else statement is an optional statement and there could be at
most only one else statement following if.
Syntax for if: Syntax for if…else:

1/19/2023 84
if, if…else Statements
 Executes if block only when it satisfies the condition and
terminates otherwise.

 Executes if block when it satisfies the condition and else block


when it fails the condition.

1/19/2023 85
Nested if Statements
 When an if statement is presented inside another if statement or
if/else statement.
 Tests for true/false conditions and then take an appropriate action.

Syntax

1/19/2023 86
if elif else ladder
 Checks for the condition and executes if block when it is True.
When it is False it checks next condition in the elif block and this
goes on until every conditions are checked.
 If all the conditions are False, the body of else is executed.
 Only one block among the several if...elif...else blocks is executed
according to the condition.
 The if block can have only one else block. But it can have multiple
elif blocks.
Syntax

1/19/2023 87
Nested if & if elif ladder Statements
Nested if

if elif ladder

1/19/2023 88
Switch Statements
 Python does not have a switch or case statement.
 In order to achieve switch statement, we can use a dictionary to map
cases to their functionality.
 We define a function week() to tell us which day a certain day of
the week is.
 A switcher is a dictionary that performs this mapping.

1/19/2023 89
III.Iterative / Repetition / Looping Statements
A.For loop
 A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
 Iterating over a sequence is called traversal.
 We can also use range function to traverse through the sequence.
Syntax

1/19/2023 90
B.while loop
 Used to iterate over a block of code as long as the test expression
(condition) is true.
 We generally use this loop when we don't know the number of
times to iterate beforehand.
 test expression is checked first. The body of the loop is entered only
if the test_expression evaluates to True.
 After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False.

Syntax

1/19/2023 91
for & while loop
for loop

while loop

1/19/2023 92
C.do…while
 Python doesn't have do-while loop. But we can create a program like
this.
 The do while loop is used to check condition after executing the
statement. It is like while loop but it is executed at least once.
Example

1/19/2023 93
IV.Loop Control Statements
A.Break
 The break statement terminates the loop containing it.
 Control of the program flows to the statement immediately after the
body of the loop.
 If the break statement is inside a nested loop (loop inside another
loop), the break statement will terminate the innermost loop.
Example Code

1/19/2023 94
B.continue
 The continue statement is used to skip the rest of the code inside a
loop for the current iteration only.
 Loop does not terminate but continues on with the next iteration.

Example Code

1/19/2023 95
C.pass
 The pass statement is a null statement.
 The difference between a comment and a pass statement in Python is
that while the interpreter ignores a comment entirely, pass is not
ignored.
 Nothing happens when the pass is executed. It results in no
operation (NOP).
Example Code

1/19/2023 96
Python Modules
 A module is a file with the extension.py that contains Python or C
executable code.
 A module is made up of a number of Python statements and
expressions.
 Modules allow us to use pre-defined variables, functions, and
classes.
 This cuts down on development time and allows code to be reused.

1/19/2023 97
Python Modules
Creating a Module in Python
• We can create a module by writing some code in a file and saving
that file in a veltech.py extension.
def display(): Output
print(“Vel Tech")
Vel Tech
if __name__ == "__main__":
display()
Importing a Module in Python
We can import a module by using the import keyword
import veltech
veltech.display()
1/19/2023 98
Python Modules
• We can import every object in a module by using the asterisk *
operator.
from veltech import *
display()
• Likewise, we can import a specific function from a module.
from pythongeeks import display
display()
• We can also alias a module while importing
import pythongeeks as pg
pg.display()

1/19/2023 99
Packages in Python
• To provide an application development environment, a python
package establishes a hierarchical directory structure with several
modules and sub-packages. They are nothing more than a bundle of
modules and sub-packages.
Creating and Importing a Package
• To create a Python package, we need to create a directory with a
__init__.py file and a module. Suppose we have created a package
named website with the previously created module veltech.py in it.
We can import the website package by using the import keyword
and a dot operator.
import website.pythongeeks
pythongeeks.display()

1/19/2023 100
Python Modules vs Packages
The following are some of the distinctions between Modules and
Packages:
• A Package is a directory containing numerous modules and sub-
packages, whereas a Module is a.py file containing Python code.
• An __init__ .py file is required to create a package. There is no
such necessity when it comes to creating modules.
• We can import all objects in a module at once by using the asterisk
(*) operator but we can’t import all modules in a package at once.

1/19/2023 101
1.Design with Functions
 A function is a group of related statements that performs a specific
task.
 Helps to break our program into smaller and modular chunks.
 When program grows larger and larger, functions make it more
organized and manageable.
 It avoids repetition and makes the code reusable.
Syntax
def function_name(parameters):
statement(s)
Example
def greet(name): #Function Definition
print("Hello, " + name + ". Good morning!")
greet('Arjun') #Function Call
1/19/2023 102
Aspects of Functions

1/19/2023 103
Types of Functions

Functions divided into the following two types:


1.Built-in Functions – functionality defined by default.
2.User-defined Functions – functionality defined by the user.
Functions vs Methods
 A method refers to a function which is part of a class.
 You access it with an instance or object of the class.
 A function doesn’t have this restriction: it just refers to a standalone
function.
 All methods are functions, but not all functions are methods.

1/19/2023 104
Functions vs Methods
 A function plus() and then a Summation class with a sum() method.
 A method refers to a function which is part of a class.
 You access it with an instance or object of the class.
 A function doesn’t have this restriction: it just refers to a standalone
function.
 All methods are functions, but not all functions are methods.
 A function plus() and then a Summation class with a sum() method.

Method Call

1/19/2023 105
Rules for Defining a User-defined Function
 Keyword def that marks the start of the function header.
 A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
 Parameters (arguments) are the variables/constants through which
we pass values to a function (optional).
 A colon (:) to mark the end of the function header.
 One or more valid python statements that make up the function
body.
 Statements must have the same indentation level (usually 4 spaces).
 An optional return statement to return a value from the function.

1/19/2023 106
Function Call
 We can call a defined function from another function, program or
even the Python shell.
 Function Call - type the function name with appropriate parameters.
 The return statement is used to exit a function and go back to the
place from where it was called.
 Can contain an expression that gets evaluated and the value is
returned.
 If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return
the None object.

1/19/2023 107
Working of Function in Python
 Scope of a variable - portion of a program where the variable is
recognized.
 Parameters and variables defined inside a function are not visible
from outside the function. They have a local scope.
 Lifetime of a variable - period throughout which the variable exits in
the memory.
 The lifetime of variables inside a function is as long as the function
executes.
 Destroyed once we return from the function.
 A function does not remember the value of a variable from its
previous calls.
1/19/2023 108
Scope & Lifetime of a Variable

1/19/2023 109
Understanding Scope of a Variable
 Code 1
Local Scope

Global Scope

 Code 2

Global Scope

Local Scope

Local Scope

1/19/2023 110
Understanding Scope of a Variable

global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3

1/19/2023 111
Understanding Scope of a Variable

Value of a using nonlocal is : 10


Value of a without using nonlocal is : 5

1/19/2023 112
Arguments & Return Values
 Formal arguments - identifiers used in the function definition to
represent corresponding actual arguments.
 Actual arguments - values(or variables) / expressions that are used
inside the parentheses of a function call.

1/19/2023 113
Passing Arguments to a Function

1/19/2023 114
Pass by Value & Pass by Reference
 In Python, we don't have to think about pass by value and pass by
reference as it does that automatically for you.
 To emulate this using Python, we use the concept of mutability.
 All parameters (arguments) in the Python language are passed by
reference.
 It means if you change what a parameter refers to within a function,
the change also reflects back in the calling function.
 If you pass immutable arguments like integers, strings or tuples to a
function, the passing acts like Call-by-value.
 It's different, if we pass mutable arguments.

1/19/2023 115
Pass by Value & Pass by Reference

1/19/2023 116
Variations of Function Arguments

1/19/2023 117
Variations of Function Arguments

1/19/2023 118
Positional / Keyword Arguments
 When we call a function with some values, these values get assigned
to the arguments according to their position.
 In keyword arguments we can call functions in different ways i.e.,
the order (position) of the arguments can be changed.
 Can mix positional arguments with keyword arguments during a
function call.
 But keyword arguments must follow positional arguments.

1/19/2023 119
Arbitrary Arguments
 We do not know in advance the number of arguments that will be
passed into a function.
 Python allows us to handle this kind of situation through function
calls with an arbitrary number of arguments.
 We use an asterisk (*) before the parameter name to denote this kind
of argument in function definition.

1/19/2023 120
Different ways of using return Statement in a
Function

1/19/2023 121
Use of values returned from a Function

1/19/2023 122
Program Structure and Design - Factorial

Output
5
The factorial of 5 is 120

1/19/2023 123
Program Structure and Design - Fibonacci

Output
How many terms? 6
Fibonacci sequence:
0
1
1
2
3
5

1/19/2023 124
2.Recursion
 A function that calls itself. Recursion is the process of defining and
calling a function in terms of itself.
Syntax

1/19/2023 125
Factorial of a number using Recursion
 When we call this function with a positive integer, it will recursively
call itself by decreasing the number.
 Each function multiplies the number with the factorial of the number
below it until it is equal to one.
 This recursive call can be explained in the following steps.

1/19/2023 126
Recursion in Python
 Our recursion ends when the number reduces to 1. This is called the
base condition.
 Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.
 The Python interpreter limits the depths of recursion to help avoid
infinite recursions, resulting in stack overflows.
 By default, the maximum depth of recursion is 1000. If the limit is
crossed, it results in RecursionError.

1/19/2023 127
Fibonacci Series of a number using Recursion

Output
Enter Number of Terms: 5
Fibonacci sequence:
0
1
1
2
3
1/19/2023 128
Advantages & Disadvantages of Recursion
Advantages
 Recursive functions make the code look clean and elegant.
 A complex task can be broken down into simpler sub-problems
using recursion.
 Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages
 Sometimes the logic behind recursion is hard to follow through.
 Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
 Recursive functions are hard to debug.
1/19/2023 129
Built-in Functions in Python
 Built-in functions are the ones whose functionality is predefined.
 These get stored in the interpreter and come into action when they
are called. These can be accessed from any part of the program. The
Python 3.6 version has 69 built-in functions and these are:

1/19/2023 130
Some of popular Built-in Functions in Python

1/19/2023 131
Built-in Functions in Python
abs()
 Return the absolute value of a number( An absolute numbers is the
magnitude of real number without regard to its sign).
Syntax:
>>>abs(X)

1/19/2023 132
Built-in Functions in Python
range()
 returns an iterator from a starting point to a end point with a specific
step. It is most commonly used in looping with a FOR LOOP.
Syntax:
range(start,stop[, step])
 Note: Stop is a mandatory argument.
 Start and Step are optional (Default value of start is 0 and step is 1).

1/19/2023 133
Built-in Functions in Python
bin()
 Converts an integer number to a binary string counterpart prefixed
with “0b “.
Syntax:
 >>> bin(x)

1/19/2023 134
Built-in Functions in Python
min()
 Return the smallest item in an iterable or the smallest of two or more
arguments.
 If one positional argument is provided, it should be an iterable. The
smallest item in the iterable is returned. If two or more positional
arguments are provided, the smallest of the positional arguments is
returned.
Syntax:
 >>>min(iterable)
 >>>min(arg1, arg2 ,…..)

1/19/2023 135
Built-in Functions in Python
max()
 Return the largest item in an iterable or the largest of two or more
arguments.
 If one positional argument is provided, it should be an iterable. The
largest item in the iterable is returned. If two or more positional
arguments are provided, the largest of the positional arguments is
returned.
Syntax:
>>>max(iterable)
>>>max(arg1, arg2 ,…..)

1/19/2023 136
Lambda Functions In Python
Lambda functions in Python are also known as Anonymous functions
(functions without a name). These functions replace the traditional
user-defined functions having two or more lines with a simple one-line
function.

Syntax for Lambda Functions in Python


lambda argument (s): expression

1/19/2023 137
Lambda Functions In Python
Example
def square(a):return a * a
#main() function
res = square(6)
print(res)
Output:
36
Here, a * a is a single expression. To execute this single
expression, we had to write a function definition with the 'def'
keyword, function name, parameters, and a return statement.
But all these are not required if we implement the same using
the lambda function.
1/19/2023 138
Lambda function with map()
map() function executes another user-defined function for each element
in an iterator. To do this it takes two arguments. One is user-defined
function and another is an iterator. Below is the example, in which
map() function executes the user-defined function len() for two
elements of the iterator.

#Without using Lambda Function #With using Lambda Function


def func(a):return len(a) list1 = [“Vel Tech", "Python"]
res = map(lambda a: len(a), list1)
#main() function print(list(res))
list1 = [“Vel Tech", "Python"]
res = map(func, list1)
print(list(res)) Output:
[8, 6]
Output:
[8, 6]

1/19/2023 139
Iterators in Python
In Python, an iterator is an object used to iterate over iterable objects
such as lists, tuples, dictionaries, and sets. An object is called iterable if
we can get an iterator from it or loop over it.

Let us understand this with one example:


Numbers = [2, 6, 8, 10, 12]

1/19/2023 140
Iterators in Python
In simple words, an iterator is just an object that can be iterated on.

A Python iterator object must implement two specific methods,


__iter__() or iter() and __next__() or next() , which are referred to
collectively as the iterator protocol.

1/19/2023 141
Python iter()
The iter() function in Python returns an iterator for the supplied object.
The iter() generates a thing that can be iterated one element at a time.
These items are handy when combined with loops such as for loops and
while loops.

Syntax:
iter( object , sentinel )

iter() function takes two parameters:

Object: An object whose iterator needs to be created (lists, sets, tuples,


etc.).
Sentinel (optional): Special value that represents the end of the
sequence.

1/19/2023 142
Python next()

The next() function returns the next item from the iterator. The next()
function holds the value one at a time.

Syntax:

next( iterator , default )

The next() method accepts two parameters:

Iterator : next( ) function retrieves the next item from the iterator.
default(optional): this value is returned if the iterator is exhausted (not
tired, but no next item to retrieve).

1/19/2023 143
Python next()
Assume we have a list of different types as given below.
list1 = [ 25 , 78, ‘coding’, ‘is’, ‘<3’ ] # list of different types
Let’s print it with the help of Iterators ( or iter() and next() ):-
# Program to print the list using Iterator protocols
X = [25, 78, 'Coding', 'is', '<3']
# Get an iterator using iter()
a = iter(X)
# Printing the a iterator
print(a)
# next() for fetching the 1st element in the list that is 25
print(next(a))
Output
# Fetch the 2nd element in the list that is 78
print(next(a)) <list_iterator object at
# Fetching the consecutive elements 0x000001B91F9CFFD0>
print(next(a)) 25
print(next(a)) 78
print(next(a)) Coding
is
1/19/2023 144
<3
Python next()

1/19/2023 145
Generators in Python
uilding an iterator in Python requires a significant amount of effort. We must
create a class containing __iter__() and __next__() methods, keep track of
internal states and raise StopIteration when no values are returned. This is both
long and contradictory. In such cases, the generator comes to the rescue.

Python has a generator that allows you to create your iterator function. A
generator is somewhat of a function that returns an iterator object with a
succession of values rather than a single item. A yield statement, rather than a
return statement, is used in a generator function.

The difference is that, although a return statement terminates a function


completely, a yield statement pauses the function while storing all of its states
and then continues from there on subsequent calls.

1/19/2023 146
Generators in Python

1/19/2023 147
Generators in Python
Example 1:
# Program to print the Power of two up to the given number
def PowerTwoGen( max=0 ):
n=1
while n < max:
yield 2 ** n
n += 1
a = PowerTwoGen(6)
# Printing the values stored in a
for i in a:
print(i)

Output
2
4
8
16
32
1/19/2023 148
Comparison of Iterators and Generators in python

Iterators Generators

A generator is a function that produces or


Iterators are the objects that use the next() yields a sequence of values using a yield
method to get the next value of the sequence. statement.

Classes are used to Implement the iterators. Functions are used to implement the generator.
Every iterator is not a generator. Every generator is an iterator.

Generators in Python are simpler to code than


Complex implementation of iterator protocols do the custom iterator using the yield
.i.e., iter() and next(). statement.
Generators in Python are more memory
Iterators in python are less memory efficient. efficient.
All the local variables are stored before the
No local variables are used in Iterators. yield statement.

1/19/2023 149
Thank You

1/19/2023 150

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy