0% found this document useful (0 votes)
17 views38 pages

Python Basics

The document provides an overview of Python programming basics, including definitions of programming, software types, and programming languages. It covers machine language, assembly language, and high-level languages, along with the history of Python and its program types. Additionally, it discusses Python basics such as identifiers, keywords, statements, expressions, variables, and various types of operators.

Uploaded by

ishwarraj126
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views38 pages

Python Basics

The document provides an overview of Python programming basics, including definitions of programming, software types, and programming languages. It covers machine language, assembly language, and high-level languages, along with the history of Python and its program types. Additionally, it discusses Python basics such as identifiers, keywords, statements, expressions, variables, and various types of operators.

Uploaded by

ishwarraj126
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3/2/2025

Python Programming - Basics

For internal use only

Introduction to programming
• A program is a set of instructions instructing a computer to do specific tasks

• Software is a generic term used to describe computer programs - other terms include
scripts, applications, programs and a set of instructions

• System software includes device drivers, operating systems, compilers and utilities helping
the computer to operate more efficiently - serves as a base for application software -
responsible for managing hardware components

• Application software such as office suites, gaming applications, database systems and
educational software are intended to perform certain tasks - can be a single program or a
collection of small programs

• Programming software is a set of tools such as interpreters, compilers, linkers, debuggers


and text editors that aid developers in writing programs

• A programming language (FORTRAN, C, C++, Python, etc.) is a computer language


engineered to communicate instructions to a machine (computer)
2

1
3/2/2025

Programming languages
• Programs are created through programming languages to control the behavior and output
of a machine through accurate algorithms

Machine language

• Machine language is a low-level computer language that is designed to be directly


understandable by a computer - it is the language into which all programs must be
converted before they can be run

• All instructions, memory locations, numbers and characters are represented using 0s and 1s

• A typical piece of machine language might look like: 00000100 10000000

• Advantages: it can run and execute very fast as the code will be directly executed by a
computer and the programs efficiently utilize memory

• Disadvantages: (a) almost impossible for human use because it consists entirely of 0s and
1s; (b) hard to maintain and debug; (c) no mathematical functions available; and (d) memory
locations are manipulated directly (requires keeping track of every memory location)
3

Programming languages
Assembly language

• Assembly language is a human-readable notation for machine language - a better


alternative to programmers who want to work at machine language level

• Instructions are represented with alphanumeric symbols (aka mnemonics) - easier to


remember and work and lesser chances of making errors

• For example, the code to perform addition and subtraction is

ADD 3, 5, result

SUB 1, 2, result

• An assembler is needed to convert these programs into machine language

• Disadvantages: there are no symbolic names for memory locations - difficult to read -
machine-dependent (makes it difficult for portability)

2
3/2/2025

Programming languages
High-level language

• Programs are written in a form that is close to human language (enables the programmers
to just focus on the problem being solved)

• High-level languages are platform independent (programs written in a high-level language


can be executed on different types of machines)

• A program written in the high-level language is called source program or source code and
is any collection of human-readable computer instructions

• Advantages: easier to modify, faster to write code and debug and portable

• A compiler or interpreter is needed to translate the program (source code) into machine
language (the only language the computer understands)

• A compiler is a system software program that transforms the source code written in a high-
level programming language into machine language

Programming languages
• Compilers translate source code all at once and the computer then executes the machine
language that the compiler produced - generated machine language can be later executed
many times against different data each time

• Programming languages like C, C++, C# and Java use compilers

• A native-code compiler is intended to produce machine language to run on the same


platform that the compiler itself runs - a cross compiler produces machine language that is
intended to run on a different platform than it runs on

• Interpreter: an interpreter reads source code one statement at a time, translates the
statement into machine language, executes the machine language statement, and then
continues with the next statement

• Compiled code runs faster than an interpreted code - overall time is usually larger in
compiling and running than interpreting and running a program

• Programming languages like Python, Ruby and Perl use interpreters


6

3
3/2/2025

History of Python
• Python was conceived in the late 1980s, and its implementation was started in December
1989 by Guido van Rossum at the Centrum Wiskunde & Informatica (abbr. CWI; English:
National Research Institute for Mathematics and Computer Science) in the
Netherlands

• Python was named after the BBC TV Show Monty Python's Flying Circus

Guido van Rossum Python Logo

Python program types


Source: ChatGPT

Standalone Python Program

Non-standalone Python Program


8

4
3/2/2025

Python program types


Source: ChatGPT

Python basics

Identifiers

Keywords

Statements /
Expressions Arithmetic

Variables Assignment
Numbers
Operators Comparison
Boolean
Data types Logical
Strings
Indentation Bitwise
None
Comments Single-line
Input
Input / Output Multi-line
Output
Type-casting

Elements of Python
10

5
3/2/2025

Python basics - identifiers


• An identifier is a name given to a variable, function, class or module

• Identifiers may be formed as a combination of letters in lowercase (a to z) or uppercase (A to


Z) or digits (0 to 9) or an underscore (_) - the first letter can be an alphabet or underscore
only

• Keywords (system reserved words) cannot be used as identifiers

• Spaces and special symbols like !, @, #, $, % etc. can neither be used as an identifier nor
as the part of an identifier

• Identifier can be of any length

11

Python basics - keywords


• Keywords are reserved words that have predefined meaning and cannot be used as
identifiers for variables, functions, constants or with any identifier name

and as assert break class

continue def del elif else

except finally for from global

if import in is lambda

nonlocal not or pass raise

return try while with yield

False True None

Keywords

12

6
3/2/2025

Python basics - statements and expressions


• A statement is an instruction that the Python interpreter can execute - Python program
consists of a sequence of statements

• Statements are everything that can make up a line (or several lines) of Python code - for
example, z = 1 is an assignment statement

• An expression is the arrangement of values and operators which are evaluated to make a
new value - expressions are statements as well

• A value is the representation of some entity like a letter or a number that can be manipulated
by a program

• A single value >>> 20 or a single variable >>> z or a combination of variable, operator and
value >>> z + 20 are all examples of expressions

13

Python basics - statements and expressions


• An expression, when used in interactive mode, is evaluated by the interpreter and result is
displayed instantly - for example,

>>> 8 + 2

10

• Same expression when used in Python program does not show any output altogether - one
need to explicitly print the result

14

7
3/2/2025

Python basics - variables


• Variable is a named placeholder to hold any type of data which the program can use to
assign and modify during execution

• No need to declare a variable explicitly by specifying whether the variable is an integer or


a float or any other type - to define a new variable, we simply assign a value to a name

Guidelines for naming the variables

• Variable names can consist of any number of letters, underscores and digits

• Variable should not start with a number

• Python keywords are not allowed as variable names

• Variable names are case-sensitive - e.g., computer and Computer are different variables

• Python variables use lowercase letters with words separated by underscores as necessary
to improve readability, like this whats_up and how_are_you (not strictly enforced, but
considered a best practice)

15

Python basics - variables


• Avoid naming a variable where the first character is an underscore (though legal in Python, it
can limit the interoperability of code with applications built using other programming
languages)

• Ensure variable names are descriptive and clear enough (this allows other programmers to
have an idea about what the variable is representing)

Assigning values to variables

• The general format for assigning values to variables is as follows:

variable_name = expression

• Examples:

number = 100

values = 1000.0

name = “Python”

• Single value can be assigned to several variables simultaneously (example: a = b = c = 7)


16

8
3/2/2025

Python basics - operators


• An operator manipulates the data values called operands

• Python language supports a wide range of operators, viz. arithmetic operators,


assignment operators, comparison operators, logical operators and bitwise operators

Arithmetic operators

• Arithmetic operators are used to execute arithmetic operations such as addition,


subtraction, division, multiplication, etc.

17

Python basics - operators


The value of p is 2 and q is 3
Name of
Operator Description Example
operator
+ Addition Adds two operands, producing their sum p+q=5

- Subtraction Subtracts two operands, produce their difference p - q = -1

* Multiplication Produces the product of two operands p*q=6


Produces the quotient of its operands where the left
/ Division operand is the dividend and right operand is the q / p = 1.5
divisor
Divides the left hand operand by the right hand
% Modulus q%p=1
operand and returns the remainder
Performs the exponential (power) calculation on the
** Exponent p ** q = 8
operands
9 // 2 = 4
// Floor Division Returns the integral part of the quotient
9.0 // 2.0 = 4.0

Arithmetic operators

18

9
3/2/2025

Python basics - operators


Assignment operators

• Assignment operators are used for assigning the values generated after evaluating the right
operand to the left operand - assignment operation always works from right to left

• An assignment operator is either a simple assignment operator or compound


assignment operator

• Simple assignment is done with the equal sign (=) and simply assigns the value of its right
operand to the variable on the left

• Compound assignment operators support shorthand notation for avoiding the repetition of
the left-side variable on the right side - they combine = operator with another operator with =
being placed at the end of original operator

19

Python basics - operators


Name of
Operator Description Example
operator
z = p + q assigns
Assigns values from right side operand to left side
= Assignment the value of p + q to
operand
z
Addition Adds the value of right operand to the left operand z += p is equivalent
+=
Assignment and assigns the result to left operand to z = z + p
Subtraction Subtracts the value of right operand from the left z -= p is equivalent
-=
Assignment operand and assigns the result to left operand to z = z - p
Multiplication Multiplies the value of right operand with the left z *= p is equivalent
*=
Assignment operand and assigns the result to left operand to z = z * p
Division Divides the value of right operand with the left z /= p is equivalent
/=
Assignment operand and assigns the result to left operand to z = z / p
Evaluates the result of raising the first operand to
Exponentiation z **= p is equivalent
**= the power of the second operand and assigns to
Assignment to z = z ** p
left operand
Produces the integral part of the quotient of its
Floor Division z //= p is equivalent
//= operands where the left operand is the dividend
Assignment to z = z // p
and the right operand is the divisor
Remainder Computes the remainder after division and z %= p is equivalent
%=
Assignment assigns the value to the left operand to z = z % p
Assignment operators 20

10
3/2/2025

Python basics - operators


Comparison operators

• When the values of two operands are to be compared then comparison operators are used

• The output of these comparison operators is always a Boolean value, either True or False

• The operands can be numbers or strings or Boolean values

• Strings are compared letter by letter using their ASCII values - thus, “P” is less than “Q”, and
“Aston” is greater than “Asher”

21

Python basics - operators


The value of p is 10 and q is 20
Name of
Operator Description Example
operator
If the values of two operands are equal, then the
== Equal to (p == q) is not True
condition becomes True
If values of two operands are not equal, then the
!= Not equal to (p != q) is True
condition becomes True
If the value of left operand is greater than the
> Greater than value of right operand, then the condition (p > q) is not True
becomes True
If the value of left operand is less than the value of
< Less than (p < q) is True
right operand, then the condition becomes True
If the value of left operand is greater than or equal
Greater than or
>= to the value of right operand, then the condition (p >= q) is not True
equal to
becomes True
If the value of left operand is less than or equal to
Less than or
<= the value of right operand, then the condition (p <= q) is True
equal to
becomes True

Comparison operators

22

11
3/2/2025

Python basics - operators


Logical operators

• The logical operators are used for comparing or negating the logical values of their operands
and to return the resulting logical value

• The values of the operands on which the logical operators operate evaluate to either True or
False

• The result of the logical operator is always a Boolean value, either True or False

• Logical expressions are evaluated left to right

23

Python basics - operators


The Boolean value of p is True and q is False
Name of
Operator Description Example
operator
Performs AND operation and the result is True when both
and Logical AND operands are True
p and q results in False

Performs OR operation and the result is True when any


or Logical OR one or both operands is True
p or q results in True

not Logical NOT Reverses the operand state not p results in False

Logical operators

P Q P and Q P or Q Not P

True True True True False

True False False True

False True False True True

False False False False

Boolean logic truth table

24

12
3/2/2025

Python basics - operators


Bitwise operators

• Bitwise operators treat their operands as a sequence 0s and 1s and perform bit-by-bit
operation, but they return standard Python numerical values
The value of p is 60 and q is 13
Name of
Operator Description Example
operator
& Binary AND Performs respective bit-wise logical AND p & q = 12 (0000 1100)

| Binary OR Performs respective bit-wise logical OR p | q = 61 (0011 1101)

^ Binary XOR Performs respective bit-wise logical XOR p ^ q = 49 (0011 0001)


(~p) = -61 (1100 0011 in
Binary One’s
~ Inverts the bits of its operand 2s complement form due
Complement
to a signed binary number)
Binary Left Left operand’s value is moved left by the
<< p << 2 = 240 (1111 0000)
Shift number of bits specified by right operand
Binary Right Left operand’s value is moved right by the
>> p >> 2 = 15 (0000 1111)
Shift number of bits specified by right operand
Bitwise operators

25

Python basics - operators


Operator precedence and associativity

• Operator precedence determines the way in which operators are parsed with respect to
each other

• Operators with higher precedence become the operands of operators with lower precedence

• Associativity determines the way in which operators of the same precedence are parsed -
almost all the operators have left-to-right associativity

26

13
3/2/2025

Python basics - operators


Operator Meaning

() Parentheses Highest

** Exponent

+x, -x, ~x Unary plus, Unary minus and Bitwise NOT

*, /, //, % Multiplication, Division, Floor division and Modulus

+, - Addition, Subtraction

Operator precedence
<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <= Comparisons

is, is not, in, not in Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR Lowest
27

Python basics - data types


1) Numbers

• Integers, floating point numbers and complex numbers fall under Python numbers category

• They are defined as int, float and complex class in Python

• Integers can be of any length; it is only limited by the memory available

• A floating-point number is accurate up to 15 decimal places

• Integer and floating points are separated by decimal points - 1 is an integer, 1.0 is floating
point number

• Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part

28

14
3/2/2025

Python basics - data types


2) Boolean

• Boolean is essential while using conditional statements - since a condition is just a yes-or-no
question, the answer to that question is a Boolean value, either True or False

• The Boolean values, True and False, are treated as reserved words

3) Strings

• A string consists of a sequence of one or more characters, which can include letters,
numbers and other types of characters - a string can also contain spaces

• Single quotes or double quotes are used to represent strings, and it is also called a string
literal

29

Python basics - data types


• Multiline strings can be denoted using triple quotes, ''' or ""“ - these are fixed values and not
variables

s = ‘This is single quote string’


s = “This is double quote string”
s = ‘”This is
Multiline
string’”
s = “a”

4) None

• None is another special data type, frequently used to represent the absence of a value

• For example,

money = None

30

15
3/2/2025

Python basics - indentation


• Python programs get structured through indentation - indentation is a requirement in
Python and not a matter of style

• Any statement written under another statement with the same indentation is interpreted to
belong to the same code block - a next statement with less indentation to the left means the
end of the previous code block

• If a code block must be deeply nested, then the nested statements need to be indented
further to the right

Block #1 Indentation which makes the


code look cleaner and easier to
understand and read
Block #2
Four whitespaces are generally
Block #3 used for indentation and are
preferred over tabs
Block #2, Continuation
Incorrect indentation will result
in IndentationError
Block #1, Continuation

31

Python basics - comments


• A comment is a text that describes what the program or a particular part of the program is
trying to do and is ignored by the Python interpreter

• Comments are useful to understand, maintain and debug the program

• Types of comments: single-line comment and multiline comments

Single-line comment

• The hash (#) symbol is used to start writing a comment - Hash (#) symbol makes all text
following it on the same line into a comment

• For example,

#This is single line Python comment

32

16
3/2/2025

Python basics - comments


Multiline comments

• First method: the hash (#) symbol is placed at the beginning of each line

#This is

#multiline comments

#in Python

• Second method: use triple quotes, either ''' or ""“ - the triple quotes are generally used for
multiline strings, and they can be used as a multiline comment as well

'''This is

multiline comment

in Python using triple quotes'''

33

Python basics - reading input


• The input() function is used to gather data from the user

• The syntax for input function is

variable_name = input([prompt])

• The prompt gives an indication to user of the value that needs to be entered through the
keyboard - when the user presses Enter key, the program resumes and input returns what
the user typed as a string

• Even when the user inputs a number, it is treated as a string which should be converted to
number explicitly using appropriate type casting function

• Example:

person = input("What is your name?")

34

17
3/2/2025

Python basics - printing output


• The print() function allows a program to display text onto the console

• The print function will print everything as strings and anything that is not already a string is
automatically converted to its string representation

• Example:

print("Hello World!!")

• Several string formats are available in Python

The [Link]() method

• The [Link]() method is used to insert the value of a variable, expression or an object
into another string and display it to the user as a single string

• The format() method returns a new string with inserted values

• The format() method uses its arguments to substitute an appropriate value for each format
code in the template
35

Python basics - printing output


• The syntax for format() method is

[Link](p0, p1, ..., k0 = v0, k1 = v1, ...)

where p0, p1,... are called as positional arguments and, k0, k1,... are keyword
arguments with their assigned values of v0, v1,... respectively

• Positional arguments are a list of arguments that can be accessed with an index of
argument inside curly braces like {index} - index value starts from zero

• Keyword arguments are a list of arguments of type keyword = value, that can be accessed
with the name of the argument inside curly braces like {keyword}

• The str is a mixture of text and curly braces of indexed or keyword types - the indexed or
keyword curly braces are replaced by their corresponding argument values and is displayed
as a single string to the user

36

18
3/2/2025

Python basics - printing output


• Example #1: country = input("Which country do you live in?")

print("I live in {0}".format(country)) The 0 inside the curly braces {0} is the
str index of the first (0th) argument

• Output: Which country do you live in? India

I live in India

• Example #2: a = 10

b = 20

print("The values of a is {0} and b is {1}".format(a, b))

print("The values of b is {1} and a is {0}".format(a, b))


str

• Output: The values of a is 10 and b is 20

The values of b is 20 and a is 10

• You can have as many arguments as you want if the indexes in curly braces have a
matching argument in the argument list

37

Python basics - printing output


The f-strings

• Formatted string or f-string is a string literal that is prefixed with “f”

• These strings may contain replacement fields, which are expressions enclosed within curly
braces - the expressions are replaced with their values

• An f at the beginning of the string tells Python to allow any currently valid variable name
within the string

• Example #1: country = input("Which country do you live in?")

print(f"I live in {country}")

• Output: Which country do you live in? India

I live in India

38

19
3/2/2025

Python basics - printing output


• Example #2: Computes the area and circumference
of a circle of a given radius
radius = int(input("Enter the radius of a circle"))

area_of_circle = 3.1415 * radius * radius

circumference_of_circle = 2 * 3.1415 * radius

print(f"Area = {area_of_circle}; Circumference = {circumference_of_circle}")

• Output:

Enter the radius of a circle 5

Area = 78.53750000000001; Circumference = 31.415000000000003

39

Python basics - type conversions


• You can explicitly cast or convert a variable from one type to another

The int() function

• Used to explicitly convert a float number or a string to an integer

• Example: float_to_int = int(3.5)

string_to_int = int("1") #number treated as string

print(f“The result of float to integer casting is {float_to_int}")

print(f“The result of string to integer casting is {string_to_int}")

• Output: The result of float to integer casting is 3

The result of string to integer casting is 1

40

20
3/2/2025

Python basics - type conversions


The float() function

• Used to explicitly convert an integer or a string to a float

• Example: int_to_float = float(4)

string_to_float = float("1") #number treated as string

print(f“The result of integer to float casting is {int_to_float}")

print(f“The result of string to float casting is {string_to_float}")

• Output: The result of integer to float casting is 4.0

The result of string to float casting is 1.0

41

Python basics - type conversions


The str() function

• The str() function returns a string which is (fairly) human readable

• Example: int_to_string = str(8)

float_to_string = str(3.5)

print(f“The result of integer to string casting is {int_to_string}")

print(f“The result of float to string casting is {float_to_string}")

• Output: The result of integer to string casting is 8

The result of float to string casting is 3.5

42

21
3/2/2025

Python basics - type conversions


The chr() function

• The chr() function converts an integer into a string of one character whose ASCII code is
same as the integer - the integer value should be in the range of 0-255

• Example:

ascii_to_char = chr(100)

print(f'Equivalent Character for ASCII value of 100 is {ascii_to_char}')

• Output:

Equivalent character for ASCII value of 100 is d

43

Python basics - type conversions


The complex() function

• The complex() function is used to print a complex number with the value real + imag*j or
convert a string or number to a complex number

• If the first argument for the function is a string, it will be interpreted as a complex number
and the function must be called without a second parameter - the second parameter can
never be a string

• Each argument may be any numeric type (including complex) - if imag is omitted, it defaults
to zero and the function serves as a numeric conversion function like int(), long() and float() -
if both arguments are omitted, the complex() function returns 0j

44

22
3/2/2025

Python basics - type conversions


• Example:

complex_with_string = complex("1")

complex_with_number = complex(5, 8)

print(f"Result after using string in real part {complex_with_string}")

print(f"Result after using numbers in real and imaginary part {complex_with_number}")

• Output:

Result after using string in real part (1+0j)

Result after using numbers in real and imaginary part (5+8j)

45

Python basics
Other related functions

• The ord() function returns an integer representing Unicode code point for the given Unicode
character

• The hex() function converts an integer number (of any size) to a lowercase hexadecimal
string prefixed with “0x”

• The oct() function converts an integer number (of any size) to a lowercase octal string
prefixed with “0o”

• The type() function returns the data type of the given object - for example type(1) returns
<class 'int’>, type(6.4) returns <class 'float’>, and so on

46

23
3/2/2025

Python basics - dynamic and strongly typed


• Python is a dynamic language as the type of the variable is determined during run-time by
the interpreter

• Python is also a strongly typed language as the interpreter keeps track of all the variables
types - in a strongly typed language, you are simply not allowed to do anything that’s
incompatible with the type of data you are working with

• Example: use of 1 + “a” leads to the following error message

Traceback (most recent call last): Traceback indicates the occurrence of an error

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'


TypeError tells us the kind of error that occurred
which in our case is the unsupported operand type(s)

47

Flow control statements


Flow control

Sequential flow Decision flow


Loop flow control
control control

True False For each item


Block of Condition
instructions #1

Block of True
Block of instructions
Block of Block of
instructions #2 False
instructions #1 instructions #2

Block of
instructions #3

Flow control statements

48

24
3/2/2025

Decision flow control statements


The if statement
Statements
• The syntax for if statement:

if conditional_expression:

statement(s) False Condition

Program to demonstrate if statement True

age = int(input(“Enter your age in years: ”)) Statement(s)

if age >= 18:


Statement
print(“You are eligible for voting.”)

print(“Remember to vote during elections.”) Flow diagram of if statement

49

Decision flow control statements


The if…else statement
Statements
• The syntax for if…else statement:

if conditional_expression:

statement(s) False Condition True

else:

statement(s)
Statement(s) Statement(s)

Program to demonstrate if statement

age = int(input(“Enter your age in years: ”))

if age >= 18: Statement

print(“You are eligible for voting.”)


Flow diagram of if…else statement
print(“Remember to vote during elections.”)

else:

print(“You are not eligible for voting, now.”)

50

25
3/2/2025

Decision flow control statements


Nested if statement

• An if statement that contains another if statement either in its if block or else block is called a
Nested if statement

if conditional_expression1:

if conditional_expression2:

statement(s)

else:

statement(s)

else:

statement(s)

51

Decision flow control statements


Program to check for leap year

year = int(input(“Enter a year: ”))

if year % 4 == 0:

if year % 100 == 0:

if year % 400 == 0:

print(f“{year} is a leap year’”

else:

print(f“{year} is not a leap year”)

else:

print(f“{year} is a leap year”)

else:

print(f“{year} is not a leap year”)

52

26
3/2/2025

Decision flow control statements


The if…elif…else statement

• The term elif is short form of else if

• The syntax of if…elif…else statement:

if conditional_expression1:

statement(s)
Only the first control
elif conditional_expression2: expression which evaluates
to True will be executed - if
statement(s) none of the conditional
expression is True, then the
elif conditional_expression3: else statement is executed

statement(s)

else:

statement(s)

53

Decision flow control statements


Statements

Condition
True False
#1

Statement(s) Condition
#2
Flow diagram of
True False if…elif…else statement

Statement(s) Condition
#3 False
True

Statement(s) Condition
#... False
True

Statement(s)

Statement(s) of
else

First statement after the statement(s) of else


54

27
3/2/2025

Decision flow control statements


Program to print the grade based on marks given as input

marks = float(input(“Enter your mark: ”))

if marks < 0 or marks > 100:

print(“Wrong input”)

elif marks >= 90.0:

print(“Your grade is A”)

elif marks >= 80.0:

print(“Your grade is B”)

elif marks >= 70.0:

print(“Your grade is C”)

elif marks >= 60.0:

print(“Your grade is D”)

else:

print(“Your grade is F”)


55

Decision flow control statements


The ternary operator

• The ternary operator is a one-line if…else statement - instead of using multi-line if…else
statements, a ternary operator is used If the conditional_expression evaluates to True,
then expression1 is to be executed and if the
conditional_expression is evaluated to be False,
• Syntax: then expression2 is to be executed

expression1 if conditional_expression else expression2

The nested ternary operator

• Just like the nested if…else statement, it is also possible to write the nested ternary operator

• Syntax:

expression1 if conditional_expression1 else expression2 if conditional_expression2 else


expression3
The conditional_expression1 is first evaluated - If the condition is
evaluated to be True, it returns expression1, otherwise it evaluates
conditional_expression2 - If this expression is evaluated to be True,
it returns expression2 otherwise it returns expression3

56

28
3/2/2025

Decision flow control statements


Program to demonstrate the ternary operator

a = int(input(“Enter first number”))

b = int(input(“Enter second number”))

print (“The bigger number is: ”, a) if a > b else print(“The bigger number is:”, b)

Program to demonstrate the nested ternary operator

a = int(input(“Enter an integer number”))

print (“The number is positive”) if a > 0 else print(“The number is negative”) if a < 0 else
print(“The number is zero”)

57

Loop flow control statements


The while loop

• Syntax: Initialization expr.

while conditional_expression:

statement(s) Condition
False
expr.
• While loop executes a set of statements repeatedly as
True Update expr.
long as the conditional_expression is true
Body of while loop

• While loop is called conditional as we don’t know in


advance the boundary for terminating the loop

Statement
Program to demonstrate the while loop
Flow diagram of while loop
i=0

while i < 10:

print(f“Current value of i is {i}”)

i=i+1
58

29
3/2/2025

Loop flow control statements


The for loop

• Syntax: Initialization expr.

for iteration_variable in collection_of_items:

statement(s)
False Test expr.

• The collection_of_items can be taken from the range() True Update expr.

function (a very special function, responsible for


Body of for loop
generating all the desired values of the control variable)

• The range() function accepts only integers as its


arguments and generates sequences of integers Statement

• The for loop is used when we know the maximum Flow diagram of for loop
number of times the body of the loop is executed and
when we want to iterate over all the elements of a
collection such as string, list, tuple, etc.

59

Loop flow control statements


The range() function

• The syntax for range() function is:

range([start], end [, step])

• The start and step are optional - when omitted, they will have default values of 0 and 1
respectively

• Examples: range(10) will have range objects of (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), range(1, 10) will
have range objects of (1, 2, 3, 4, 5, 6, 7, 8, 9), and range(1, 10, 2) will have range objects of
(1, 3, 5, 7, 9)

Program to demonstrate the for loop (program that will find the sum of first 9 numbers)

sum = 0

for i in range(1, 10):

sum += i

print(“The sum is”, sum) or print(f“The sum is {sum}”)


60

30
3/2/2025

Loop flow control statements


The continue statement

• The continue statement is used to skip the rest of the code inside the loop for the current
iteration (only) - the loop does not terminate but continues with the next iteration

• Syntax:

for k in range(5): while (condition1):

statement(s) statement(s)

if (condition): if (condition2)

continue continue

statement(s) statement(s)

61

Loop flow control statements


The break statement

• The break statement terminates the loop containing it - on encountering a break statement
inside a loop, the control jumps to the statement immediately after the body of the loop

• Syntax:

for k in range(5): while (condition1):

statement(s) statement(s)

if (condition): if (condition2):

break break

statement(s) statement(s)

statement(s) statement(s)

62

31
3/2/2025

Loop flow control statements


The pass statement

• The pass statement refers to doing nothing (no code) - it just acts as a placeholder - it
means instead of writing nothing, we write pass

• Example:
for k in range(5): k=1
if (k == 3): while k in range(5):
pass if (k == 3):
else pass
print(k) else
print(“Outside the loop”) print(k)
k=k+1
print(“Outside the loop”)

63

Loop flow control statements


The nested loops

• When a loop is inside another loop, we say it is a nested loop

• Any type of loop can be nested under any other loop - this means we can have a for-loop
inside another for-loop or a for-loop inside a while-loop or a while-loop nested inside another
while-loop or we may also have a while-loop nested inside a for-loop

• Example:

for k in range(5):

for m in range(5):

statement(s)

statement(s)

64

32
3/2/2025

Loop flow control statements


Looping through two lists using zip()

• The zip() combines two or more arrays into a single array

• The length of the resulting array will be the length of the smallest array - rest of the items
on the bigger list after the length of the smaller list will be omitted

• The general syntax is: zip(list1, list2, …)

• Example: Output: 1 cat

List1 = [1,’rat’,’mat’,4,5+5j] rat 7

List2 = [‘cat’,7,’bat’,9.2,10,11,12] mat bat


Omitted
for i, j in zip(List1, List2): 4 9.2

print(i,”\t”,j) (5+5j) 10

65

Loop flow control statements


The iterator, iter()

• The iterator iter() is a special data structure in Python - it can iterate over by using its index
starting at 0 and continuing until the last item of the sequence

• The iter() supports both sequence data and non-sequence datatypes (keys of a dictionary,
lines of a file, etc.) including user-defined objects

• An iterator has a special method next() to access the next value just like in any looping
structure where we increment the control variable

• An iterator accesses the next item by iterator.__next__() method - the iterator raises a stop
exception once all the items are exhausted

66

33
3/2/2025

Loop flow control statements


• Example: myTup=(1, ‘two’, 3.0, 4j,”Five”)

i = iter(myTup)

while True:

try:

print(“The next item in Tuple is “,i.__next__())

except StopIteration:

break
It is not possible to move backward, go back to the
beginning or copy an iterator - if we want to iterate
• Output: The next item in Tuple is 1 over the same objects again (or simultaneously),
then another iterator object needs to be used.
The next item in Tuple is two

The next item in Tuple is 3.0

The next item in Tuple is 4j

The next item in Tuple is Five

67

Loop flow control statements


Catching exceptions using try and except statement

• There are at least two distinguishable kinds of errors, viz., syntax errors and exceptions

a) Syntax errors

• Syntax errors (aka parsing errors) are perhaps the most common kind of error you get
while you are still learning Python

• Example: Output:

while True File "<ipython-input-3-c231969faf4f>", line 1

print(“Hello World!”) while True


^
SyntaxError: invalid syntax

68

34
3/2/2025

Loop flow control statements


b) Exceptions

• An exception is an unwanted event that interrupts the normal flow of the program - even a
syntactically correct statement or expression may cause such an exception during its
execution

• The program execution gets terminated when an exception occurs - we get a system-
generated error message in such cases

• Python exception handling allows us to handle the errors caused by exceptions

• Exception handling allows the programmer to provide a meaningful message to the user
about the issue rather than a system-generated message (which may not be
understandable to the user)

• Exceptions can be either built-in exceptions or user-defined exceptions

• The interpreter or built-in functions can generate the built-in exceptions while user-defined
exceptions are custom exceptions created by the user
69

Loop flow control statements


• When the exceptions are not handled by programs it results in error messages

Shows the context where the exception


• Example (1):
happened in the form of a stack traceback

>>> 10 * (1/0)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ZeroDivisionError: division by zero


This line of the error message indicates what
• Example (2): happened - ZeroDivisionError and NameError are
error types - the string printed as the exception
>>> 4 + spam*3 type is the name of the built-in exception that
occurred
Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'spam' is not defined

70

35
3/2/2025

Loop flow control statements


Exception handling using try…except…finally

• A try block consisting of one or more statements is used to partition the code that might be
affected by an exception

• The associated except blocks are used to handle any resulting exceptions thrown in the
try block

• If any statement within the try block throws an exception, control immediately shifts to the
catch block - if no exception is thrown in the try block, the catch block is skipped

• There can be one or more except blocks - multiple except blocks with different exception
names can be chained together

• Exception handling ensures uninterrupted flow of program when an exception occurs - it


also results in the execution of all statements in the program

71

Loop flow control statements


• Syntax:
try:
statement1
except exception1:
statement2
The else block will be executed if the try block does not

raise an exception - the use of else block is better than
else: adding additional code to the try block because it avoids
Optional blocks
- when present, statement3 accidentally catching an exception that wasn’t raised by
must follow all the code being protected by the try…except statement
finally:
except blocks
statement4
When an exception has occurred in the
try block and has not been handled by
The finally block is intended to define an except block, it is re-raised after the
clean-up actions - a finally block is finally block has been executed
always executed under all circumstances
The finally statement is also executed
before leaving the try statement even
“on the way out” when any other clause
when an exception did not occur
of the try statement is left via a break,
continue or return statement

72

36
3/2/2025

Loop flow control statements


• Except blocks are evaluated from top to bottom, as they appear in the code - the first except
block that specifies the exact exception name of the thrown exception is executed

• Only one except block is executed for each exception thrown - if no except block specifies a
matching exception name, an except block that does not have an exception name is
executed (if present in the code)

• Instead of having multiple except blocks with multiple exception names for different
exceptions, you can combine multiple exception names together separated by a comma
(aka parenthesized tuples) in a single except block

• The syntax for combining multiple exception names in an except block is

except (exception1, exception2, exception3):


statement(s)

• You can also leave out the name of the exception after the except keyword (this is generally
not recommended as the code will now be catching different types of exceptions and
handling them in the same way)
73

Loop flow control statements


• This is not optimal as you will be handling a TypeError exception the same way as you
would have handled a ZeroDivisionError exception

• When handling exceptions, it is better to be as specific as possible and only catch what you
can handle

Write a program to repeatedly read numbers until the user enters done. Once done is entered,
print the total, count and average of numbers. If the user enters anything other than a number,
detect the mistake using try and except, print an error message and skip to next number.

total = 0

count = 0

while True:

num = input("Enter a number: ")

74

37
3/2/2025

Loop flow control statements


if num == 'done’:

print(f"Sum of all the entered numbers is {total}")

print(f"Count of total numbers entered is {count}")

print(f"Average is {total / count}")

break

else:

try:

total += float(num)

except:

print("Invalid input")

continue

count += 1

75

Loop flow control statements


• Output:

Enter a number: 1

Enter a number: 2

Enter a number: 3

Enter a number: 4

Enter a number: done

Sum of all the entered numbers is 10.0

Count of total numbers entered is 4

Average is 2.5

76

38

You might also like