0% found this document useful (0 votes)
6 views94 pages

Chapter-2-Basics of Programming in Python Part 1

Chapter Two introduces the basics of Python programming, highlighting its features, advantages, and application areas such as data science, web development, and machine learning. It covers Python's syntax, data types, and variable management, along with installation instructions for Python and popular IDEs. The chapter also discusses Python's rich standard library and various frameworks that enhance its functionality.

Uploaded by

yeyoyee48
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views94 pages

Chapter-2-Basics of Programming in Python Part 1

Chapter Two introduces the basics of Python programming, highlighting its features, advantages, and application areas such as data science, web development, and machine learning. It covers Python's syntax, data types, and variable management, along with installation instructions for Python and popular IDEs. The chapter also discusses Python's rich standard library and various frameworks that enhance its functionality.

Uploaded by

yeyoyee48
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 94

Chapter Two

Basics of Python Programming

1
Introduction to
Python is a widely used programming language that offers several unique

features and advantages compared to languages like Java and C++.

Python is an object-oriented programming language created by Guido

Rossum in 1989. It is ideally designed for rapid prototyping of complex


applications.

Python is one of the most popular programming languages. Although it is a

general-purpose language, it is used in various areas of applications such


as Machine Learning, Artificial Intelligence, web development, IoT, and
more.

Many large companies use the Python programming language, including NASA, Google, YouTube,

BitTorrent, etc.
2
Why learn Python?
Python provides many useful features to the programmer:-
Easy to use and Read - Python's syntax is clear and easy to read, making

it an ideal language for both beginners and experienced programmers

Dynamically Typed - The data types of variables are determined during

run-time. We do not need to specify the data type of a variable during


codes

High-level - High-level language means human readable code

Garbage Collected - Memory allocation and de-allocation are

automatically managed. Programmers do not specifically need to


manage the memory
3
Why learn Python?
Cross-platform Compatibility - Python can be easily installed on
Windows, macOS, and various Linux distributions.

Rich Standard Library - Python comes with several standard libraries


that provide ready-to-use modules and functions.

Open Source - Python is an open-source, cost-free programming


language.

GUI Programming Support: Python provides several GUI frameworks, such


as Tkinter to allowing developers to create desktop applications easily.

Wide Range of Libraries and Frameworks: Python has a vast collection of


libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can
be used to solve a wide range of problems. 4
Application area of python
Data Science: Data Science is a vast field, and Python is an important
language for this field because of its simplicity, ease of use, and
availability of powerful data analysis and visualization libraries like
NumPy, Pandas, and Matplotlib.

Desktop Applications: Tkinter are useful libraries that can be used in


GUI - Graphical User Interface-based Desktop Applications. There
are better languages for this field, but it can be used with other
languages for making Applications.

Mobile Applications: While Python is not commonly used for creating


mobile applications, it can still be combined with frameworks like
Kivy or BeeWare to create cross-platform mobile applications.
5
Application area of python
Web Applications: Python is commonly used in web development
on the backend with frameworks like Django and Flask and on
the front end with tools like JavaScript HTML and CSS.

Machine Learning: Python is widely used for machine learning


due to its simplicity, ease of use, and availability of powerful
machine learning libraries
Computer Vision or Image Processing Applications: Python can
be used for computer vision and image processing applications
through powerful libraries such as OpenCV and Scikit-image.
Gaming: Python has libraries like Pygame, which provide a
platform for developing games using Python.
DevOps: Python is widely used in DevOps for automation and
scripting of infrastructure management, configuration
management, and deployment processes
6
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used
in various fields such
Web development (Server-side) - Django Flask, Pyramid,
CherryPy

GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.

Machine Learning - TensorFlow, PyTorch, Scikit-learn,


Matplotlib, Scipy, etc.

SQLAlchemy: a library for working with SQL databases

NLTK: a library for natural language processing

Pygame: a library for game development


7
Advantages of Python language
Cross-Platform Compatibility

Strong Community Support

Integration and Extensibility

Scalability and Performance

Versatility and Flexibility

8
How to install Python
Visit the official website of Python https://www.python.org/downloads/
and choose
Once your version.
the download is completed, run the .exe file to install Python. Now click on Install Now.

9
How to install Python IDE
1. PyCharm is a cross-platform editor developed by
JetBrains. Pycharm provides all the tools you need for
productive Python development.
visit the website https://www.jetbrains.com/pycharm/download/ and Click the
“DOWNLOAD” link under the Community Section.

10
How to install Python IDE
2. Anaconda is a free and open source distribution of
the Python and R programming languages for large-
scale data processing, predictive analytics, and
scientific computing.
An anaconda is an open-source free path that allows users to
write programming in Python language. The anaconda is termed
by navigator as it includes various applications of Python such as
Spyder, Vs code, Jupiter notebook, PyCharm
How to install anaconda: Go to
https://www.anaconda.com/download/ and download Anaconda

To check anaconda is installed


Go to anaconda command prompt then
write the following
11
How to install Python IDE
3. Visual Studio Code is a free open source text editor by Microsoft. VS Code
is available for Windows, Linux, and macOS
How to install Visual Studio Code: Go to https://code.visualstudio.com and download
visual studio code

12
Basic elements of Python:
Python Basic Syntax:-
There is no use of curly braces or semicolons in Python
programming language. It is an English-like language.
 But Python uses indentation to define a block of code.
Indentation is nothing but adding whitespace before
the statement.
Python is a case-sensitive language, which means that uppercase and
lowercase letters are treated differently.
In Python, comments can be added using the '#' symbol. Any text written after
the '#' symbol is considered a comment.
Following triple-quoted string is also ignored by Python interpreter and can
be used as a multiline comments: example ''' This is a
13
Basic elements of Python:
Python print() Function
Python print() function is used to display output to the console or terminal.
It allows us to display text, variables and other data in a human readable
format.
Output

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string.

14
Basic elements of Python:
More about Data output
• If you do not want the print function to start a new line of output when it finishes
displaying its output, you can pass the special argument end=' ' to the function
example. print('Python',end=' ') Output:
print('Programming')
• Specifying an Item Separator
When multiple arguments are passed to the print function, they are automatically
separated by a space when they are displayed on the screen
example: print('Python','Programming’) Output:

• If you do not want a space printed between the items, you can pass the argument
sep='' to the print function.
Example :print('Python','Programming',sep='') Output:

• You can also use this special argument to specify a character other than the space to
separate multiple items
Example: print('Python','Programming',sep='#####’) Output: 15
Basic elements of Python:
Formatting floating point Numbers
• Used for floating-point numbers to displayed the amount of rounded to some decimal
places
• It is possible by calling the built-in format function
• you pass two arguments to the function: a numeric value and a format specifier.
• numeric value is the number that we want to format
• The format specifier is a string that contains special characters specifying how the
numeric value should be formatted
Example:
a=200 Output:
b=13
print(a/b)
print(format(a/b,'.3f’))
# Inserting Comma Separators
print(format(5234.47,',.1f'))

16
Basic elements of Python:
Formatting a Floating-Point Number as a Percentage
• Instead of using f as the type designator, you can use the % symbol to format a
floating point number as a percentage
• The % symbol causes the number to be multiplied by 100 and displayed with a %
sign following it
Example: Output:

print(format(0.256,'%'))

print(format(0.256,'.0%'))

print(format(0.2567,'.1%'))

print(format(12.25687,',.2%'))
17
Basic elements of Python:
Formatting Integers
• You can also use the format function to format integers. There are two differences
to keep in mind when writing a format specifier that will be used to format an
integer:
• You use d as the type designator.
• You cannot specify precision.
• Example: Output:
x=12345
print(format(x,',d'))

18
Python Variables:
Python Variables
Python variables are the reserved memory locations used to
store values with in a Python Program.
When you create a variable you reserve some space in the
memory
Based on the data type of a variable, Python interpreter
allocates memory and decides what can be stored in the
reserved memory

19
Python Variables:
A name associated with an object m
Assignment used for binding 64
m = 64
students
c = ‘students’;
f = 3.1416;
c
3.1416
 Variables can change their bindings
f
f = 2.7183;

2.7183

20
Python Variables:
Python variables do not need explicit declaration to reserve
memory space or you can say to create a variable.
A Python variable is created automatically when you assign a
value to it. The equal sign (=) is used to assign values to
variables.
Example output

21
Deleting Python Variables:
You can delete the reference to a number object by using the del statement.
The syntax of the del statement is
del var name
Example

You can get the data type of a Python variable using the python built-in
function type() as follows. x = "Zara“ Output
y = 10
Example: Printing Variables Type
z = 10.10
print(type(x))
print(type(y))
22
Python Variables - Multiple Assignment:
 Python allows to initialize more than one variables in a single
statement.
In example A , three variables have same value.
Example A a=b=c=10 Outputa,b,c = 10,20,30
Output
print (a,b,c) print (a,b,c)

Rules for Python Variables:


A variable name must start with a letter or the underscore character
A variable name cannot start with a number or any special character like $, (, * % etc.)
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Python variable names are case-sensitive which means Name and NAME are two different
variables in Python.
 23
Python Variables - Multiple Assignment:
Casting
If you want to specify the data type of a variable, this can be done with
casting.
Example:
x = str(5) # x will be ‘5'
y = int(5) # y will be 5
z = float(5) # z will be 5.0

24
Python Basics - Whitespace:
Whitespace is meaningful in Python: especially indentation and placement of newlines
•Use a newline to end a line of code
Use \ or + when must go to next line prematurely
•Example:
print('Line one, \ print('Line one, '\ print('Line one,'+
Line two, \ 'Line two, '\ 'Line two,'+
line Three.') 'line Three.') 'line Three.')

Output:

•No braces {} to mark blocks of code, use consistent indentation instead


•Colons start of a new block in many constructs, e.g. function definitions, then clauses

25
Constants in Python
Python constant
Python doesn't have any formally defined constants, However you can indicate
a variable to be treated as a constant by using all-caps names with underscores
For example, the name PI_VALUE indicates that you don't want the variable
redefined or changed in any way.
In Python, constants are usually declared and assigned in a module (a new file
containing variables, functions, etc which is imported to the main file).
Create a constant.py: Create a main.py:
# declare constants # import constant file we created above
PI = 3.14 import constant
GRAVITY = 9.8 print(constant.PI)# prints 3.14
print(constant.GRAVITY # prints 9.8

26
Data Types in Python:
A data type represents a kind of value and determines what operations can be
done on it. It defines what type of data we are going to store in a variable.

27
Python Numeric Data Type
- Python supports different numerical types and each of them have built-in classes in Python
library like int, bool, float and complex

- We can use the type() function to know which class a variable or a value belongs to.

output

28
Python Sequence Data Type
Sequence is a collection data type. It is an ordered collection of items. Items in the sequence
have a positional index starting with 0. It is conceptually similar to an array in C++.

1. Python String Data Type


Python string is a sequence of one or more Unicode characters, enclosed in single, double
or triple quotation marks.

output

29
Python Sequence Data Type
Strings in Python are “immutable” which means they can not be changed after
they are created(you always produce a new string object of the same type, rather
than mutating an existing string)
 Some other immutable data types are integers, float, boolean, etc

Example: output
name = "Computing"
name[0] = 'T'
print(name)

30
Python Sequence Data Type
A string is a non-numeric data type. Obviously, we cannot perform arithmetic
operations on it. However, operations such as slicing and concatenation can be
done.
Python's str class defines a number of useful methods for string processing.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and working their way from
-1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator in Python.
31
Python Sequence Data Type
Example of String Data Type

Output

32
Python Sequence Data Type
2. Python List Data Type
A Python list contains items separated by commas and enclosed within square brackets ([]).

Python lists are similar to arrays in C++. One difference between them is that:

They allow us to store multiple items in a single variable

 List declaration :placing elements inside square brackets [], separated by commas.

Example Output

33
Python Sequence Data Type
Python List Data Type
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus
(+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Output

34
Python Sequence Data Type
3. Python Tuple Data Type
A Python tuple consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses (...)
A tuple is a collection of data similar to a python list The only difference is that we cannot
modify a tuple once it has been created
A tuple is also a sequence, hence each item in the tuple has an index referring to its position
in the collection. The index starts from 0.
 Tuple declaration :placing elements inside parentheses(), separated by commas

Example Output

35
Data Types in Python:
Python Tuples Data Type :- The main differences between lists and tuples are:

Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed that means
lists are mutable,

while tuples are enclosed in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can

be thought of as read-only lists Output

Output

36
Python Boolean Data Types
Python Boolean type is one of built-in data types which represents one of the
two values either True or False.
Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression.

Output

37
Python User Input
Python provides us with two built-in functions to read the input from the
keyboard. The input () Function and The raw_input () Function
When the interpreter encounters input() function, it waits for the user to enter
data from the standard input stream (keyboard)
 Output

38
Taking Numeric Input in Python
Python always read the user input as a string.

If there is an input type int or float numbers and used for
some operation with out casting to respective datatype error
will be occurred
To overcome such problem, we shall use type casting:
 int():It converts a string object to an integer.
float(): It converts a string object to an floating point
Complex(): It converts a string object to complex number
Example:
 Write a Python program that inputs two numbers and display their values for
the user
39
Taking Numeric Input in Python
Let us write a Python code that accepts integer value of width and height of a
rectangle from the user and computes the area.)

Sample output

40
Taking Numeric Input in Python
Python String split() Method

• Split a string into a list where each word is a list item


Example:
msg='Good work, Practice makes perfect!!!'
print(msg.split())
print(msg.split(','))
Output:

41
Methods to Take multiple inputs from user and format output

Python user can take multiple values or inputs in one line.

Methods to Take multiple inputs from user


• Using split() method: It breaks the given input by the specified separator. If a separator
is not provided then any white space is a separator.
• Generally, users use a split() method to split a Python string but one can use it in taking
multiple inputs.
Example: output:

• Using map() with split():


• Using List comprehension :

42
Methods to Take multiple inputs from user
Example: multipleinput.py

Sample output:

43
Python Escape Characters

Escape Characters: used to insert characters that are in a string.


An escape character is a backslash \ followed by the illegal character you want to
insert.
Example:

output:

44
Operators in Python
The operator is a symbol that performs a specific operation
between two operands. Python also has some operators

• Arithmetic + - * // / % **

• Comparison == != > < >= <=

• Assignment = += -= *= //= /= %= **=

• Logical and or not


• Bitwise & | ^ ~ >> <<
• Membership in not in
• Identity is is not
45
Operators in Python
1. Arithmetic operators

Arithmetic operators used between two operands to perform mathematical operations. There
are many arithmetic operators. It includes the exponent (**) operator as well as the +
(addition), - (subtraction), * (multiplication), / (divide), % (reminder), and // (floor division)
operators.

** (Exponent):- As it calculates the first operand's power to the second operand, it is an
NB: Modulo operator computed as follow:
exponent operator. A%B=A-(A//B)*B

// (Floor division):-It provides the quotient's floor value, by dividing the two operands.

Result is a whole integer, But the type need not be int

rounded towards minus infinity 46


Operators in Python

Operator Operation Example


+ Addition 4 +5 = 9
- Subtraction 7 -3 = 4
* Multiplication 5 * 3 =15
/ Division 9 / 2 = 4.5
// Floor Division 9 // 2 = 4
% Modulo 7%2=1
** Power 2** 3 = 8
47
Operators in Python
2. Comparison operator
Comparison operators compare two values/variables and return a Boolean result: True or False.
The example of comparison operators are ==, !=, <=, >=, >, <.
Operator Meaning Example

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True


48
Operators in Python
3. Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left
operand. There are some examples of assignment operators like =, +=, -=, *=,
%=, **=, Operator Name Example

= Assignment Operator a=7

+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

Multiplication
*= a *= 4 # a = a * 4
Assignment

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10


49
Operators in Python
4. Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>).
 The result of AND is 1 only if both bits are 1.
 The result of OR is 1 if any of the two bits is 1.
 The result of XOR is 1 if the two bits are different.

 shift (<<) takes two numbers, left shifts the bits of the first

operand, the second operand decides the number of places to shift. Output

 Right shift (>>) takes two numbers, right shifts the

bits of the first operand, the second operand decides the number of places to shift.
50
 Bitwise NOT ( ~ ) is the only unary bitwise operator. Since take only one operand. X=-X-1
Operators in Python
5. Logical Operators
Logical operators are used to check whether an expression is True or False. They
are used in decision-making.
Operator Example Description

Logical AND:
Example: and a and b True only if both the
operands are True

Logical OR:
or a or b True if at least one of
the operands is True

Logical NOT:
not not a True if the operand is
Output: False and vice-versa.

51
Operators in Python
6. Membership Operators
In Python, in and not in are the membership operators.
The membership of a value inside a Python data structure can be verified using Python
membership operators.
They are used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
 The result is true if the value is in the data structure; otherwise, it returns false.
In a dictionary, we can only test for the presence of a key, not the value.

52
Operators in Python
6. Membership Operators
Example:

53
In

Operators in Python
7. Identity Operators
In Python, is and is not are used to check if two values are located at the same memory
location.
It's important to note that having two variables with equal values doesn't necessarily mean
they are identical.
Operator Meaning Example

True if the operands are identical (refer to the


is x is y
same object)

True if the operands are not identical (do not


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

54
In

Operators in Python
Example:

55
Precedence and Associativity of Operators in
Python
*,, /, // Multiplication, matrix, division, Left to
1
,% floor division, remainder right
Left to
2 +,- Addition and subtraction
right
<<, > Left to
3 Shifts
> right
Left to
4 & Bitwise AND
right
Left to
5 ^ Example:- 100 +Bitwise XOR
200 / 10 - 3 * 10 right
56
Debugging and Errors in
Python
Debugging means the complete control over the program execution. Developers use
debugging to overcome program from any bad issues.

debugging is a healthier process for the program and keeps the diseases bugs far away.

Python also allows developers to debug the programs using pdb module that comes with
standard Python by default.

We just need to import pdb module in the Python script and use pdb.set_trace(). Using pdb
module, we can set breakpoints in the program to check the current status

57
Errors in Python
 Errors are the mistakes or faults performed by the user which results in abnormal working
of the program.

However, we cannot detect programming errors before the compilation of programs. The
process of removing errors from a program is called Debugging

Errors in Python can be broadly classified into three categories:- Syntax Errors, Runtime
Errors, and Logical Errors.

1. Syntax errors :- occurs when we do not use properly defined syntax
 Using Python keywords as variable names.
 Incorrect arguments/parameter
Example:
 Mixing single and double quotes improperly in a string
 Indentation
 Forgetting a colon at the end of an if statement
 Mismatched parentheses, like 58
Errors in Python
2. Runtime Errors
Error does not appear until after the program has started running
These errors are also called exceptions because they usually indicate that something
exceptional (and bad) has happened in program execution.
Example:
Division by zero
Performing an operation on incompatible types
Accessing a list element, dictionary value or object attribute which doesn’t exist
Trying to access a file which doesn’t exist

59
Errors in Python
3. Logical/Semantic Errors
If there is a semantic error in your program, it will run successfully in the sense that the
computer will not generate any error messages, but it will not do the right thing.

The program runs without issues, but it doesn't achieve the intended results.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the
program (its semantics) is wrong.

Identifying semantic errors can be tricky because it requires you to work backward by looking at the
output of the program and trying to figure out what it is doing.
x,y=10,5
Example: display the sum of two numbers(10,5) sum=x*y
print(sum)

60
Control Statements, Conditional,
Looping
Introduction:
and
A control structure is a logical design that controls the order in which a set of statements execute
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program
accordingly x=10
if x>0:
print("x is positive")

 The Boolean expression after if is called the condition. If it is true, then the indented statement gets executed. If not, nothing
happens

 if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called
compound statements.

 There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful
to have a body with no statements. In that case, you can use the pass statement, which does nothing.

61
Indentation in python
Indentation in Python

For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block.

If two statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of code.

All the statements of one block are intended at the same level indentation.

62
Indentation
Indentation is important in Python
grouping of statement (block of statements)
no explicit braces, e.g. { }, to group statements

x,y = 6,10 Run


x the program
y

if x < y: 6 10
print (x)
else:
print (y) ed Output
i p p
sk the min’)
print (‘is 6
63
Conditional Statements
 Conditional Statement in Python perform different computations or actions depending on
whether a specific Boolean expression evaluates to true or false
Decision making is the most important aspect of almost all the programming languages. As
the name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions.
Statement Description

if The if statement is used to test a specific condition. If the condition is true, a block of code (if-
block) will be executed.

if – else The if-else statement is similar to if statement except the fact that, it also provides the block of
the code for the false case of the condition to be checked.

Nested if Nested if statements enable us to use if ? else statement inside an outer if statement.

elif The elif statement enables us to check multiple conditions and execute the specific

64
The If statement(no
else!)
• The if statement is used to test a particular condition and if the condition is
true, it executes a block of code known as if-block
• General form of the if statement
e
tru

fals
if boolean-expr :

e
Statement 1(S1) S1
Statement 2(S2)
S2
• Execution of if statement
• First the expression is evaluated.
• If it evaluates to a true value, then S1 is executed and then control moves to the S2.
• If expression evaluates to false, then control moves to the S2 directly.
NB: Python interprets non-zero values as True. None and 0 are interpreted as False.
65
The If statement(no
else!)
• Example:
NB:
If you have only one statement to
execute, you can put it on the same line
as the if statement.
E.g.
x=5
if x==5:print('x is five')

• Output:

66
The If-else statement
• The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
• General form of the if-else statement

if boolean-expr : rt u
e

fa
ls
Statement1(S1)

e
S1
else: S2

Statement2(S2)
Statement3(S3) S3
• Execution of if-else statement
• First the expression is evaluated.
• If it evaluates to a true value, then S1 is executed and then control moves to S3.
• If expression evaluates to false, then S2 is executed and then control moves to S3.
• S1/S2 can be blocks of statements!

67
The If-else statement
• Example:

NB:
If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line.
E.g.
x,y=5,6
print('x is greater')if x>y else print('y is greater')

• Output:

68
Nested if, if-else
statement
• We can have a if...else statement inside another if....else statement
• Any number of these statements can be nested inside one another.
• Indentation is the only way to figure out the level of nesting.
• Example : input a number to check if the number is positive or negative or zero
and display appropriate message

Output:
69
The elif statement
• A special kind of nesting is the chain of if-else-if-else-… statements
• The elif is short for else if. It allows us to check for multiple expressions
• If the condition for if is False, it checks the condition of the next elif block and so on.
• 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.
if condition1: e
rt u

fa
ls
s1

e
elif condition2: S1
s2 rt u
e

fa
ls
elif condition3:

e
s3 S2
e

fa
elif … tru

els
else Slast
S3
last-block-of-statement(Slast) 70
The elif statement
Example: You can also have multiple else statements on
the same line:

Output:

Output: 71
Python Match Case Statement
• Match Case is the Switch Case of Python which was introduced in Python 3.10
• Here we have to first pass a parameter and then try to check with which case the parameter is
getting satisfied. If we find a match we will execute some code and if there is no match at all,
a default action will take place.

_
• The “ ” is the wildcard character that runs when all the cases fail to match the parameter
value
• Syntax: Example:

72
Python Match Case Statement
Match Case Statement with OR Operator
• When there are more than one case that results in same output we can
use match case statement in python.
• Example:

73
Python Match Case Statement
Match Case Statement with Python If Condition
• We can use the Python If condition along with match case statement when instead
of matching the exact value, we use a condition.
• Based on the condition, if the value is True and matches the case pattern, the code
block is executed.
• Example:

74
Python Match Case Statement
Match Case with the Sequence Pattern
• Python match case statements are commonly used to match sequence patterns such as lists and strings.
• It is quite easy and can use positional arguments for checking the patterns.
we are using a python string to check if a we are using a python list for pattern matching. We are matching
character is present in the string or not using the first element of the lost and also used positional arguments to
match the rest of the list
match case
strmatch = "Python Programming" mystr=['a']
match (strmatch[7]): mystr1=['a','b','c','d']
case "p": mystr2=['b','a','c','d'] Output for mystr: a
print("Case 1 matches") match mystr:
case "P": case ["a"]:
print("Case 2 matches") print("a") If we change the parameter of match case
case _: case ["a", *b]: to mystr1 or mystr2
print(f"a and {b}")
print("Character not in the string") case [*a, "d"]: Output for mystr1:a and ['b', 'c', 'd']
print(f"{a} and d")
Output for mystr2:['b', 'a', 'c'] and d
case _:
print("No data")

Output: Case 2 matches 75


Python Match Case Statement
Match Case Statement with Python Dictionary
• Python match case statements can handle dictionary as well. It can match a single key or multiple
keys. The keys and values must reside in the dictionary, if there is any misplaced value or any key
which does not exist and does not match the actual dictionary and value, that case will be
discarded.
• it will match the dictionary keys with different cases provided.
• Example: output:

•:
If we change the parameter of match case
to dictionary1
• output:

76
Looping Statements
In general, statements are executed sequentially

There may be a situation when you need to execute a block of code several number of times.

Loop statements allow us to execute a statement or group of statements multiple time

Python programming language provides the following types of loops to handle looping
requirements.

77
while loop Statements
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.

We generally use while loop when we don't know the number of times to iterate beforehand.

The body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

while (expression):
1. Evaluate expression S1 FALSE
expression
2. If TRUE then
S2
a) execute statement1 TRUE
b) goto step 1.
S1 S2
3. If FALSE then execute statement2. 78
while loop Statements
Example:
1. write a Program that display the sum of the following natural numbers series
sum = 1+2+3+...+n , take n as input from the user
2. Write a program that accepts a positive number from the keyboard and determine whether
the number is prime or not?
 output:

79
Python while loop
using List
Len() function
It's important to note that the indexing of elements in a list starts from 0, so the length of a
list is always greater than or equal to 0.
The len() function is efficient and commonly used for iterating over lists or performing
operations based on the size of a list
Example:- Write a python program to find the sum of the given list using while loop?
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
sum = 0
i=0
while i < len(numbers):
sum =sum+ numbers[i]
i += 1
print("Sum of each element:", sum)
80
Python for loop
Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and
strings.
Iterating over a sequence is called traversal.
syntax
for loops are used when a section of code needs tosyntax
be repeated a certain number of times.
for value in range for value in sequen
(): ce:
statement statement
Passing the whitespace to the end parameter (end=' ') indicates that the end character has to
be identified by whitespace and not a newline.
 Using Iterating over a range: The range () function:
We can also define the start, stop and step size as range (start, stop, step_size).
• range(start, end) is equivalent to range(start, end, 1)
• range(end) is equivalent to range(0, end)
• step_size defaults to 1, start to 0 and stop is end of object if not provided 81
Python for loop
Example:- write a python program to print a number from print 1 to 10 even using for loop.

for i in
for i in range(11):
range(1,11):
print(i,end="
print(i,end="
")
")

for i in for i in
range(1,11,2): range(2,11,2):
print(i) print(i)

82
for loop using list
The rang() function does not store all the values in memory; it would be inefficient. So, it
remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
Example:
print(range(10))
print(list(range(10)))
print (list (range (2, 8)))
print (list (range (2, 20, 3)))
Output:
range (0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

83
For loop using list
Write a python program to find the sum of each element of the list using for
loop? numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
syntax
for value in sequenc
e:
statement
Since instead of range just replace list (numbers) Output

Solution:-

84
For loop for Iterating over a Sequence
Iterating over a sequence
We can use the len() function inside range Let's change the example into a more
function to access the list sequence elements: Pythonic form:

What if you wanted to print the position of current iteration


of items as well though? Use enumerate ->it's much more
readable (and more efficient) than the range(len(...))

You can call enumerate with a start parameter, like enumerate(iterable, start), and it
will start from start, rather than 0.
85
For loop for Iterating over a Sequence
Iterating over multiple sequences

Use to iterate over two sequences of the same


length, in order to work on their respective
elements in pairs

a ke
m
to
ry
e t 's t
c . L
oni
Pyth
not
t and
i c ien
n e ff e:
t h i
e r at
bo um
s
d e i ng e n
i s co usi
Th e t t e r
b
86
For loop for Iterating over a Sequence
Iterating over multiple sequences

87
Control Statements
 Control statements used to control the order of execution of the program
based on the values and logic
 Python supports the following control statements

No. Control Statement & Description

Break statement:- Terminates the loop statement and transfers execution to the
1
statement immediately following the loop.

Continue statement :- Causes the loop to skip the remainder of its body and
2
immediately retest its condition prior to reiterating.

Pass statement :- The pass statement in Python is used when a statement is


3
required syntactically but you do not want any command or code to execute.
88
Python break
statement
Break is commonly used to break the loop for a given condition.
It is useful when we want to terminate the loop as soon as the condition is fulfilled instead of
doing the remaining iterations Syntax Loop statements
Write the output of the following program?? break;
my_str = "python"
for i in range(1,10,2): for char in my_str:
while i==8: if char == 'o':
break break
print(i) print(char)
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
for i in range(1,10,2): for char in numbers:
while i==7: if char == 1:
print(i) break
break print(char)
89
Python continue
statement
 Python continue keyword is used to skip the remaining statements of the current loop and
go to the next iteration
Write the output of the following program?? Loop statements
continue;
for i in range(1,10,2): my_str = "python"
while i==8: for char in my_str:
continue if char == 'o':
print(i) continue
print(char)

infinitely displaying 7 numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]


for i in range(1,10,2): for char in numbers:
while i==7: if char == 1:
print(i) continue
continue print(char)
90
Python pass
statement
We can use the pass statement as a placeholder when unsure of the code to
provide. Therefore, the pass only needs to be placed on that line
Loop statements
Syntax: pass;
Write the output of the following program??

sequence = {"Python", "program",


sequence =
"Statement",
[4,7,21,7,90,54]
22,10,"Placeholder“,40}
for value in sequence:
for value in sequence:
if value == 7:
if value == "program":
pass
pass
else:
else:
print(value)
print( value)

91
Python nested loop
In python nested loop is a loop inside another loop. Syntax
Outer loop
inner loop
statement of inner loop
statement of outer loop

92
Python nested loop
Example:- Write the output of the following python program
for i in range(1,6): for i in range(1,6):
for j in range(1,6): for j in range(1,7-
print("*",end=" i):
") print(j, end=" ")
print() print()
for i in range (1,6):
for i in range(1,6): for j in
for j in range(1,6): range(1,i+1):
print(i,end=" ") print(j,end="
print() ")
print(" ")
for i in range(1,6):
for j in range(1,6):
print(j,end=" ")
print()
93
Part 1 The End

94

You might also like