Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Python U1

Uploaded by

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

Python U1

Uploaded by

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

Programming using in

Python

1
Unit-1

• INTRODUCTION TO PYTHON
• Structure of Python Program-Underlying mechanism of Module Execution-
Branching and Looping-Problem Solving Using Branches and Loops-Functions
- Lists and Mutability- Problem Solving Using Lists and Functions

• Lab Exercises
1. Demonstrate usage of branching and looping statements
2. Demonstrate Recursive functions
3. Demonstrate Lists
2
What is Python?

• Python is a popular programming language. It


was created by Guido van Rossum, and
released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

3
What can Python do?
• Python can be used on a server to create web
applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can also
read and modify files.
• Python can be used to handle big data and perform
complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.
4
Why Python?

• Python works on different platforms (Windows, Mac,


Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English
language.
• Python has syntax that allows developers to write programs
with fewer lines than some other programming
languages.
• Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.
5
• Python Syntax compared to other programming languages
• Python was designed for readability, and has
some similarities to the English language with
influence from mathematics.
• Python uses new lines to complete a command,
as opposed to other programming languages
which often use semicolons or parentheses.
• Python relies on indentation, using whitespace,
to define scope; such as the scope of loops,
functions and classes. Other programming
languages often use curly-brackets for this
purpose.

6
Structure of Python Program
• a program consists of a set of statements. Each statement can contain one or more
mathematical expressions, and each expression consists of literals, identifiers and
operators.
• Python runs a program by executing its statements, each of which fulfills a specific
functionality.
• The right hand side of = must be an expression, and the left hand side must be an
identifier
• The statement is executed by evaluating the
expression first, and then binding the
resulting object with associating
the left-hand-side identifier.
Understanding the execution of each
type of statement is crucial to the understanding
and design of Python programs.
7
8
9
10
Underlying mechanism of Module Execution
• What is a Module?
A file containing a set of functions you want to include in your application.

• Create a Module
To create a module just save the code you want in a file with the file extension .py

def wel(name):
print("Hello," + name+"welcome to python class")

• Use a Module
Now we can use the module we just created, by using the import statement:

import ex1

ex1.wel("MDS B students ")

11
Module Objects
• an imported module can be accessed by an identifier that bares the same
name of the module
• functions defined in a module can be accessed by using the module name
and the dot (.) operator (i.e. math.e)
• the memory structure after the following three lines of code are executed
>>> x = 1
>>> y =’abc’
>>> import math

12
13
• Python automatically searches for the locations above when a library
module is imported, where the folder names depend on the Python
version. Note that the math module is an exception: it cannot be
found under the library folder locations above.
• This is because math is a very commonly used module, and is built in
the main Python program itself.
• Other commonly used modules, including cmath, are also built-in.

14
The Mechanism of Module Importation

• The import statement creates an identifier that has the same name as
the module.
• For example, by using ‘import random’, ‘random.py’ is imported into
the memory, and associated with the name ‘random’ in the global
binding table.
• To avoid name clashes and for the convenience of reference, a
module can also be given a different name when imported into the
binding table.
• This can be achieved by using a variant of the import statement, with
the syntax ‘import x as y’, where x is the name of the module in the
file system and y is the desired name in the binding table.

15
• The Math Module
• Python has also a built-in module called math, which extends the list of mathematical
functions.

import math
import math
x = math.sqrt(64)
print(x)
x = math.ceil(1.4)
y = math.floor(1.4)

print(x)
print(y)

x = math.pi

print(x)

print(math.isclose(1.233, 1.231))
print(math.isfinite(2000)) 16
Example

❖ In the example above, the math module is loaded into the binding table and associated with the identifier m.

❖ As a result, by using “m.”, the corresponding binding table of the math module can be accessed.

❖ However, the identifier “math” does not exist in the global binding table this time

17
Example

In the example above, x is initially bound to a number, but then rebound to a module.

The original binding is overridden.

18
Example

19
• modules such as random.py are Python programs themselves. In fact,
any Python program can be loaded as a module.
• To verify this, the program saving.py can be used as an example.
• Suppose that another source file, textimport.py, is created under the
Desktop folder.

20
Duplicated Imports

• If the same module is imported twice, the content of the module will
not be executed by the second import statement.

21
Importing Specific Identifiers

22
23
24
Python Install
• https://www.python.org/downloads/release/python-3106/

• C:\Users\Your Name>python --version

25
Run Python in Immediate mode

26
Run Python in the Integrated Development Environment
(IDE)

• PyCharm
• PyDev
• Spyder
• Thonny
• IDLE
• Wing
• Atom IDE

27
• Python syntax can be executed by writing directly in the Command
Line: >>> print("Hello, World!")
Hello, World!

• Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
if 5 > 2:
print(“Five is greater than two!”)ry it Yourse

• use the same number of spaces in the same block of code, otherwise Python will
give an error 28
Comments

• Python has commenting capability for the purpose of in-


code documentation.
• Comments start with a #, and Python will render the
rest of the line as a comment:
‘’’ comments
comments
comments
’’’

29
Python Variables

• In Python, variables are created when you assign a


value to it
• Python has no command for declaring a variable.
• Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Variables do not need to be declared with any
particular type, and can even change type after they
have been set.
x = 5
y = "John"
print(x)
print(y)
30
• Casting
• To specify the data type of a variable, this can be done
with casting.
• x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
• Get the Type
• The data type of a variable with the type() function
•x = 5
y = "John"
print(type(x))
print(type(y))

31
• Single or Double Quotes?
• String variables can be declared either by using single or double
quotes:
• x = "John"
# is the same as
x = 'John’
• Variable names are case-sensitive.
• a = 4
A = "Sally"
#A will not overwrite a
• Variable Names
• A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables: A
variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three
different variables) 32
Multi Words Variable Names

• Variable names with more than one word can be


difficult to read.
• Camel Case
• Each word, except the first, starts with a capital letter:
• myVariableName = "John"
• Pascal Case
• Each word starts with a capital letter:
• MyVariableName = "John"
• Snake Case
• Each word is separated by an underscore character:
• my_variable_name = "John"

33
Assign Multiple Values

• Many Values to Multiple Variables


• Python allows you to assign values to multiple variables in one line
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• Note: Make sure the number of variables matches the number of
values, or else you will get an error.

• One Value to Multiple Variables


• And you can assign the same value to multiple variables in one
line:
• x = y = z = "Orange"
print(x)
print(y)
print(z)
34
Output Variables
• The Python print() function is often used to output
variables.
• x = "Python is awesome"
print(x)

• In the print() function, you output multiple variables,


• separated by a comma
• Use + operator to output multiple variables
• x = "Python "
y = "is "
z = "awesome"
print(x, y, z)
print(x + y + z)

35
• when combine a string and a number with the +
operator , an error is occurred
•x = 5
y = "John"
print(x + y)
• The best way to output multiple variables in the print()
function is to separate them with commas, which even
support different data types
•x = 5
y = "John"
print(x, y)
36
Global Variables

• Variables that are created outside of a function (as in all


of the examples above) are known as global
variables.
• Global variables can be used by everyone, both inside
of functions and outside.
• If you create a variable with the same name inside a
function, this variable will be local, and can only be
used inside the function. The global variable with the
same name will remain as it was, global and with the
original value.
• To create a global variable inside a function, you can
use the global keyword.

37
Built-in Data Types

• In programming, data type is an important concept.


• Variables can store data of different types, and different
types can do different things.
• Python has the following data types built-in by default,
in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

38
Keywords

39
Strings

• Strings in python are surrounded by either single quotation marks, or double


quotation marks.
• Assign String to a Variable
• Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
• a = "Hello"
print(a)
• Multiline Strings
• assign a multiline string to a variable by using three quotes
• use three double quotes
• a = """ aaa
bbbb bbbb ccc
"""
print(a)
• three single quotes:
• a = ''' Ljjjjj fffff tttttt,
tttttt yyyyy uuuuuuu,
uuuuuu xxxxxx cccccc
'''
print(a)
• To get the length of a string, use the len() function 40
• Modify Strings
• Python has a set of built-in methods that you can use on strings.
• upper() method returns the string in upper case
• a = "Hello, World!"
print(a.upper())
• Lower() method returns the string in lower case
• a = "Hello, World!"
print(a.lower())
• Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very
often you want to remove this space.
• a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“
• Replace String
• Replace() method replaces a string with another string:
• a = "Hello, World!"
print(a.replace("H", "J"))
• split() method returns a list where the text between the specified separator
becomes the list items. 41
• a = "Hello, World!"
• String Concatenation
• To concatenate, or combine, two strings you can use the +
operator.
• String Format
• age = 36
txt = "My name is John, I am " + age
print(txt)
• combine strings and numbers by using the format()
method
• Format () method takes the passed arguments, formats them,
and places them in the string where the placeholders { }
• age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

• quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars." 42
Boolean Values
In programming you often need to know if an expression is True or False.
Evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)

43
Python Operators

• Operators are used to perform operations on variables


and values.
• Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

44
Arithmetic Operators

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

45
Assignment operators

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
46
Comparison operators

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

47
Logical operators

Operator Description Example

and Returns True if both statements x < 5 and x < 10


are true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true

48
Python Identity Operators

Operator Description Example

is Returns True if both variables are x is y


the same object (memory
location)
is not Returns True if both variables are x is not y
not the same object

Python Membership Operators


Operator Description Example
in Returns True if a sequence x in y
with the specified value is
present in the object

not in Returns True if a sequence x not in y


with the specified value is
not present in the object
49
Python Bitwise Operators
bitwise operations include encryption, compression, graphics, communications over
ports/sockets, embedded systems programming and finite state machines.

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall
shift off

>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
shift the rightmost bits fall off

50
51
52
53
54
55
56
Execution-Branching and Looping

57
Python Conditions and If statements

• Python supports the usual logical conditions from


mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

58
• These conditions can be used in several ways, most
commonly in "if statements" and loops.
• An "if statement" is written by using the if keyword.
• Example
• If statement:
if <condition>:
print()

a = 33
b = 200
if b > a:
print("b is greater than a")

59
• Elif
• The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".
if <condition1>:
print()
elif <condition2>:
print()

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
60
Else
• The else keyword catches anything which isn't caught by the
preceding conditions.
if <condition1>:
print()
elif <condition2>:
print()
else:
print()

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

* Also have an else without the elif: 61


Short Hand If
• If you have only one statement to execute, you can put
it on the same line as the if statement.
• Example
• One line if statement:
• if a > b: print("a is greater than b")

62
Short Hand If ... Else
• If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line:
Example
• One line if else statement:
•a = 2
b = 330
print("A") if a > b else print("B")
• This technique is known as Ternary Operators,
or Conditional Expressions.

63
• lso have multiple else statements on the same line:
• Example
• One line if else statement, with 3 conditions:
• a = 330
b = 330
print("A") if a > b else print("=") if a ==
b else print("B")

64
And
The and keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

65
Or
The or keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

66
Nested If
• have if statements inside if statements, this is called nested if statements.

Example
• x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
67
The pass Statement
• if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.

• Example
a = 33
b = 200

if b > a:
pass

68
Python Loops

Python has two primitive loop commands:

• while loops
• for loops

69
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Initialization
while <condition>:
print()
<increment or decrement >
Example
• Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1

• remember to increment i, or else the loop will continue forever.


70
The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example
• Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
71
The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example
Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
72
The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example
• Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

73
Python For Loops

• A for loop is used for iterating over a sequence (that is


either a list, a tuple, a dictionary, a set, or a string).
• This is less like the for keyword in other programming
languages, and works more like an iterator method as
found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc.
• The for loop does not require an indexing variable to
set beforehand.
74
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
• Even strings are iterable objects, they contain a
sequence of characters:
Example
• Loop through the letters in the word "banana":
for x in "banana":
print(x)

75
The break Statement

With the break statement we can stop the loop before it has looped through all
the items:

Example
• Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break 76
The continue Statement

With the continue statement we can stop the current


iteration of the loop, and continue with the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

77
The range() Function
• To loop through a set of code a specified number of
times, we can use the range() function,
• The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the
values 0 to 5.
78
• The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values
from 2 to 6 (but not including 6):
• Example
• Using the start parameter:
• for x in range(2, 6):
print(x)

79
• The range() function defaults to increment the sequence
by 1, however it is possible to specify the increment value
by adding a third parameter: range(2, 30, 3):
• Example
• Increment the sequence with 3 (default is 1):
• for x in range(2, 30, 3):
print(x)
• Try it Yourself »

80
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has
ended:

for x in range(6):
print(x)
else:
print("Finally finished!") 81
• The else block will NOT be executed if the loop is stopped by a break statement.

• Example
• Break the loop when x is 3, and see what happens with the else block:

• for x in range(6):
• if x == 3: break
• print(x)
• else:
• print("Finally finished!")
82
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each
iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
83
The pass Statement

• for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass

84
Python Collections (Arrays)
• There are four collection data types in the Python programming
language:
• List is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable.
No duplicate members.
• *Set items are unchangeable, but you can remove and/or add
items whenever you like.
• **As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered. 85
List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second
item has index [1] etc.

Ordered
• Lists are ordered, it means that the items have a defined order,
and that order will not change.
• If you add new items to a list, the new items will be placed at
the end of the list.

Changeable
• The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created. 86
Python Lists

• Access List Items


• Change List Items
• Add List Items
• Remove List Items
• Loop Lists
• List Comprehension
• Sort Lists
• Copy Lists
• Join Lists
• List Methods
87
Python Lists
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage.
• Lists are created using square brackets:
• Example
• Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

88
Allow Duplicates
• Since lists are indexed, lists can have items with the same value:
Example
• Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

89
List Length
• To determine how many items a list has, use the len() function:
Example
#Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types


• List items can be of any data type:
Example
• String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
90
list3 = [True, False, False]
• A list can contain different data types:
Example
• A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
type()
• From Python's perspective, lists are defined as objects with the
data type 'list':
• <class 'list'>
Example
• What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
91
The list() Constructor

• It is also possible to use the list() constructor when creating a new list.

Example
• Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry"))


# note the double round-brackets
print(thislist)

92
Access List Items
• List items are indexed and you can access them by
referring to the index number:
Example
• Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
• The first item has index 0.

93
Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last item etc.
Example
• Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range of Indexes
• specify a range of indexes by specifying where to start and where to end the range.
• When specifying a range, the return value will be a new list with the specified items.
Example
• Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])

The search will start at index 2 (included) and end at index 5 (not included) 94
• By leaving out the start value, the range will start at the first item:
Example
• This example returns the items from the beginning to, but NOT
including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

• By leaving out the end value, the range will go on to the end of the list:
Example
• This example returns the items from "cherry" to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

95
Range of Negative Indexes

• Specify negative indexes if you want to start the search from the
end of the list:

Example

• This example returns the items from "orange" (-4) to, but NOT
including "mango" (-1):

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
96
Check if Item Exists

• To determine if a specified item is present in a list use the in


keyword:

Example

• Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")


97
Change List Items
Change Item Value

• To change the value of a specific item, refer to the index number:

Example

• Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)
98
Change a Range of Item Values
• To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
Example
• Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

• If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
• Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist) 99
• If you insert less items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:
Example
• Change the second and third value by replacing it with one
value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

100
Python - Add List Items

Append Items
• To add an item to the end of the list, use the append() method:
Example
• Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

Insert Items
✔ To insert a list item at a specified index, use the insert() method.
✔ The insert() method inserts an item at the specified index:
Example
✔ Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist) 101
Extend List
• To append elements from another list to the current list, use the
extend() method.
• Example
• Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

❖The elements will be added to the end of the list.

102
Add Any Iterable
• The extend() method does not have to append lists, you can add any
iterable object (tuples, sets, dictionaries etc.).
Example
• Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

103
Python - Remove List Items
Remove Specified Item
• The remove() method removes the specified item.
Example
• Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Remove Specified Index


⮚ The pop() method removes the specified index.
Example
⮚ Remove the second item:

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)
104
❖If you do not specify the index, the pop() method removes the last item.
❑The del keyword also removes the specified index:
Example
❑Remove the first item:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)

✔ The del keyword can also delete the list completely.


Example
✔ Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist

❖Clear the List


❖The clear() method empties the list.

❖The list still remains, but it has no content.


Example
❖Clear the list content:

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)

105
Python - Loop Lists

Loop Through a List


• loop through the list items by using a for loop:
Example
• Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

106
Loop Through the Index Numbers
• Also use loop through the list items by referring to their index number.
• Use the range() and len() functions to create a suitable iterable.
Example
• Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])

107
Using a While Loop
• loop through the list items by using a while loop.
• Use the len() function to determine the length of the list, then start at 0 and
loop your way through the list items by referring to their indexes.
• Remember to increase the index by 1 after each iteration.
Example
• Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
108
List Comprehension
✔ List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Example:
✔ Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
✔ Without list comprehension you will have to write a for statement with a conditional test
inside:
✔ Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
109
Looping Using List Comprehension
• List Comprehension offers the shortest syntax for looping through lists:
• Example
• A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

With list comprehension you can do all that with only one line of code:
• Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
110
The Syntax
• newlist = [expression for item in iterable if condition == True]
• The return value is a new list, leaving the old list unchanged.

Condition
• The condition is like a filter that only accepts the items that valuate to
True.

Example
• Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]

111
• The condition if x != "apple" will return True for all elements other than "apple",
making the new list contain all fruits except "apple".
• The condition is optional and can be omitted:

Example
• With no if statement:
newlist = [x for x in fruits]

✔ Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Example
✔ You can use the range() function to create an iterable:
newlist = [x for x in range(10)]

Example
112
newlist = [x for x in range(10) if x < 5]
Expression
• The expression is the current item in the iteration, but it
is also the outcome, which you can manipulate before it
ends up like a list item in the new list:
Example
• Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]
print(newlist)
Example
• Set all values in the new list to 'hello':
newlist = ['hello' for x in fruits]
print(newlist)
113
• The expression can also contain conditions, not like a filter, but
as a way to manipulate the outcome:
Example
• Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]

• The expression in the example above says:


• "Return the item if it is not banana, if it is banana return
orange".

114
Python - Sort Lists

• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default
num = [100, 50, 65, 82, 23]
num.sort()
print(num)
str = ["orange", "mango", "kiwi", "pineapple", "banana"]
str.sort()
print(str)
• To sort descending, use the keyword argument reverse = True

115
Reverse Order
• The reverse() method reverses the current sorting order of the
elements.
• Example
• Reverse the order of the list items:
L = ["banana", "Orange", "Kiwi", "cherry"]
L.reverse()
print(L)

116
Copy a List

• There are ways to make a copy, one way is to use the built-in List
method copy()
L1 = ["mon", "tue", "wed"]
n1 = L1.copy()
print(n1)

• Another way to make a copy is to use the built-in method list()


L2 = [123, 432, 543]
n2 = list(L2)
print(L2)

117
Repetition of lists
>>>x=[1,2]
>>>print(x*3)
[1, 2, 1, 2, 1, 2]

118
Python Functions

▪ A function is a block of code which only runs when it is called.


▪ can pass data, known as parameters, into a function.
▪ A function can return data as a result.
▪ Creating a Function
▪ In Python a function is defined using the def keyword:
• Example
def my_function():
print("Hello from a function")
✔ Calling a Function
✔ To call a function, use the function name
followed by parenthesis:
my_function()
119
120
Arguments
✔ Information can be passed into functions as arguments.
✔ Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
✔ The following example has a function with one argument
(fname). When the function is called, we pass along a first name,
which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
121
my_function("Linus")
Parameters or Arguments?
• The terms parameter and argument can be used for the same thing:
information that are passed into a function.

• A parameter is the variable listed inside the parentheses in the


function definition.

• An argument is the value that is sent to the function when it is called.

122
Number of Arguments
• By default, a function must be called with the correct number of arguments. Meaning that
if your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.

Example
• This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

✔ If you try to call the function with 1 or 3 arguments, you will get an error:
123
Arbitrary Arguments, *args

• If do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
Example
• If the number of arguments is unknown, add a * before the parameter
name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


124
Ex:
def adder(x,y,z):
print("sum:",x+y+z)

adder(10,12,13)

sum: 35
Ex:
def adder(x,y,z):
print("sum:",x+y+z)

adder(5,10,15,20,25)
125
Example *args
def adder(*num):
sum = 0

for n in num:
sum = sum + n

print("Sum:",sum)

adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
126
Keyword Arguments

• To send arguments with the key = value syntax.


• This way the order of the arguments does not matter.
• Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

127
Arbitrary Keyword Arguments, **kwargs

✔ If do not know how many keyword arguments that will be passed into your function,
add two asterisk: ** before the parameter name in the function definition.

✔ This way the function will receive a dictionary of arguments, and can access the items
accordingly:

✔ Example
✔ If the number of keyword arguments is unknown, add a double ** before the parameter
name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


128
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

myFun(first='Python', mid='Programming', last='Language')

129
def myFun(args,**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

myFun('Hi',first='Python', mid='Programming', last='Language')

130
• *args and **kwargs are special keyword which allows function to take
variable length argument.
• *args passes variable number of non-keyworded arguments and on
which operation of the tuple can be performed.
• **kwargs passes variable number of keyword arguments dictionary to
function on which operation of a dictionary can be performed.
• *args and **kwargs make the function flexible.

131
Default Parameter Value

❖The following example shows how to use a default parameter value.

❖If we call the function without argument, it uses the default value:

❖Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
132
Passing a List as an Argument

✔ Send any data types of argument to a function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside the function.

✔ E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

✔ Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
133
Return Values

• To let a function return a value, use the return statement:

• Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

134
def num(x):
if x>0:
return "positive"
elif x<0:
return "negative"
else:
return "zero"

print(num(-4))

135
def odd(n):
for i in n:
if i%2==1:
return i

print(odd((1,2,3)))

136
def odd(n):
s=[]
for i in n:
if i%2==1:
s.append(i)
return s

print(odd((1,2,3)))

137
The pass Statement

✔ function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to
avoid getting an error.

✔ Example
def myfunction():
pass

138
Recursion

❖Python also accepts function recursion, which means a defined function can call itself.

❖Recursion is a common mathematical and programming concept. It means that a function


calls itself. This has the benefit of meaning that you can loop through data to reach a result.
❖The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.

❖In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).

❖To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.

139
140
141
Recursion Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)
142
143
Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems using
recursion.
• Sequence generation is easier with recursion than using some nested
iteration.

Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
• Recursive functions are hard to debug.

144
Python programs in Recursive
• Factorial
• Fibonacci series

145
recursion to find out the sum of numbers from 1 to n like 1 + 2 + 3 + 4 +, etc.

def sumnums(n):
if n == 1:
return 1
return n + sumnums(n - 1)

print(sumnums(3))
print(sumnums(6))
print(sumnums(9))
146
Function Definition Using lambda
expressions
• f (x, y) = x+2y. The function takes two number arguments, and returns
their weighted sum. The name of the function is f .
• Python provides a simple type of expression, the lambda expression,
for the definition of such a function

lambda <arguments >: <return value expression >

The value of a lambda expression is a function object.


f = lambda x, y: x+2*y

147
148
149
150
• An argument that is explicitly assigned in a function call is called a
keyword argument.
151
The Dynamic Execution Process of Function Calls
def f1():
print("function1")
f2()

def f2():
print("function2")
f3()

def f3():
print("function3")

f1()
152
Identifier Scopes
• Identifier scope refers to the accessibility of identifiers in different
parts of Python code; it is an important concept related to functions.
• For a simple example of the concept of scopes, consider the
accessibility of identifiers from a function body.
• Statements defined in a function can contain references to identifiers
defined outside the function
• Global scope and local scope. Top-level statements in IDLE or a Python
program being executed form the global scope, while statements
inside a function body being executed form a local scope.

153
x = "global"

def scope():
x="local"
print("x inside:", x)

scope()
print("x outside:", x)

154

You might also like