0% found this document useful (0 votes)
2 views

Module 1 - Python

Module 1 of the Python Programming course covers Python basics, including data types, flow control, functions, and program execution. It introduces Python as a high-level, interpreted, and object-oriented language, highlighting its features, applications, and historical development. The module also provides practical examples and exercises to familiarize learners with the Python interactive shell and basic programming concepts.

Uploaded by

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

Module 1 - Python

Module 1 of the Python Programming course covers Python basics, including data types, flow control, functions, and program execution. It introduces Python as a high-level, interpreted, and object-oriented language, highlighting its features, applications, and historical development. The module also provides practical examples and exercises to familiarize learners with the Python interactive shell and basic programming concepts.

Uploaded by

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

Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

Module 1
Python Basics, Flow Control, Functions

Topics Covered in the Module:


Python Basics, Entering Expressions into the Interactive Shell, The Integer, Floating-Point, and String
Data Types, String Concatenation and Replication, Storing Values in Variables, Your First Program,
Dissecting Your Program, Flow control, Boolean Values, Comparison Operators, Boolean Operators,
Mixing Boolean and Comparison Operators, Elements of Flow Control, Program Execution, Flow Control
Statements, Importing Modules, Ending a Program Early with sys.exit(), Functions, def Statements with
Parameters, Return Values and return Statements, The None Value, Keyword Arguments and print(),
Local and Global Scope, The global Statement, Exception Handling, A Short Program: Guess the Number
Textbook 1: Chapters 1 – 3
RBT: L1, L2

Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”, 1 st Edition, No Starch Press,
2015. (Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/)

Department of CSE, Vemana IT Page 1 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.1 Introduction to Python


 Python is a general purpose high-level programming language, interpreted, interactive and object-
oriented scripting language.
 The Python programming language has a wide range of syntactical constructions, standard library
functions, and interactive development environment features.
 It was developed by Guido van Rossum during 1989 at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
 Python source code is also available under the GNU General Public License (GPL).
 Python is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.

1.1.1. Why to learn Python?


 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.

1.1.2. Why the name Python?


 When van Rossaum began implementing Python, he was also reading the published scripts from
“Monty Python’s Flying Circus”, a BBC comedy series from the 1970s.
 Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he
decided to call the language Python.

1.1.3. Features/Applications of Python


 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.

Department of CSE, Vemana IT Page 2 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

 Easy-to-maintain − Python's source code is fairly easy-to-maintain.


 A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
 Extendable − we can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than shell scripting.

Other Features include


 It supports functional and structured programming methods as well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for building large
applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

1.1.4. Characteristics of Python


 It supports functional and structured programming methods as well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for building large
applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Department of CSE, Vemana IT Page 3 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.1.5. History of Python


 Python laid its foundation in the late 1980s.
 The implementation of Python was started in the December 1989 by Guido Van Rossum at the
National Research Institute for Mathematics and Computer Science in the Netherlands . This
release included exception handling, functions, and the core data types of list, dict, str and others.
It was also object oriented and had a module system.
 In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
 In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
 Six and a half years later in October 2000, Python 2.0 was introduced. This release included list
comprehensions, a full garbage collector and it was supporting unicode.
 On December 3, 2008, Python 3.0 (also known as "Python 3000" and "Py3K") was released. It
was designed to rectify fundamental flaw of the language. Python 3 is not backwards compatible
with Python 2.x.
 ABC programming language is said to be the predecessor of Python language which was capable
of Exception Handling and interfacing with Amoeba Operating System.
 Python is influenced by following programming languages:
 ABC language.
 Modula-3
 Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
 Python is now maintained by a core development team at the institute, although Guido van Rossum
still holds a vital role in directing its progress.

1.1.6. Versions of Python


Python Version Release Date Python Version Release Date
Python 1.0 January 1994 Python 3.0 December 3, 2008
Python 1.5 December 31, 1997 Python 3.1 June 27, 2009
Python 1.6 September 5, 2000 Python 3.2 February 20, 2011
Python 2.0 October 16, 2000 Python 3.3 September 29, 2012
Python 2.1 April 17, 2001 Python 3.4 March 16, 2014
Python 2.2 December 21, 2001 Python 3.5 September 13, 2015
Python 2.3 July 29, 2003 Python 3.6 December 23, 2016

Department of CSE, Vemana IT Page 4 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

Python 2.4 November 30, 2004 Python 3.7 June 27, 2018
Python 2.5 September 19, 2006 Python 3.8 December 18, 2019
Python 2.6 October 1, 2008 Python 3.8.2 February 24, 2020
Python 2.7 July 3, 2010 Python 3.8.3 May 13, 2020
Python 3.8.4 July 13, 2020
Python 3.8.5 July 20, 2020
Python 3.9 Oct 10, 2020
Python 3.10 Oct 4, 2021

1.1.7. Applications of Python


1) Web Applications: Python can be used to develop web applications. It provides libraries to handle
internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design and
delelop web based applications. Some important developments are: PythonWikiEngines, Pocoo,
PythonBlogSoftware etc.
2) Desktop GUI Applications: Python provides Tk GUI library to develop user interface in python
based application. Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several
platforms. The Kivy is popular for writing multitouch applications.
3) Software Development: Python is helpful for software development process. It works as a support
language and can be used for build control and management, testing etc.
4) Scientific and Numeric: Python is popular and widely used in scientific and numeric computing.
Some useful library and package are SciPy, Pandas, IPython etc. SciPy is group of packages of
engineering, science and mathematics.
5) Business Applications: Python is used to build Business applications like ERP and e-commerce
systems. Tryton is a high level application platform.
6) Console Based Application: Python is used to develop console based applications. For example:
IPython.
7) Audio or Video based Applications: Python is awesome to perform multiple tasks and can be
used to develop multimedia applications. Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications: To create CAD application Fandango is a real application which provides
full features of CAD.

Department of CSE, Vemana IT Page 5 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

9) Enterprise Applications: Python can be used to create applications which can be used within an
Enterprise or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images: Using Python several applications can be developed for image.
Applications developed are: VPython, Gogh, imgSeek etc.

1.1.8. Java vs Python

Parameter Java Python

Java is both compiled and interpreted


Python is an interpreted
Compilation process language, which is first compiled and
programming language
then interpreted into a byte code.

Longer lines of code as compared to 3-5 times shorter than equivalent


Code Length
python. Java programs.

Define particular block by curly braces, No need of semi colons and curly
Syntax Complexity
end statements by ; braces, uses indentation

Strongly typed, need to define the exact Dynamic, no need to define the
Ease of typing
datatype of variables exact datatype of variables.

Java is much faster than python in terms Expected to run slower than Java
Speed of execution
of speed. programs

Multiple inheritance is partially done Provide both single and multiple


Multiple Inheritance
through interfaces inheritance.

Developed by James Gosling (1991) Guido van Rossum (1989)

First release 1995 1991

Extension .java .py

Keywords 51 37

Department of CSE, Vemana IT Page 6 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.1.9. Python IDE Tools


 Anaconda Navigator is a desktop graphical user interface (GUI) included in Anaconda®
distribution that allows you to launch applications and easily manage conda packages
o PyCharm
o Spyder
o Jupyter
o Eclipse PyDev
o IDLE (cross-platform open-source IDE)
o Wing

1.2 Python Basics


1.2.1 Entering Expressions into Interactive Shell
 Interactive shell in python can be launched using Python IDLE, which will be installed with Python
 On Windows, open the Start menu, select All Programs  Python 3.3, and then select IDLE
(Python GUI). A window with the >>> prompt should appear; that’s the interactive shell.
 On OS X, select Applications ▸ MacPython 3.3  IDLE. On Ubuntu, open a new Terminal
window and enter idle3.
 To find sum of 2 numbers example, enter 2 + 2 at the prompt to have Python do some simple math.
>>> 2 + 2  will give 4 as an answer
 In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction
in the language.
 Expressions consist of values (such as 2) and operators (such as +), and they can always evaluate
(that is, reduce) down to a single value. That means you can use expressions anywhere in Python
code that you could also use a value.
 In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value with no
operators is also considered an expression, though it evaluates only to itself, as shown here
>>> 2 results in 2

 Table 1-1. Math Operators from Highest to Lowest Precedence


Operator Operation Example Evaluates to ..

** Exponent 2 ** 3 8

% Modulus / Remainder 2%8 6

Department of CSE, Vemana IT Page 7 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

// Integer Division / Floor Quotient 22 // 8 2

/ Division 22 // 8 2.75

* Multiplication 3*5 15

- Subtraction 5–2 3

+ Addition 2+2 4

 Evaluate
>>> 2 + 5 * 6 #32
>>> 29 // 6 #4
>>> (6 -1) * ((7+2)/(3-1)) #22.5

Evaluating expression

1.2.2 The Integer, Floating-Point, and String Data Types


 A data type is a classification that specifies which type of a value a variable has.
 A data type is a category for values, and every value belongs to exactly one data type.
 Common Data types

Department of CSE, Vemana IT Page 8 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

 The values -2 and 30, are said to be integer values. The integer (or int) data type indicates values
that are whole numbers.
 Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats).
 Note that even though the value 42 is an integer, the value 42.0 would be a floating-point number.

1.2.3 String Concatenation (+)


>>> ‘Hello! #Syntax error : EOL while scanning string literal (closing Single
#quote is missing)

 When + operator is used between strings it will act as Concatenation Operator


 Ex : >>> ‘Alice’ + ‘Bob’ #‘AliceBob’

 If + operator is used between string and integer, an error message will be displayed
o >>>’Alice’ + 5 #TypeError : Can’t convert ‘int’ object to str implicitly

1.2.4 Replication Operator (*)


 When * operator is used between string value and an integer value it becomes String replication
operator.
o >>> ‘Alice’ * 3 #AliceAliceAlice’
 Operator can be used between 2 numbers or between a string and integer otherwise error will be
displayed
 >>>’Alice’ * ‘Bob’ #TypeError : Can’t multiply sequence of non-int of
#type ‘str’
 >>>’Alice’ * 5.0 #TypeError : Can’t multiply sequence by non-int of
#type ‘float’

1.2.5 Storing Values in Variables


 A variable is the name of computer’s memory location where single value can be stored.
 Values are stored in a variable using Assignment Statement
 A good variable name describes the data it contains.
 Assignment statement consists of name of the variable, assignment operator (=) and a value.
>>> a = 7.7

Department of CSE, Vemana IT Page 9 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

>>> a #outputs 7.7


>>> b = 3.3
>>> a+b #outputs 11.0

 A variable is initialized (or created) the first time a value is stored in it (spam = 'Hello')
 After that, variable can be used in expressions with other variables and values (s=spam)
 When a variable is assigned a new value, the old value is forgotten. (spam = 'Goodbye‘)

Rules for Variable names


 Variable names are case sensitive.
 It has to be only one word
 It should contain only letters, numbers, under score character.
 It can’t begin with a number.
 Valid Variables:
o balance, curBal, acc4
 Invalid Variables
o cur-bal (hyphan not allowed)
o cur bal (spaces are not allowed)
o 4acc (Can’t begin with a number)
o tot_$um ( Special characters are not allowed)

Department of CSE, Vemana IT Page 10 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.2.6 Your First Program


 The file editor is similar to text editors such as Notepad or TextMate can be used to type python
programs.
 To open the file editor in IDLE, select File▸ New Window.
 The major difference between Interactive shell and file editor
 The interactive shell window will always be the one with the >>> prompt.
 The file editor window will not have the >>> prompt.

first.py
# This program says hello and asks for your name
print(‘Hello world!’)
print(‘What is your name?’) # ask for your name
myname = input() #ask user to enter name
print(‘It is good to meet you ’+myname)
print(‘The length of your name is :’+str(len(myname))
print(‘What is your age?’) # ask for the age
myage = input() #ask user to enter age
print(‘You are ’+str(int(myage) + 1) +’ in next year.’)

 Once the program is typed it should be saved with .py extension


Ex: first.py
 Running the program from command prompt type
py hello.py
 Output
Hello World !
What is your name? #enter Raju
It is good to meet you, Raju
The length of your name is : 4
What is your age? #enter value: 37
You will be 38 in next year

Department of CSE, Vemana IT Page 11 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.2.7 Dissecting Your Program


Comments
 Comment in python starts with #
#this is the first program in python
 Single Line Comment
# is used at the beginning of any statement
 Multi Line Comment
# is used in each line or
 Use of triple quotes(3 times double quote) at beginning & end
Use of double quotes at beginning & end

The print() Function


 print() is an output function which displays the specified message on the screen
print(“Welcome to Python”)
print('Hello world!')
print('What is your name?')
Year=input(“Enter Year”) #Year - int value: 1991
print(“Python is released in the year:”+ Year)
Python is released in the year: 1991

The input() Function


 The input() function waits for the user to type some text on the keyboard and press ENTER.
 The input() function waits for user to enter some text on a console, reads a line entered on a console
by an input device such as a keyboard and convert it into a string and returns it.
myname = input()
 This function call evaluates to a string equal to the user’s text, and the previous line of code assigns
the myName variable to this string value.

Printing the User’s Name


 The following call to print() actually contains the expression
‘Hai Welcome, ' + myName between the parentheses.
or
print(‘Hai Welcome,' + myName)

Department of CSE, Vemana IT Page 12 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

The len() Function


 len() function takes a string value and returns the number of characters in that string
>>> myname = ‘Hello’ #5
>>> len(myname) #5
>>> len(‘Hello, Welcome.') # 15
>>> len(‘ ') #0

The str(), int(), and float() Functions


 str() function converts the value passed to it as string
>>> a=str('29') # here '29‘ is string or
>>> a=str(29) #here, 29 is int converted to string
>>> type(a) #<class 'str'>

 int() function converts the value passed to it as integer


>>> b=int(’29’) #29
>>> type(b) #<class ‘int'>

 If we pass a value to int that in cannot evaluate as an integer, an error message will be displayed.
int('99.99') #ValueError: invalid literal for int() with base 10: '99.99‘
int(‘two’) #ValueError: invalid literal for int() with base 10: 'two‘

 int() function is also used if we need to round a floating point number down.
int(7.7) + 1 #8
 float() function converts the value passed to it as floating point
float(10) #10.0
 The str() function is handy when you have an integer or float that you want to concatenate to a
string. The int() function is also helpful if you have a number as a string value that you want to
use in some mathematics.
>>> spam = input() # read 100
>>> spam # ’100’
>>> spam = int(spam)
>>> spam # 100
>>> spam * 10 / 5 # 200.0
>>> int(7.7) #7

Department of CSE, Vemana IT Page 13 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

>>> 42==42 #True


>>> 42==42.0 #True
>>> 42=='42‘ #False
>>> 42==0042.0 #True
 Python makes this distinction because strings are text, while integers and floats are both numbers.

1.3 Flow Control


 Flow control statements can decide which Python instructions to execute under which conditions.
 Flow control statements directly correspond to the symbols in a flowchart

1.3.1 Boolean Values


 Boolean data type has only 2 values: True and False. (True and False are keywords).
 (Boolean is capitalized because the data type is named after mathematician George Boole.)
>>> spam = True
>>> spam #True
>>> true #NameError: name 'true' is not defined
>>> True #True
>>> True+2 #3
>>> True=2+2 #SyntaxError: can't assign to keyword

 Boolean values are used in expressions and can be stored in variables.


 If you don’t use the proper case or you try to use True and False for variable names, Python will
give you an error message.

Department of CSE, Vemana IT Page 14 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.3.2. Comparison Operators


 Comparison operators compare two values and evaluate down to a single Boolean value.

Operator Meaning

== Equal to

!= Not Equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

 Operators evaluate to True or False depending on the values you give them.
>>> 42 == 42 #True
>>> 42 == 99 #False
>>> 2 != 3 #True
>>> 2 != 2 #False

 == (equal to) evaluates to True when the values on both sides are the same, and != (not equal to)
evaluates to True when the two values are different.
>>> 'hello' == 'hello‘ #True
>>> 'hello' == 'Hello‘ #False
>>> 'dog' != 'cat‘ #True
>>> True == True #True
>>> True != False #True
>>> 42 == 42.0 #True
>>> 42 == '42‘ #False

 The <, >, <=, and >= operators, on the other hand, work properly only with integer and floating-
point values.
>>> 42 < 100 #True
>>> 42 > 100 #False

Department of CSE, Vemana IT Page 15 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

>>> 42 < 42 #False


>>> eggCount = 42
>>> eggCount <= 42 #True
>>> myAge = 29
>>> myAge >= 10 #True

1.3.3. Boolean Operators


== vs =
 The == operator (equal to / Comparison) asks whether two values are the same as each other.
 The = operator (assignment) puts the value on the right into the variable on the left.

 The three Boolean operators (and, or, and not) are used to compare Boolean values.
 Boolean operators evaluate the expressions down to a Boolean value.

Binary Boolean Operators (and)


 The and and or operators takes two Boolean values (or expressions), so they’re considered as
binary operators.
 The order of preference among Boolean operators are not, and, or
 The and operator evaluates an expression to True if both Boolean values are True; otherwise, it
evaluates to False.
>>> True and True #True
>>> True and False #False
 The and Operator’s Truth Table
Expression Evaluates to ….

True and True True

True and False False

False and True False

False and False False

Department of CSE, Vemana IT Page 16 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

Binary Boolean Operators (or)


 The or operator evaluates an expression to True if either of the two Boolean values is True. If both
are False, it evaluates to False.
>>> True or True #True
>>> False or False #False
>>> True or False #True
 The or Operator’s Truth Table

Expression Evaluates to ….

True or True True

True or False True

False or True True

False or False False

Binary Boolean Operators (not)


 The not operator operates on only one Boolean value (or expression).
 The not operator simply evaluates to the opposite Boolean value.
>>> not True #False
>>> not not not not True #True

Expression Evaluates to ….

not True False

not False True

1.3.4. Mixing Boolean and Comparison Operators


 Boolean expressions that use comparison operators into the interactive shell
>>> (4 < 5) and (5 < 6) #True
>>> (4 < 5) and (9 < 6) #False
>>> (1 == 2) or (2 == 2) #True

>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 #True

Department of CSE, Vemana IT Page 17 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

 The Boolean operators have an order of operations just like the math operators do.
 After any math and comparison operators evaluate, Python evaluates the not operators first, then
the and operators, and then the or operators.

1.3.5. Elements of Flow Control


 Flow control statements often start with a part called the condition, and all are followed by a
block of code called the clause.
 Conditions
o Condition is a flow control statement which always evaluates to True or False
o Condition is just a more specific name in the context of flow control statements.
o A flow control statement decides what to do based on whether its condition is True or
False, and almost every flow control statement uses a condition.
 Blocks of Code
o Lines of Python code can be grouped together in blocks.
o Indentation of lines is used to identify beginning of block and end of block
o There are three rules for blocks.
 Blocks begin when the indentation increases.
 Blocks can contain other blocks.
 Blocks ends when the indentation decreases to zero or to a containing block’s
indentation.
o Blocks are easier to understand by looking at some indented code
if name == 'Ravi':
print('Hello Ravi')
if password == 'Ra@123':
print('Access granted.')
else:
print('Wrong password.')

Department of CSE, Vemana IT Page 18 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

if Statements
 An if statement’s clause (the block following the if statement) will execute if the statement’s
condition is True. The clause is skipped if the condition is False.
 An if statement could be read as, “If this condition is true, execute the code in the clause.”
 In Python, an if statement consists of the following:
o The if keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the if clause)

 Ex:-
if name == ‘Alice’:
print(‘Hi Alice’)

else Statements
 An if clause can optionally be followed by an eelse Statements lse statement. The else clause is
executed only when the if statements condition is False.
 An else statement could be read as, “If this condition is true, execute this code. Or else, execute
that code.”
 An else statement doesn’t have a condition, and in code, an else statement always consists of the
following:
o The else keyword
o A colon
o Starting on the next line, an indented block of code (called the else clause)
 Example
if name == ‘Alice’:

Department of CSE, Vemana IT Page 19 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

print(‘Hi Alice’)
else:
print(‘Hello Stranger’)
 Flow chart

elif Statements
• The elif statement is an “else if” statement that always follows an if or another elif statement.
• It provides another condition that is checked only if any of the previous conditions were False.
• In code, an elif statement always consists of the following:
o The elif keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the elif clause)
• Example 1:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
• Flow Chart

Department of CSE, Vemana IT Page 20 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

Example 2:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')

while Loop Statements


 The code in a while clause will be executed as long as the while statement’s condition is True.
 In code, a while statement always consists of the following:
o The code in a while clause will be executed as long as the while statement’s condition is
True.
o In code, a while statement always consists of the following:
 Example

Department of CSE, Vemana IT Page 21 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
 Flowchart

An Annoying while Loop


 Example
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')

 Flow chart

Department of CSE, Vemana IT Page 22 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

break Statements
 If the execution of the program reaches a break statement it immediately exits the while loop’s
clause.
 Example
while True:
print(‘Enter name of the subject’)
name = input()
if name == ‘python’:
break
print(‘Thanks’)
 Flow chart

Department of CSE, Vemana IT Page 23 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

continue Statements
 Continue statements are used inside loops. When the program execution reaches a continue
statement, the program execution immediately jumps back to the start of the loop and re-evaluates
the loop’s condition.
 Example
while True :
print('who are you')
name = input()
if name != 'abc':
continue
print('Hello abc, enter your password')
password = input()
if(password == '1234'):
break
print('Access Granted')

Department of CSE, Vemana IT Page 24 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

for loops and the range function


 A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
 With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc..
 The for statements include the following
o The for keyword.
o A variable name
o The in keyword
o A call to range() method with up to 3 integers passed to it.
o A colon
o Starting on the next line an indented block of code.

 Example 1
total = 0
for num in range(10) :
total = total + num
print(total) #45

 Example 2
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')

Department of CSE, Vemana IT Page 25 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

An Equivalent while Loop


 A while loop to do the same thing as a for loop;
 for loops are just more concise.
 Example
print('My name is')
i=0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i=i+1

The Starting, Stopping, and Stepping Arguments to range()


 range() to follow any sequence of integers, including starting at a number other than zero.
for i in range(12, 16):
print(i) # prints 12 13 14 15

 The range() function can also be called with three arguments. The first two arguments will be the
start and stop values, and the third will be the step argument. The step is the amount that the
variable is increased by after each iteration.
for i in range(0, 10, 2): #Begin: 0 End: 10 (Exclude) interval: 2
print(i) #prints 0 2 4 6 8

 The range() function is flexible in the sequence of numbers it produces for for loops
for i in range(5, -1, -1):
print(i) #5 4 3 2 1 0

for i in range(5, 0, -2):


print(i) #5 3 1

1.3.6. Importing Modules


 Python also comes with a set of modules called the standard library. Each module is a Python
program that contains a related group of functions that can be embedded in your programs.

Department of CSE, Vemana IT Page 26 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

 For example, the math module has mathematics-related functions, the random module
(random.randint() function) for random number related functions, and so on.
 To use module, use import keyword with module name.
 An import statement consists of the following:
o The import keyword
o The name of the module
o Optionally, more module names, as long as they are separated by commas.

 Example
import random
for i in range(5): #repeat for 0 to 4
print(random.randint(1, 10)) #prints 4 1 8 4 1 (may very)

 The random.randint() function call evaluates to a random integer value between the two integers
that you pass it.
 An import statement that imports four different modules:
import random, sys, os, math

1.3.7. Random Numbers


 The function randint takes the parameters low and high, and returns an integer between low and
high (including both).
>>> random.randint(5, 10) # prints number between 5 to 10
• To choose an element from a sequence at random, you can use choice:
>>> t = [1, 2, 3]
>>> random.choice(t) #2
>>> random.choice(t) #3

1.3.8. Math Functions


• Python has a math module that provides most of the familiar mathematical functions.
• Before using the module, we have to import it:
>>> import math
• This statement creates a module object named math. If you print the module object, you get some
information about it:

Department of CSE, Vemana IT Page 27 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

>>> print(math) #<module 'math' (built-in)>


>>> math.sqrt(3) #1.7320508075688772
>>> math.pi # 3.141592653589793
>>> math.factorial(5) #120
>>> math.gcd(5,7) #1

Other form of importing modules


• It is composed of from keyword, followed by module name, the import keyword and a star.
• Each module is a python program that contains a related group of functions that can be
embedded in programs.
• Ex:
from random import *
from random import * #from random module import all(*)

for i in range(5):
print(randint(1,10) # call to randint() need not be prefixed with
# random.

1.3.9. Ending a Program Early with sys.exit()


• If the program need to exit before executing last line of the code then exit() method in sys module
can be used.
• Example
import sys
while True:
print(‘Type E to exit’)
response = input()
if response == ‘E’:
sys.exit()
print(‘You typed ’+response)

1.4. Functions
• A function is a block of organized, reusable code that is used to perform a single, related action.

Department of CSE, Vemana IT Page 28 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

• It provides better modularity to application and a high degree of code reusing.


• A function is like a mini-program within a program.
• Python provides several built-in functions like print(), input(), and len() functions, but you can also
write your own functions.

1.4.1. Defining a Function


• Function block begins with a keyword def followed by the function name and parenthesis
• Any number of input parameters should be placed within these parentheses
• A colon
• Starting on the next line an indented block of code.
• The return statement at the end of code block exits a function. A return statement with no
arguments is the same as return None
• Syntax:
def functionname(parameters):
function block
return [expression]
• Example
def printme(str):
print(str)
return

printme(“Abc”)

Calling a function
• It can be called by name of the function and passing arguments.
• Ex:- printme(‘Vemana Institute of Technology’)

• Example :
def hello(name):
print('Hello ' + name)

hello('Alice') #Hello Alice


hello('Bob') # Hello Bob

Department of CSE, Vemana IT Page 29 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.4.2. The None Value


• In Python there is a value called None, which represents the absence of a value.
• None is the only value of the NoneType data type. (Other programming languages might call this
value null, nil, or undefined.)
• None must be typed with a capital N.
• To know the return value of None
>>> spam = print('Hello!') #Hello!, here spam doesnot have value
>>> None == spam #True
>>> type(spam) #<class 'NoneType'>

1.4.2. Parameters and Arguments


• The information into the functions can be passed as the parameters. The parameters are specified
in the parentheses. We can give any number of parameters, but we have to separate them with a
comma.
• Example 1
#defining the function
def func (name):
print("Hai ",name); #print(‘Hai’+name)

#calling the function


func("Manu")

• Example 2: Finding sum of 2 numbers


#python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;

#taking values from the user


a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b


print("Sum = ",sum(a,b))

Department of CSE, Vemana IT Page 30 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

• Example 3: Print Hai Message


>>> def print_twice(bruce):
print(bruce) #print hai 5 times
print(bruce) #print hai 5 times

>>> print_twice('Hai') #prints Hai Hai (2 times)


>>>print_twice('Hai '*5) #prints Hai Hai Hai Hai Hai (twice)

• Function definition cannot be empty, otherwise error


• To define empty function, use pass keyword
• Example
def sum(a,b):
pass
sum(10,20)

Parameters and Arguments: Pass by reference


 All parameters (arguments) in the Python language are passed by reference.
 Example
# Function definition is here
def changeme( mylist ):
#"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print('Values inside the function: ', mylist)
return

# Now you can call changeme function


mylist = [10,20,30]; #[ ]->List, ( )->Tuple
changeme( mylist );
print ('Values outside the function: ', mylist)

Output: Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

Department of CSE, Vemana IT Page 31 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

The None Value


def no_return(x, y):
c=x+y

res = no_return(4, 5)
print(res) #None

1.4.3. Keyword Parameters


 Using keyword parameters is an alternative way to make function calls. The definition of the
function doesn't change.
def sumsub(a, b, c=0, d=0):
return a - b + c - d
print(sumsub(12, 4)) #8
print(sumsub(42, 15, d=10)) #17

Return Values and return Statements


• A return statement ends the execution of the function call and "returns" the result
• If the return statement is without an expression, the special value None is returned.
• A return value can be any one of the four variable types: handle, integer, object, or string.
• Example
import random
# function which returns name of the day based on number
def getDay(num):
if num == 1:
return 'Monday'
elif num == 2:
return 'Tuesday'
elif num == 3:
return 'Wednesday'
elif num == 4:
return 'Thursday‘
elif num == 5:

Department of CSE, Vemana IT Page 32 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

return 'Friday'
elif num == 6:
return 'Saturday'
elif num == 7:
return 'Sunday'

#main program
r = random.randint(1,7)
day = getDay(r)
print(day)

• keyword arguments are identified by the keyword put before them in the function call.
• Keyword arguments are often used for optional parameters.
• For example, the print() function has the optional parameters end and sep to specify what should
be printed at the end of its arguments and between its arguments (separating them),respectively.
• The two strings appear on separate lines because the print() function automatically adds a newline
character to the end of the string it is passed.
• However, use of end keyword argument to change this to a different
print('Hello') #outputs Hello
print('World') #Outputs World in separate line
• For example:
print('Hello', end=‘ ')
print('World') #outputs Hello World in a single line

• But you could replace the default separating string by passing the sep keyword argument.
• Enter the following into the interactive shell:
>>> print('cats', 'dogs', 'mice') #cats dogs mice
>>> print('cats', 'dogs', 'mice', sep=',') #cats,dogs,mice

1.4.4. Local and Global Scope


 Parameters and variables that are assigned in a called function are said to exist in that function
local scope.

Department of CSE, Vemana IT Page 33 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

 Variables that are assigned outside all functions are said to exist in global scope.
 A local scope is created whenever a function is called. When the function returns, the local scope
is destroyed.
 local variables cannot be used in global scope.
 A variable that exists in a local scope is called a local variable, while a variable that exists in the
global scope is called a global variable. A variable must be one or the other; it cannot be both local
and global.

Scopes matter for several reasons:


 Code in the global scope cannot use any local variables.
 However, a local scope can access global variables.
 Code in a function’s local scope cannot use variables in any other local scope.
 You can use the same name for different variables if they are in different scopes. That is, there can
be a local variable named spam and a global variable also named spam.

Local Variables Cannot Be Used in the Global Scope


def spam():
eggs = 31337

spam()
print(eggs) #NameError: name 'eggs' is not defined

Local Scopes Cannot Use Variables in Other Local Scopes


 A new local scope is created whenever a function is called, including when a function is called
from another function.
def spam():
eggs = 99
bacon()
print(eggs) #99

def bacon():
ham = 101
eggs = 0 #0

spam() #outputs 99 which is local variable in function spam

Department of CSE, Vemana IT Page 34 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

Global Variables Can Be Read from a Local Scope


def spam():
print(eggs)

eggs = 42
spam()
print(eggs)

Local and Global Variables with the Same Name


 Avoid using local variables that have the same name as a global variable or another local variable.
 Example
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'

def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'

eggs = 'global'
bacon()
print(eggs) # prints 'global'

 There are actually three different variables in this program, but confusingly they are all named
eggs.
 The variables are as follows:
o A variable named eggs that exists in a local scope when spam() is called.
o A variable named eggs that exists in a local scope when bacon() is called.
o A variable named eggs that exists in the global scope.

Department of CSE, Vemana IT Page 35 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

1.4.5. The global Statement


 To modify a global variable from within a function, use the global statement.
 If you have a line such as global eggs at the top of a function, it tells Python, “In this function,
eggs refers to the global variable, so don’t create a local variable with this name.

The global keyword


def spam():
global eggs #global keyword helps in modifying global variable
eggs = 'spam‘ #value inside function

eggs = 'global‘ #eggs is global variable


spam()
print(eggs) #outputs updated global value i.e. spam

• There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions), then it is
always a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a local
variable.
4. But if the variable is not used in an assignment statement, it is a global variable.

 Example
def spam():
global eggs
eggs = 'spam' # this is the global

def bacon():
eggs = 'bacon' # this is a local

def ham():
print(eggs) # this is the global

Department of CSE, Vemana IT Page 36 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

eggs = 42 # this is the global


spam()
print(eggs) #outputs spam

• If you try to use a local variable in a function before you assign a value to it, as in the following
program, Python will give you an error.
def spam():
print(eggs) # ERROR!
eggs = 'spam local'

eggs = 'global'
spam() #Raises Error

1.4.6. Exception Handling


 An unwanted and unexpected event that disturbs normal flow of the program is called Exception.
 Errors in python can be handled using try and except statements
 The code that could potentially have an error is put in a try clause. The program execution moves
to the start of a following except clause if an error happens.
 Example
o Internal Error
o ZeroDivisionError
o EOFError
o ValueError
o ArithmeticException
o FileNotFoundError

 It is highly recommended to handle exceptions


 The main objective of exception handling is to provide Graceful termination / Normal
termination of the program/application
 Aims to avoid blocking of resources and not to miss execution of statements
 Exception Hierarchy

Department of CSE, Vemana IT Page 37 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

• Every Exception in python is a class


• All exception classes are child classes of BaseException either directly or indirectly
• Hence, BaseException is a root for Python exception hierarchy
• Being a programmer, most of the times, we have to concentrate / handle exception and its
classes.
• Example
def spam(divideBy):
return 42 / divideBy

print(spam(2)) #21.0
print(spam(12)) #3.5
print(spam(0)) #ZeroDivisionError: division by zero
print(spam(1)) #not executed

• Example
def spam(dividedby):
try:
return 42/dividedby
except ZeroDivisionError:
print('Error : Invalid argument.')

Department of CSE, Vemana IT Page 38 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

print(spam(2)) #21.0
print(spam(0)) #Error : Invalid argument None
print(spam(1)) #42.0

• A ZeroDivisionError happens whenever you try to divide a number by zero.


• The return statement in spam() is causing an error.
• Errors can be handled with try and except statements. The code that could potentially have an error
is put in a try clause. The program execution moves to the start of a following except clause if an
error happens.
• Example
def spam(dividedby):
try:
return 42/dividedby
except ZeroDivisionError:
print('Error : Invalid argument.')

print(spam(2)) #21.0
print(spam(0)) #Exception : Invalid argument None
print(spam(1)) #42.0

• Example
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2)) #21.0
print(spam(12)) #3.5
print(spam(0)) #Exception:Error: Invalid argument.
print(spam(1)) #not Executed
except ZeroDivisionError:
print('Error: Invalid argument.')

• The reason print(spam(1)) is never executed is because once the execution jumps to the code in
the except clause, it does not return to the try clause.
• Instead, it just continues moving down as normal.

Department of CSE, Vemana IT Page 39 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

Customized Exception Handling by using try-except


try:
print(10/0)
except ZeroDivisionError as msg:
print("Exception Type:",type(msg)
print("Exception Type:",msg. class ) TYPE OF EXCEPTION CLASS
print("Exception Class Name:",msg. class . name )
print(“Description of Exception:",msg)

Output:
Exception Type: <class 'ZeroDivisionError'>
Exception Type: <class 'ZeroDivisionError'>
Exception Class Name: ZeroDivisionError
Description of Exception: division by zero

Try with multiple except blocks


try:
....................
....................
except ZeroDivisionError:
#perform alternative airthmetic operations
except FileNotFoundError:
use local file instead of remote file
except BaseException:
which can any type of exception

 Example
try:
x=int(input("Enter the First Number: "))
y=int(input("Enter the Second Number:"))
print("The result :",x/y)

Department of CSE, Vemana IT Page 40 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

except ZeroDivisionError:
print("Cannot divide with Zero")
except ValueError:
print("Please provide int value only")

finally block
• It is not recommended to place cleanup code (resource deallocation, closing database connection
etc) inside try block because there is not guarantee for execution of every statement inside try block
• It is not recommended to place cleanup code inside except block because id there is no exception
then except block will not be executed.
• The main purpose is to maintain cleanup code
• Finally block is executed always irrespective of whether exception raised or not and exception
handled or not.
• Syntax
try:
Risky code
except:
Handling code
finally:
cleanup code

else block with try-except-finally


• Else block can be used with try-except-finally blocks
• If there is no exception in try block then only else block will be executed
• If else block is used, it is must to have except block otherwise error will raise(Syntax Error: Invalid
Syntax)
• There is no chance of executing both except and else block simultaneously.
• Syntax
try:
Risky code
except:
Handling code
Department of CSE, Vemana IT Page 41 of 43
Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions
it will be executed if exception in try block

else:
it will be executed if no exception in try block

finally:
cleanup code
it will be executed if either exception or non exception

 Example 1
try:
print("Try")
except:
print("Except")
else:
print("Else")
finally:
print("Finally")

 Example 2
try:
print("Try")
print(10/0)
except:
print("Except")
else:
print("Else")
finally:
print("Finally")

1.4.7. A Short Program: Guess the Number


import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

Department of CSE, Vemana IT Page 42 of 43


Introduction to Python Programming (22PLC15B) Module 1: Python Basics, Flow Control, Functions

# Ask the player to guess 6 times.


for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))

Department of CSE, Vemana IT Page 43 of 43

You might also like