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

Chapter Two. UPDATEDpdf

Chapter Two provides an overview of Python programming, highlighting its features, advantages, and various application areas such as web development, data science, and machine learning. It discusses Python's syntax, data types, operators, and installation procedures for Python and its IDEs. Additionally, it covers basic elements like variables, constants, and input/output operations.

Uploaded by

kalkidanasdro11
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)
32 views94 pages

Chapter Two. UPDATEDpdf

Chapter Two provides an overview of Python programming, highlighting its features, advantages, and various application areas such as web development, data science, and machine learning. It discusses Python's syntax, data types, operators, and installation procedures for Python and its IDEs. Additionally, it covers basic elements like variables, constants, and input/output operations.

Uploaded by

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

Chapter Two

Basics of Python Programming

Collage of Computing Compiled by Desalegn A


Department of software engineering
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

➢Pytest: a testing framework for Python Django

➢REST framework: a toolkit for building RESTful API


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
➢1. Visit the official website of Python https://www.python.org/downloads/ and choose your
version.
Once 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

11
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
multiline comment. ''' 12
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.
# Displaying a string Output
print("Hello, World!")
# Displaying multiple values
name = "Aman"
age = 21
print("Name:", name, "Age:", age)
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. 13
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
➢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. Print (counter)
Print(miles)
Example Print(name)
or print(coutter, miles,name)
14
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. Output
x = "Zara“
Example: Printing Variables Type y = 10
z = 10.10
print(type(x))
print(type(y))
print(type(z)) 15
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 Output Output
a,b,c = 10,20,30
print (a,b,c) print (a,b,c)

➢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.
➢Python reserved keywords cannot be used naming the variable. 16
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.

17
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.

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

19
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.

➢Python strings are immutable which means when you perform an operation on
strings, you always produce a new string object of the same type, rather than
mutating an existing string
20
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.
21
Python Sequence Data Type
Example of String Data Type

Output

22
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 all the items
belonging to a Python list can be of different data type. List declaration

Example x= [2023, "Python", 3.11, 5+6j, 1.23E-4]


print(type(x))
<class 'list'>

x= [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]


print(type(x))
<class 'list'>
23
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

24
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 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

Example
x=(2023, "Python", 3.11, 5+6j, 1.23E-4)
print(type(x))
<class 'tuple'>

x=(['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))


print(type(x))
<class 'tuple'>
25
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

26
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.

27
Python Input/output operations
➢Python provides us with two built-in functions to read the input from the
keyboard. The input () Function The raw_input () Function

➢When the interpreter encounters input() function, it waits for the user to enter
data from the standard input stream (keyboard)

28
Taking Numeric Input in Python
➢Let us write a Python code that inputs width and height of a rectangle from
the user and computes the area.) The reason is, Python always read the
user input as a string.
Hence, width=“45" and height=“70" are
the strings and obviously you cannot
perform multiplication of two strings.
➢ To overcome this problem, we shall
use int(), another built-in function
from Python's standard library.
➢ It converts a string object to an integer.
➢ To accept an integer input from the
user, read the input in a string, and
type cast it to integer with int()
function
29
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.)
➢ We can use float() function
converts a string into a float
object.
➢ Write a python program
accepts the user input and
parses it to a float variable

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

➢Arithmetic operators used between two operands for a particular operation. 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
exponent operator.

➢// (Floor division):-It provides the quotient's floor value, by dividing the two operands.
31
Operators in Python
2. Comparison operator
Comparison operators compare the values of the two operands and return a true
or false Boolean value in accordance. The example of comparison operators are
==, !=, <=, >=, >, <. Output

32
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 =, +=, -=, *=, %=, **=,

Output

➢ The error occurs in the subsequent lines because you cannot use assignment operators
directly within a print() statement. Example :- A=2,b=3
print(a+=b)-----------→ error 33
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.

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

bits of the first operand, the second operand decides the number of places to shift.
34

➢ Bitwise NOT ( ~ ) is the only unary bitwise operator. Since take only one operand. X=-X-1
Operators in Python
5. Logical Operators
The assessment of expressions to make decisions typically uses logical operators
and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Example Output

35
Operators in Python
6. Membership Operators
➢The membership of a value inside a Python data structure can be verified using
Python membership operators.
➢The result is true if the value is in the data structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be
true (list, tuple, or dictionary).
not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).
Example Output

36
Operators in Python
7. Identity Operators
Operator Description
is If the references on both sides point to the same object, it is
determined to be true.
is not If the references on both sides do not point at the same object, it
is determined to be true.
Example Output

37
Precedence and Associativity of Operators in Python

*,, /, // Multiplication, matrix, division, floor


1 Left to right
,% division, remainder
2 +,- Addition and subtraction Left to right
3 <<, >> Shifts Left to right
4 & Bitwise AND Left to right
5 ^ Bitwise XOR Left to right
6 | Bitwise OR Left to right

Example:- 100 + 200 / 10 - 3 * 10


38
Errors in Python
➢In any programming language errors is common. If we miss grammar mistakes of the
programming, when your code doesn't produce the expected output.

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

1. Syntax errors :- are the grammar mistakes of the programming world. They occur when
you write code that doesn't conform to Python's syntactical rules.
➢ Forgetting a colon at the end of an if statement. Example

➢ Mismatched parentheses, like print("Hello world". print("Hello, Python!"


➢ Mixing single and double quotes improperly in a string.

➢ Using Python keywords as variable names. 39


Errors in Python
2. Runtime Errors
➢While syntax errors occur during the parsing or interpretation phase of your code, runtime
errors happen during the execution phase. Errors can be more challenging because we don't
prevent our program from running
➢Occurs when you try to divide a number by zero.
➢Occurs when you try to access an index in a list, tuple, or string that doesn't exist.
➢Occurs when you use a variable or function that hasn't been defined.
➢Occurs when you perform an operation on a data type that doesn't support it.
➢Occurs when you try to open or manipulate a file that doesn't exist.
num1 = 10
num2 = 0
Example result = num1 / num2
print(result)
40
Errors in Python
3. Logical Errors
➢Logical errors, also known as semantic errors, occur when your code doesn't produce the
expected output because of a flaw in the algorithm or the overall logic of your program.

➢Unlike syntax or runtime errors, logical errors don't generate error messages or exceptions.
Instead, your code runs without issues, but it doesn't achieve the intended results.

def calculate_average(numbers):
total = 0
Example for num in numbers:
total += num
average = total / len(numbers) - 1
return averag
41
Control Statements
➢Python's conditional statements carry out various calculations or operations according to
whether a particular Boolean condition is evaluated as 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
42
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 of
code.

➢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 indicate block of code.

➢All the statements of one block are intended at the same level indentation.
43
The If statement

The syntax of the if-statement is given below.


if expression:
statement
if expression:
statement

Exercise
1. Write a program to check the given number is positive using python?
2. Write a Simple Python Program to print the largest of the three numbers?
44
The if-else statement

The syntax of the if-else statement is given below.

if condition:
block of statements
else:
else-block

Exercise
1. Write a program to check the given number is positive or negative using python?
2. Write a Program to check whether a number is even or not using python.
45
The elif statement
The syntax of the elif- statement is given below.
if expression 1:
block of statements
elif expression 2:
block of statements
elif expression 3:
block of statements
else:
block of statements

Exercise
1. Write a python program to calculate the Grade letter of a given course by adding mid exam
and final exam result based DBU grade scale using elif ?
2. Write a python program to find the largest number from three number using nested if 46?
Looping in Python
➢Python loops allow us to execute a statement or group of statements multiple times

➢Python programming language provides the following types of loops to handle looping
requirements.
Sr.No. Name of the loop Loop Type & Description
1 While loop ➢ Repeats a statement or group of statements while a
given condition is TRUE.
➢ It tests the condition before executing the loop body.
2 For loop ➢ This type of loop executes a code block multiple
times and abbreviates the code that manages the
loop variable.
3 Nested loops ➢ We can iterate a loop inside another loop
47
Python for loop
➢Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and strings.
➢for loops are used when a section of code needs to be repeated a certain number of times.
syntax syntax
for value in range(): for value in sequence:
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.
Example:- write a python program to print a number from 1to 10 using for loop
for i in range(11): for i in range(1,11):
print(i,end=" ") print(i,end=" ")

Or Or
for i in range(11): for i in range(1,11):
print(i) print(i) 48
Python for loop
1. Write the output of the following python program? Output
for i in range(1,10,2):
print(i,end=" ")

for i in range(2,10,2):
print(i,end=" ")

2. Write a python program to display the sum of the first 100 number?
sum=0
for i in range(1,101,1):
sum=sum+i
print("the sum is",sum)
3. Write a program a python program to calculate the factorial of the given
number ? 49
For loop using list
➢Write a python program to find the sum of the square of each element of the list
using for loop? numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
syntax
for value in sequence:
statement
Since instead of range just replace list (numbers) Output

Solution:- numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]


sum = 0
for num in numbers:
sum = sum + num ** 2
print("The sum of squares is: ", sum)
50
Python while loop
➢The Python while loop iteration of a code block is executed as long as the
given Condition, i.e., conditional expression, is true.
1. Write a python program to display a number from 1 to 10?
The syntax i=1
while i<=10:
Statement print(i)
while Condition: i=i+1
Statement
2. Write a python program to find the sum of n natural number ?
i=1
sum=0
while (i<=10):
sum=sum+i
i=i+1
print(" the sum is",sum)

51
Python while loop
Exercise
1. Write a Python program for checking a number is Prime number or not
2. Write a python program to find the sum of n natural number ?
3. Write a python program to calculate factorial of a number
4. Write the output of the following program Output

i=1
while i<51:
if i%5 == 0 or i%7==0 :
print(i, end=' ')
i+=1

52
Python while loop using List
Example:- Write a python program to find the sum of the given list using for loop?
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
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
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)
53
Looping in Python
Python Loop Control Statements
➢ Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
➢ Python supports the following control statements
Sr.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.
54
Python break statement
Break is commonly used to break the loop for a given condition. Syntax
Loop statements
break;
❑Write the output of the following program??
for i in range(1,10,2): my_str = "python"
while i==8: for char in my_str:
break if char == 'o':
print(i) break
print(char)

for i in range(1,10,2): numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]


while i==7: for char in numbers:
print(i) if char == 1:
break break
print(char)
55
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)
for i in range(1,10,2): numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
while i==7: for char in numbers:
print(i) if char == 1:
continue continue
print(char) 56
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
pass;
❑Write the output of the following program??

sequence = {"Python", "program", sequence =


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

57
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

58
Python Nested loop
Example:- Write the output of the following python program
* * * * * * *
* * * * * * *
for i in range (1,8): * * * * * * *
for j in range(i+1): * * * * * * *
print("*",end=" ") * * * * * * *
print(" ") * * * * * * *
* * * * * * *
0
for i in range (1,8): 0 1
for j in range(1,8-i+1): 0 1 2
print("*",end=" ") 0 1 2 3
print(" ") 0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6 59
Python Nested loop
Example:- Write the output of the following python program
k = 2 * rows - 2 #let row=5
m = (2 * rows) - 2 #let row=5
for i in range(rows, -1, -1):
for i in range(0, rows):
for j in range(k, 0, -1):
for j in range(0, m):
print(end=" ")
print(end=" ")
k = k + 1
m = m - 1
for j in range(0, i + 1):
for k in range(0, i + 1):
print("*", end=" ")
print("*", end=' ')
print("")
print(" ")

Exercise:- write the program for the following output *


* * *
* * * * *
* * * * * * *
* * * * * * * * *

60
Python Function
➢A collection of related assertions that carry out a mathematical, analytical, or
evaluative operation is known as a function

➢A function is a block of code that used to perform certain actions. which only

runs when it is called.

➢Function names meet the same standards as variable names do.

➢Instead of repeatedly creating the same code block for various input variables,
We can call the function and reuse the code it contains with different variables.

61
Python Function
Advantages of Python Functions

➢We can stop a program from repeatedly using the same code block by including
functions.

➢Once defined, Python functions can be called multiple times and from any
location in a program.

➢The ability to return as many outputs as we want using a variety of arguments


is one of Python's most significant achievements.

62
Python Function
Python Functions Declaration 1.def function_name( parameters ):
# code block

➢The start of a capability header is shown by a catchphrase called def.

➢function_name is the function's name, which we can use to distinguish it from other
functions.

➢We will utilize this name to call the capability later in the program.

➢Name functions in Python must adhere to the same guidelines as naming variables.

➢Using parameters, we provide the defined function with arguments.

➢A colon (:) marks the function header's end.


63
Python Function
1. write a python program to calculate the sum of two number using function

def sum(num, num1):


return num+num1
x=int(input("Enter any number"))
y=int(input("Enter any number"))
addition = sum(x,y)
print( "The square of the given number is: ", addition )

2. Write a python program to square the given number?


3. Write a program to perform arithmetic operation using function?
4. Write a python function program to calculate the Grade letter of a given course by adding
mid exam and final exam result based on DBU grade scale
5, Write a python function to swap a given two number without using third variable
64
Python Function
1. What is the output of the following program?
# Example Python Code for calling a function
# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)
# Calling the function we defined
print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )

Output
65
Variable Scopes
:➢When you want to use the same variable for rest of your program or module
you declare it as a global variable,
➢while if you want to use the variable in a specific function or method, you use
a local variable.
❑Let’s understand this Python variable types with the difference between local
and global variables in the below program.
1.Let us define variable in Python where the variable “f” is global in scope and
is assigned value 101 which is printed in output
2.Variable f is again declared in function and assumes local scope.
➢It is assigned value “I am learning Python.” which is printed out as an output.
This Python declare variable is different from the global variable “f” defined
earlier
66
Local & Global Variable
:3. Once the function call is over, the local variable f is destroyed. At line 12,
when we again, print the value of “f” is it displays the value of global variable
f=101

67
Local & Global Variable
:➢While Python variable declaration using the keyword global, you can
reference the global variable inside a function.

1.Variable “f” is global in scope and is assigned value 101 which is printed

2.Variable f is declared using the keyword global. This is NOT a local


variable, but the same global variable declared earlier. Hence when we print
its value, the output is 101
3.We changed the value of “f” inside the function. Once the function call is
over, the changed value of the variable “f” persists
68
Local & Global Variable
: At line 12, when we again, print the value of “f” is it displays the value
“changing global variable”

69
Parameter & Arguments
What is the difference between Arguments and Parameters?
➢Both arguments and parameters are variables/ constants passed into a function. The
difference is that:
I. Arguments are the variables passed to the function in the function call.
II. Parameters are the variables used in the function definition.
III. The number of arguments and parameters should always be equal except for the variable
length argument list.

def add_func(a,b): ➢ (num1, num2) are in the function


sum = a + b call, and (a, b) are in the function
return sum
num1 = int(input("Enter the value of the first number: ")) definition.
num2 = int(input("Enter the value of the second number: ")) ➢ (num1, num2) are arguments and
print("Sum of two numbers: ",add_func(num1, num2)) (a, b) are parameters.
70
Types of Arguments
❑The following are the types of arguments that we can use to call a function:-

➢Positional arguments

➢Keyword arguments

➢Default arguments

➢Arbitrary arguments

71
1. Positional arguments
➢Positional or required arguments are those supplied to a function during its call in a
predetermined positional sequence.

➢The number of arguments required in the method call must be the same as those provided
in the function's definition.

Example :
def student(num1,num2,num3):
3 is assigned for num1,
sum=num1+num2-num3
5 is assigned for num2,
return sum
6 is assigned for num3,
print("the sum is ",student(3,5,6))

➢respective arguments are passed in order one after the other 72


2. Keyword arguments
➢If the arguments are passed by assigning them to their respective parameters in the function
call with no significance to the passing order, they are called "Keyword arguments"..

➢in a function call, the caller identifies the arguments by the parameter name.

Example :

5 is assigned for num1,


def student(num1,num2,num3):
10 is assigned for num2,
sum=num1+num2-num3
6 is assigned for num3,
return sum
print("the sum is ",student(num2=10,num1=5,num3=6))

➢The Python interpreter is able to use the keywords provided to match the values with
parameters 73
Positional and Keyword arguments
➢Keyword arguments must always follow positional arguments. If not, Python will raise a
syntax error:

➢Example 1 Example2

def student(num1,num2,num3):
def student(num1,num2,num3):
sum=num1+num2-num3
sum=num1+num2-num3
return sum
return sum
print("the sum is ",student(num1=7,8,num3=4))
print("the sum is ",student(10,num2=7,num3=4))

In example 2 generate Syntax Error: positional argument follows keyword argument

74
3. Default arguments
➢Default values indicate that the function argument will take that value if no argument value
: is passed during the function call.

➢The default value is assigned by using the assignment(=) operator of the form parameter

Example :1 Example:2

def student(num1=6,num2=4,num3=7): def student(num1=6,num2=4,num3):


sum=num1+num2-num3 sum=num1+num2-num3
return sum return sum
print("the sum is ",student()) print("the sum is ",student(4,6,7))

➢In example to make non-default argument follows default argument error, since default
argument must be assign right to left 75
4. Arbitrary or variable length arguments
➢Arbitrary or Variable-length Arguments process a function for more arguments than you
: specified while defining the function.

➢An asterisk (*) is placed before the variable name that holds the values of all nonkeyboard
variable arguments.
def student(*numbers):
Example : sum=0
for i in numbers:
sum=i+sum
return sum
print("the sum is ",student(4,6))
print("the sum is ",student(5,3,7,1))
print("the sum is ",student(10,9,11)) 76
Parameter passing
➢There are two methods of invoking/ calling functions-Call by value and Call by reference.

➢The default value is assigned by using the assignment(=) operator of the form parameter

➢ When the values of arguments are passed into parameters in the function, the values are
copied into parameters. This method is called "Call by value".

➢In this method, arguments and parameters are different and are stored in different memory
locations.

➢Changes done on parameters inside the function do not affect the arguments in the program
and vice versa.

77
Parameter passing
➢When the addresses of the arguments are passed into parameters instead of values, this
method of invoking a function is called "Call by Reference".

➢Both the arguments and parameters refer to the same memory location.

➢Changes to the parameters (pointers) will affect the values of the arguments in the program.

What is the output of the


above c++ program ?
Output Output
------- ----------
------- -----------

78
Parameter passing in python
➢Python’s argument-passing model is neither “Pass by Value” nor “Pass by Reference” but it
is “Pass by Object Reference or Call by assignment”. In Python, every single entity is an
object. Objects are divided into Mutable and Immutable objects.

➢What happens in Python when we assign a value to a variable is different from other
languages like C ,C++ or Java.

➢Mutable objects are those objects/ data types in Python that we can modify after creating
them Example : Lists, Dictionaries, Sets

➢Immutable objects, on the other hand, are objects that can't be modified once created.

Example: int, float, strings, tuples, Boolean ,complex


79
Parameter passing
The Python id() Function: Used to read the special ID or address of object
Mutable Objects example : Output

a = [23, 45, 89]


print(id(a))
print(a)
a.append(49)
print(id(a))
print(a)

➢ List is mutable object ,As you can observe, when created with the name a, it is saved in
the address “2891662300096“ and the value is 23,45,89.
➢ Using append(), we altered it by appending another value 49. It is still in the same
memory location and the value is updated to 23,45,89,49 , meaning the same object is
modified.
80
Parameter passing
Immutable Objects: example : Output

a = 20
print(id(a))
print(a)
a += 23
print(id(a))
print(a)

➢ An int object is immutable, meaning we can't modify it once created. You might
wonder we still added 23 in the above code.
➢ Observe that the object when created is not the same object after adding. Both are in
different memory locations and different value which means they are different objects.
81
Parameter passing
➢So, how are arguments passed to the parameters when a function is invoked?
With all the knowledge about assignment or Object Reference operation in Python:
➢The passing is like a "Call by Reference" if the arguments are mutable.
➢The passing is like "Call by Value" if the arguments are immutable.

82
Nested Function
➢Nested (or inner) functions are functions defined within other functions that allow us to
directly access the variables and names defined in the enclosing function.

➢simply use the def keyword to initialize another function within a function to define a
nested function. Java, C, C++ not support nested function, but python and JavaScript
support nested function def arithmetic_operation():
x="wellcome"
Example: print("the outer function is",x)
def add(x, y):
return x + y
a=int(input("enter the value"))
b=int(input("enter the value"))
print("the sum is ",add(a,b))
arithmetic_operation() 83
Module in python
➢A file containing a set of function you want to include in your application.

➢A module is a file containing Python code, definitions of functions, statements,

➢We employ modules to divide complicated programs into smaller, more understandable
pieces. Modules also allow for the reuse of code.

How to cerate user defined module

➢To create a module just save the code with the file extension .py

How to use the module

To use the module just import the module name

84
Module in python
Example first create the module save in second import the module and use
def add(a,b):
return a+b import calcu
def sub(a,b): print(calcu.add(4,5))
return a-b print(calcu.sub(6,8))
def div(a,b): print(calcu.div(4,5))
return a/b print(calcu.mult(6,8))
def mult(a,b): print(calcu.flo(4,5))
return a*b print(calcu.mod(6,8))
def expo(a,b): print(calcu.expo(6,8))
return a**b
def flo(a,b): the module you created and imported must be in the same folder
return a//b
def mod(a,b):
return a%b 85
Python Built in Function (Python version3.12.2)
➢Python comes with a wide range of built-in functions that are readily
available for you to use without needing to import any additional libraries.

As of Python 3.12.2 version, there are 71 built-in functions

➢Len(list) :- Returns the length of the string.

➢max(list):-Returns the max alphabetical character from the string str.

➢min(list):-Returns the min alphabetical character from the string str.

➢swapcase():- Inverts case for all letters in string.


86
Python Built in Function (Python version3.12.2)
➢The abs() function returns the absolute value of x,

➢The max() function returns the largest of its arguments or largest number from the iterable
(list or tuple).

➢The function min() returns the smallest of its arguments i.e. the value closest to negative
infinity, or smallest number from the iterable (list or tuple)

➢The pow() function returns x raised to y. It is equivalent to x**y. The function has third
optional argument mod. If given, it returns (x**y) % mod value

➢round() is a built-in function in Python. It returns x rounded to n digits from the decimal
point.
87
Python Built in Function (Python version3.12.2)
➢The sum() function returns the sum of all numeric items in any iterable (list or tuple).

➢sorted():-Returns a sorted list from the given iterable

➢reversed():-Returns the reversed iterator of a sequence

➢ord():-Returns an integer of the Unicode character

➢eval():- Runs Code Within Program by accept input from the user

➢range():-Returns a sequence of integers

88
Python built in Function by imported libraries
➢Python's built-in functions that are provided by imported libraries. Python has a wide range
of libraries that extend its functionality.

➢To import the libraries use import keyword and include libraries

Import Libraries name

1. math libraries(import math)

➢ math.sqrt(): Computes the square root of a number.

➢ math.sin():math.cos()`, `math.tan()`: Compute trigonometric functions.

➢ math.log():math.exp()`: Compute logarithms and exponentials.

example x=40, print(sqrt(x)) 89


Python built in Function by imported libraries
2. random(import random)

➢ random.randint(): Generate a random integer.

➢ random.choice(): Choose a random element from a sequence.

➢ random.shuffle(): Shuffle a sequence randomly.

Example

print(random.randint(1, 10)) # Output: Random integer between 1 and 10

print(random.choice(['apple', 'banana', 'orange'])) # Output: Randomly chosen fruit

3. Turtle (import turtle):-Turtle is a Python library which used to create graphics, pictures,
and games. 90
Python built in Function by imported libraries
4. datetime(import datetime):- Get the current date and time.

Example

print(datetime.datetime.now()) # Output: Current date and time

5. statistics( import statistics)

Python statistics module provides like mean(), median() ,mode(), stdev()

Example
import statistics
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
print("Mean is :", x)
91
Python Packages
➢One of the key features of Python is the ability to create and access packages, which are
collections of modules that can be reused across different projects.

➢Python packages are groups of modules that may be used in several applications.

➢Packages in Python can be easily created and accessed using the built-in package manager

Python also provides a built-in package manager, pip ,conda that can be used to install and
manage packages.

A command-line programm called Pip, conda may be used to add, delete, and update
packages in Python. "pip instal package name“ and “conda instal package name“ is the
syntax to use when installing a package using pip and conda.
92
Python Packages
➢For example, if you want to install the "numpy" package, the command would be "pip
install numpy". Pip can also be used to update and remove packages.

➢ The syntax for updating a package is "pip install --upgrade package_name" and

➢the syntax for removing a package is "pip uninstall package_name".

➢some packages are fundamental across a wide range of applications:

➢1. NumPy: This package is essential for numerical computing in Python.

➢2. Pandas: Pandas is a powerful library for data manipulation and analysis.

93
Python Packages
3. Matplotlib: For data visualization, Matplotlib is a go-to library.

4. Scikit-learn: It offers simple and efficient tools for data mining and data analysis, including
various algorithms for classification, regression, clustering, and dimensionality reduction.

5.TensorFlow or PyTorch: These libraries are crucial for deep learning and neural network-
based tasks. with support for GPU acceleration.

➢These packages form the backbone of many Python projects in fields ranging from
scientific computing and data analysis to machine learning and artificial intelligence.

94

You might also like