• No results found

Python Essentials. The Core Python Programming Language

N/A
N/A
Protected

Academic year: 2021

Share "Python Essentials. The Core Python Programming Language"

Copied!
107
0
0

Loading.... (view fulltext now)

Full text

(1)

Python Essentials

The Core Python Programming Language

(2)

Version history of Python

• Version 1.0: Released in 1994 (New features like, lambda, map and filter were added)

• Version 2.0: Released in 2000 (List comprehension were added)

• Version 3.0: Released in 2008 (emphasized on removing duplicate construct and methods)

• There are various minor versions and update to each python versions.

• Currently Python 3.9.2 is the latest version of python

(3)

Flavors of Python

• Python flavors means the different python compilers.

• These favors are useful integrating other programming languages with python

• C python: C based compiler used. Can be helpful to integrate c/c++ programs

• J python: Designed to run on Java platform

• Py : Implementation based on Python , faster than c python

• Iron Python: Integrated with .NET framework

• Ruby Python: Useful to provide a bridge between Ruby and python App Development

• Pythonxy: Used for numerical computations and data analytics

• Anaconda Python: Used for Scientific computation

(4)

• First of all, the Python program is

translated into an executable program, or a set of libraries linked into another program.

• Depending on flavor of Python, the interpreter itself may be implemented as a C program, a set of Java classes, or something else.

• Whatever form it takes, the Python code you write must always be run by this interpreter. And to enable that, you must install a Python interpreter on your computer.

(5)

Setting up your programming environment

• Visit python.org and download the latest version of python for windows os

• Install the python on your machine

• After installation check the python version by using cmd Type py –v on command prompt

• Open Python IDLE (Integrated Learning and Development Environment)

• From the shell create a new source file and type the code

Print(“welcome to python”)

(6)

Variables and Simple Data Types

• Variables are names given to memory locations where constants and values are stored.

• You can think of a variables like a container which contains data.

• The variables are given names.

• Consider the following example here, message is the variable

message “welcome”

(7)

Rules for creating variables

• Variable names can contain only letters, numbers, and underscores.

• They can start with a letter or an underscore, but not with a number. For instance, you can call a variable message_1 but not 1_message.

• Spaces are not allowed in variable names, but underscores can be used to

separate words in variable names. For example, greeting_message works, but greeting message will cause errors.

• Avoid using Python keywords and function names as variable names; that is, do not use words that Python has reserved for a particular programmatic purpose, such as the word print.

• Variable names should be short but descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than

length_of_persons_name.

• Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0.

(8)

Practice Exercise

• Store a message in a variable, and print that message . Then change the value of your variable to a new message, and print the new

message .

(9)

The Basic Data types

• Strings

• Number

• Integers

• Floats

• Complex

(10)

String

• A string is simply a series of characters.

• Anything inside quotes is considered a string in Python

• You can use single or double quotes around your strings.

"This is a string.“

'This is also a string.'

(11)

Some Common String functions

• Method is an action that Python can perform on a piece of data.

• string_object.title()

• string_object.upper()

• string_object.lower()

• string_object.strip()

• string_object.rstrip()

• string_object.lstrip()

• len(string_object)

(12)

Access String As Arrays

mystr="welcome"

print(mystr[0]) W

(13)

Number

• There are 3 numeric types in python

• Integer x=25

print(type(x))

• Float y=2.5

print(type(y))

• Complex z=25+1j

print(type(z))

(14)

Operators in Python

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Bitwise operators

Special Operators in Python

• Identity operators

• Membership operators

(15)

Arithmetic

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

** Exponentiation

// Floor division

x=5 y=3

print("\n Addition= ",x+y) print("\n Substraction= ",x-y) print("\n Multiplication= ",x*y) print("\n Divsion= ",x/y)

print("\n Reminder= ",x%y) print("\n Exponent= ",x**y) print("\n Floor Division= ",x//y)

(16)

Assignment operators

Operator Example

= x = 5

+= x += 3

-= x -= 3

*= x *= 3

/= x /= 3

%= x %= 3

//= x //= 3

**= x **= 3

&= x &= 3

|= x |= 3

^= x ^= 3

>>= x >>= 3

<<= x <<= 3

(17)

Relational Operators

Operator Name

== Equal

!= Not equal

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

(18)

Logical Operators

Operator Description

and Returns True if both statements are true or Returns True if one of the statements is true

not Reverse the result, returns False if the result is true

(19)

Bitwise Operators

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

Shift left by pushing zeros in from the right and let the leftmost bits fall off

>> Signed right shift

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

(20)

Identity Operators in Python

Operator Description

is Returns true if both variables are the same object is not Returns true if both variables are not the same object

x=25 y=10 z=x

print(z is x ) print(z==x)

x=25 y=25

print(x is not y)

(21)

Membership Operators in Python

Operator Description

in Returns True if a sequence with the specified value is present in the object not in Returns True if a sequence with the specified value is not present in the object str="welcome to c"

print("abc" in str) print("to" in str) print("w" in str)

lst=[25,45,65,78,10,25]

print (25 in lst)

lst=[25,45,65,78,10,25]

print (250 not in lst)

(22)

Collections in Python

• List

• Tuple

• Set

• Dictionaries

(23)

Lists in Python

• Python uses lists, tuple, set and dictionary data types to store collections of data.

• Lists are used to store multiple items in a single variable.

• Lists are created using square bracket.

• List items are indexed, the first item has index [0], the second item has index [1] etc.

• Ordered: When we say that 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.

• Allow Duplicates: Since lists are indexed, lists can have items with the same value.

<class 'list'>

['Hindi', 'Marathi', 'Urdu', 'English', 'Sanskrit', 'Arabic']

languages=["Hindi","Marathi","Urdu", "English", "Sanskrit", "Arabic"]

print(type(languages))

(24)

List Items - Data Types

colors=["red","green","blue"]

temp=[25.20,45.32,59.63]

size=[20,40,30,30]

person=["Azad",69,"Educationist",59.20]

print("\n",colors,"\n",temp,"\n",size,"\n",person)

['red', 'green', 'blue']

[25.2, 45.32, 59.63]

[20, 40, 30, 30]

['Azad', 69, 'Educationist', 59.2]

(25)

List constructor

Students = list(("Aarif","Mujahid","Sajid","Gazi","Ali")) print(students)

['Aarif', 'Mujahid', 'Sajid', 'Gazi', 'Ali']

(26)

Accessing List elements (Indexing)

color=["White","Grey","Blue","Green","Orange","Yellow"]

print(color) print(color[0]) print(color[-1]) print(color[-4]) print(color[:3]) print(color[2:]) print(color[2:5]) print(color[1:4]) print(color[-1]) print(color[-4:-1])

['White', 'Grey', 'Blue', 'Green', 'Orange', 'Yellow']

White Yellow Blue

['White', 'Grey', 'Blue']

['Blue', 'Green', 'Orange', 'Yellow']

['Blue', 'Green', 'Orange']

['Grey', 'Blue', 'Green']

Yellow

['Blue', 'Green', 'Orange']

(27)

Change list items

colors=list(("red", "green", "blue", "orange", "purple")) print(colors)

colors[0]="White"

print(colors)

colors[1:3]=["Black"]

print(colors)

colors[0:1]=["Pink", "Magenta"]

print(colors)

colors[4]=["Sky blue", "Navy Blue", "Light Blue", "Teal"]

print(colors)

colors[-1]="Cyan"

print(colors)

colors[-3:-1]=["Yellow","Brown"]

['red', 'green', 'blue', 'orange', 'purple']

['White', 'green', 'blue', 'orange', 'purple']

['White', 'Black', 'orange', 'purple']

['Pink', 'Magenta', 'Black', 'orange', 'purple']

['Pink', 'Magenta', 'Black', 'orange', ['Skyblue', 'Navy Blue', 'Light Blue', 'Teal']]

['Pink', 'Magenta', 'Black', 'orange', 'Cyan']

['Pink', 'Magenta', 'Yellow', 'Brown', 'Cyan']

(28)

The insert method

• To insert a new list item, without replacing any of the existing values, we can use the insert() method.

• The insert() method inserts an item at the specified index:

colors=list(("red","green","blue","orange","purple")) print(colors)

colors.insert(1,"Brown") print(colors)

colors.insert(-4,"Pink") print(colors)

colors.insert(2,["Yellow","Cyan"]) print(colors)

['red', 'green', 'blue', 'orange', 'purple']

['red', 'Brown', 'green', 'blue', 'orange', 'purple']

['red', 'Brown', 'Pink', 'green', 'blue', 'orange', 'purple']

['red', 'Brown', ['Yellow', 'Cyan'], 'Pink', 'green', 'blue', 'orange', 'purple']

(29)

The append method

• To add an item to the end of the list, use the append() method

colors=list(("red","green","blue","orange","purple")) print(colors)

colors.append("Yellow") print(colors)

colors.append(["Yellow","Brown","Pink"]) print(colors)

['red', 'green', 'blue', 'orange', 'purple']

['red', 'green', 'blue', 'orange', 'purple', 'Yellow']

['red', 'green', 'blue', 'orange', 'purple', 'Yellow', ['Yellow', 'Brown', 'Pink']]

(30)

Extend List

• To append elements from another list to the current list, use the extend() method.

colors=list(("red","green","blue","orange","purple")) print(colors)

shapes=["circle","square","rectangle","hexagon","pentagon"]

print(shapes)

colors.extend(shapes) print(colors)

colors.extend(["icolices triangle","right angled triangle"]) print(colors)

['red', 'green', 'blue', 'orange', 'purple']

['circle', 'square', 'rectangle', 'hexagon', 'pentagon']

['red', 'green', 'blue', 'orange', 'purple', 'circle', 'square',

'rectangle', 'hexagon', 'pentagon']

['red', 'green', 'blue', 'orange', 'purple', 'circle', 'square',

'rectangle', 'hexagon', 'pentagon', 'icolices triangle', 'right angled

triangle']

(31)

Remove List items

• The pop() method removes the specified item.

colors=list(("red","green","blue","orange","purple")) print(colors)

colors.pop() print(colors) colors.pop(0)

['red', 'green', 'blue', 'orange', 'purple']

['red', 'green', 'blue', 'orange']

['green', 'blue', 'orange']

(32)

Loop through list

colors=list(("red","green","blue","orange","purple")) print(colors)

for i in colors:

print(i)

colors=list(("red","green","blue","orange","purple")) print(colors)

for i in range(5):

print(colors[i])

colors=list(("red","green","blue","orange","purple")) print(colors)

for i in range(len(colors)):

print(i,"....",colors[i])

0 .... red 1 .... green 2 .... blue 3 .... orange 4 .... purple

(33)

Using Remove() to remove item

fruits=list(("Orange","Banana","Apple","Custered Apple", "Pineapple")) print(fruits)

i=0

j=len(fruits) while 1:

if(len(fruits)>0):

print(len(fruits),"\t",fruits) fruits.remove(fruits[i])

['Orange', 'Banana', 'Apple', 'Custer Apple', 'Pineapple']

5 ['Orange', 'Banana', 'Apple', 'Custer Apple', 'Pineapple']

4 ['Banana', 'Apple', 'Custer Apple', 'Pineapple']

3 ['Apple', 'Custer Apple', 'Pineapple']

2 ['Custer Apple', 'Pineapple']

1 ['Pineapple']

(34)

Sort method

colors=list(("red","green","blue","orange","purple")) print(colors)

colors.sort()

print(colors) ['red', 'green', 'blue', 'orange', 'purple']

['blue', 'green', 'orange', 'purple', 'red']

[55, 12, 39, 87, 53, 89]

[12, 39, 53, 55, 87, 89]

marks=[55,12,39,87,53,89]

print(marks) marks.sort() print(marks)

colors.sort(reverse=True) print(colors)

marks.sort(reverse=True) print(marks)

['red', 'purple', 'orange', 'green', 'blue']

[89, 87, 55, 53, 39, 12]

(35)

Python - Copy Lists

1. Use the built-in List method copy() 2. Use of list constructor

fruits=list(("Orange","Banana","Apple","Custer Apple","Pineapple"))

vegs=list(("Spinach","Capsicum","Potato","Tomatto","Brinjal","Cucumber")) print(fruits)

print(vegs)

newfruits=fruits.copy() print(newfruits)

newvegs=list(vegs) print(newvegs)

['Orange', 'Banana', 'Apple', 'Custer Apple', 'Pineapple']

['Spinach', 'Capsicum', 'Potato', 'Tomatto', 'Brinjal', 'Cucumber']

['Orange', 'Banana', 'Apple', 'Custer Apple', 'Pineapple']

['Spinach', 'Capsicum', 'Potato', 'Tomatto', 'Brinjal', 'Cucumber']

(36)

Use of = Assignment operator to copy list

fruits=list(("Orange","Banana","Apple","Custer Apple","Pineapple"))

vegs=list(("Spinach","Capsicum","Potato","Tomatto","Brinjal","Cucumber")) newvegs=vegs

print(newvegs)

print(newvegs)

['Spinach', 'Capsicum', 'Potato', 'Tomatto', 'Brinjal', 'Cucumber']

['Spinach', 'Correindar', 'Capsicum', 'Potato', 'Tomatto', 'Brinjal', 'Cucumber']

(37)

Join Lists

fruits=list(("Orange","Banana","Apple","Pineapple")) vegs=list(("Spinach","Capsicum","Brinjal","Cucumber")) newlist=fruits+vegs

print("1: Use of +\n",newlist) freshlist=[]

for x in fruits:

freshlist.append(x) for x in vegs:

freshlist.append(x)

print("2: Use of Append Method:\n",freshlist);

anotherlist=[]

anotherlist.extend(fruits) anotherlist.extend(vegs)

1: Use of +

['Orange', 'Banana', 'Apple', 'Pineapple', 'Spinach', 'Capsicum', 'Brinjal', 'Cucumber']

2: Use of Append Method:

['Orange', 'Banana', 'Apple', 'Pineapple', 'Spinach', 'Capsicum', 'Brinjal', 'Cucumber']

3: Use of Extend Method:

['Orange', 'Banana', 'Apple', 'Pineapple', 'Spinach', 'Capsicum', 'Brinjal', 'Cucumber']

(38)

More List Methods

clear() Removes all the elements from the list

count() Returns the number of elements with the specified value

index() Returns the index of the first element with the specified value

reverse() Reverses the order of the list

fruits=list(("Orange","Banana","Apple","Pineapple"))

vegs=list(("Spinach","Capsicum","Brinjal","Cucumber","Spinach")) fruits.clear()

print(fruits)

print(vegs.count("Spinach"))

print(vegs.index("Spinach")) vegs.reverse()

print(vegs)

[]

2 0

['Spinach', 'Cucumber', 'Brinjal', 'Capsicum', 'Spinach']

(39)

Tuples

• Tuples are used to store multiple items in a single variable.

• A tuple is ordered, unchangeable and allow duplicates.

• Tuples are written in round brackets

shapes=("Circle","Square","Rectangle","Triangle") print(shapes)

('Circle', 'Square', 'Rectangle', 'Triangle')

lines=tuple(("solid","dashed","dotted","dot-dashes"))

print(lines) ('solid', 'dashed', 'dotted', 'dot-dashes')

print(len(lines)) 4

(40)

Single Element tuple

color=("Red") print(type(color))

rainbow=("Voilet","Indigo","Blue","Green","Yellow","Orange","Red") print(type(rainbow))

colors=("Red",) print(type(colors))

<class 'str'>

<class 'tuple'>

<class 'tuple'>

(41)

Tuple item Data types

(True, False, True, True, False)

<class 'bool'>

(48.52, 65.36, 45.5, 85.32, 49.62)

<class 'float'>

(1, 'Zubair', 58.62, True, 'First Class')

<class 'int'>

<class 'str'>

<class 'float'>

<class 'bool'>

attendance=(True, False, True, True, False) print(attendance)

print(type(attendance[0]))

percent=(48.52,65.36,45.50,85.32,49.62) print(percent)

print(type(percent[0]))

personalInfo=(1,"Zubair",58.62,True,"First Class") print(personalInfo)

for x in personalInfo:

print(type(x))

(42)

Access Tuple elements

cities=("Mumbai","Pune","Nagpur","Aurangabad","Amravati","Nashik") print(cities)

print(cities[0]) print(cities[:2]) print(cities[:-1]) print(cities[1:3]) print(cities[-4:-1])

('Mumbai', 'Pune', 'Nagpur', 'Aurangabad', 'Amravati', 'Nashik') Mumbai

('Mumbai', 'Pune')

('Mumbai', 'Pune', 'Nagpur', 'Aurangabad', 'Amravati') ('Pune', 'Nagpur')

('Nagpur', 'Aurangabad', 'Amravati')

(43)

Change the tuple elements

• You cannot change the tuple elements directly, you have to convert the tuple into a list and then re convert the list into a tuple.

colors=("pink","orange","yellow") print(colors)

print(type(colors)) lst=list(colors) print(lst)

print(type(lst))

lst.insert(1,"Brown") lst.insert(1,"Purple") lst.insert(1,"Orange") print(lst)

colors=tuple(lst) print(colors)

Converted a tuple into a list

Converted the list back into a Change the list

items

('pink', 'orange', 'yellow')

<class 'tuple'>

['pink', 'orange', 'yellow']

<class 'list'>

['pink', 'Orange', 'Purple', 'Brown', 'orange', 'yellow']

('pink', 'Orange', 'Purple', 'Brown', 'orange', 'yellow')

<class 'tuple'>

(44)

Append elements in a tuple

colors = ("Red","Green","Orange","Yellow") print("Actual Tuple : ",colors)

#colors.append("Blue") not supported colors=list(colors)

colors.append("Blue") colors=tuple(colors)

print("New Tuple : ",colors)

Actual Tuple : ('Red', 'Green', 'Orange', 'Yellow')

New Tuple : ('Red', 'Green', 'Orange', 'Yellow', 'Blue')

(45)

Remove Tuple elements

• Tuples are unchangeable, so you cannot remove items from it, but we can

convert tuples into list and then remove items from tuple and re convert the list into a tuple.

subjects=tuple(("english","hindi","marathi","urdu",)) print(subjects)

newsubs=list(subjects)

newsubs.remove("english") subjects=tuple(newsubs) print(subjects)

('english', 'hindi', 'marathi', 'urdu')

('hindi', 'marathi', 'urdu')

(46)

Delete the tuple

• The del keyword can delete the tuple completely:

subjects = ("maths1", "physics", "chemistry", "Statistics") del subjects

print(subjects) NameError: name 'subjects' is not defined

(47)

Unpack Tupple

collegeInfo=("SESCOE",1983,"B Plus",516) print(collegeInfo)

(name,date,grade,code)=collegeInfo print(name)

print(date) print(grade) print(code)

('SESCOE', 1983, 'B Plus', 516)

SESCOE 1983 B Plus 516

(48)

Using Asterisk*

• If the number of variables is less than the number of values, we can add an * to the variable name and the values will be assigned to the variable as a list

colors=("red","green","orange","yellow","pink","purple") print(colors)

(c1,c2,*c3)=colors print(c1)

print(c2) print(c3)

('red', 'green', 'orange', 'yellow', 'pink', 'purple')

red green

['orange', 'yellow', 'pink', 'purple']

(c1,*c2,c3)=colors print(c1)

print(c2) print(c3)

red

['green', 'orange', 'yellow', 'pink']

purple

(49)

Looping through tuples

colors=("red","green","orange","yellow","pink","purple") print("By using for loop")

for x in colors:

print(x)

print("\nBy using while loop") i=0

while(i<len(colors)):

print(colors[i]) i+=1

By using for loop red

green orange yellow pink purple

By using while loop red

green orange yellow pink

(50)

Join and multiple tuples

colors=("red","green","orange","yellow","pink","purple") fruits=("apple","orange","mango","banana")

newtuple=colors+fruits print(newtuple)

print(fruits*2)

('red', 'green', 'orange', 'yellow', 'pink', 'purple', 'apple', 'orange', 'mango', 'banana') ('apple', 'orange', 'mango', 'banana', 'apple', 'orange', 'mango', 'banana')

(51)

Count and index

fruits=("apple","orange","mango","banana") allfruits=fruits*2

print(allfruits)

print(allfruits.count("apple")) print(allfruits.index("apple"))

('apple', 'orange', 'mango', 'banana', 'apple', 'orange', 'mango', 'banana') 2

0

(52)

Sets

• Sets are used to store multiple items in a single variable.

• Sets are unordered, unchangeable, unindexed and do not allow duplicates.

• Sets are written with curly brackets.

colors={"red","green","blue"}

print(colors)

print(type(colors))

{'red', 'green', 'blue'}

<class 'set'>

grades=set(("A","B","C","A")) print(grades)

print(type(grades))

{'B', 'A', 'C'}

<class 'set'>

(53)

Set Elements Data Type

students={"Mahfooz","Isaar","Sachin","Vaibhav"}

result={False,True}

marks={65,30,52,65}

for x in students:

print(x,type(x)) print("\n")

for y in result:

print(y,type(y)) print("\n")

for z in students:

Isaar <class 'str'>

Sachin <class 'str'>

Mahfooz <class 'str'>

Vaibhav <class 'str'>

False <class 'bool'>

True <class 'bool'>

Isaar <class 'str'>

Sachin <class 'str'>

Mahfooz <class 'str'>

Vaibhav <class 'str'>

(54)

Sets are unordered

grades=set(("A","B","C","D"))

marks=set((25,66,88,55,62,70,65)) print(grades)

print("C" in grades) y=66

print("\n\n") for x in marks:

if(x==y):

print(y,"is Present ") else:

print(y,"is not Present ",x)

{'B', 'C', 'D', 'A'}

True

66 is not Present 65 66 is Present

66 is not Present 70 66 is not Present 55 66 is not Present 88 66 is not Present 25 66 is not Present 62

(55)

Add an element in set

cities={"Mumbai","Pune","Nasik","Aurangabad","Nagpur"}

cities.add("Amravati") cities.add("Malegaon") print(cities)

{'Nasik', 'Malegaon', 'Pune', 'Nagpur', 'Mumbai', 'Amravati', 'Aurangabad'}

Use update method with sets

metros={"Mumbai","Pune","Aurangabad","Nagpur"}

cities={"Nashik","Solarpur","Amravati","Kalyan","Thane","Ratnagri"}

metros.update(cities) print(metros)

(56)

Add a list to a Set

metros={"Mumbai","Pune","Aurangabad","Nagpur"}

cities=["Nashik","Solarpur","Amravati","Kalyan","Thane","Ratnagri","Nashik"]

metros.update(cities) print(metros)

for x in cities:

metros.add(x) print(metros)

{'Solarpur', 'Nashik', 'Aurangabad', 'Amravati', 'Kalyan', 'Nagpur', 'Pune', 'Thane', 'Mumbai', 'Ratnagri'}

{'Solarpur', 'Nashik', 'Aurangabad', 'Amravati', 'Kalyan', 'Nagpur', 'Pune', 'Thane', 'Mumbai', 'Ratnagri', 'Dhule'}

(57)

Remove, discard and pop

metros={"Mumbai","Pune","Aurangabad","Nagpur"}

metros.remove("Pune") print(metros)

#metros.add("Pune")

#metros.remove("Pune") Will generate an error metros.discard("Nagpur")

print(metros)

#metros.discard("Nagpur") Will not Generate an error

metros.add("Pune") metros.add("Nashik") print(metros)

metros.pop() print(metros)

{'Nagpur', 'Mumbai', 'Aurangabad'}

{'Mumbai', 'Aurangabad'}

{'Aurangabad', 'Mumbai', 'Nashik', 'Pune'}

Generates Error if item not present

Will not Generate an Error if item not present

(58)

mycities={"Mumbai","Pune","Aurangabad","Nagpur"};

i=len(mycities) while i>0:

print(mycities) mycities.pop() i-=1

POP an item from a set

{'Nagpur', 'Mumbai', 'Aurangabad', 'Pune'}

{'Mumbai', 'Aurangabad', 'Pune'}

{'Aurangabad', 'Pune'}

{'Pune'}

(59)

Clear, del

metros={"Mumbai","Pune","Aurangabad","Nagpur"}

cities={"Nashik","Mumbai","Amravati"}

metros.clear() print(metros) del(cities)

print(cities) # Generates Error!

set()

(60)

Join sets

numbers={"One","Two","Three","Four"}

print(numbers) nums={1,2,3,4,5}

print(nums)

Allnums=numbers.union(nums) print(Allnums)

{'Three', 'Four', 'One', 'Two'}

{1, 2, 3, 4, 5}

{1, 2, 3, 4, 5, 'Three', 'Four', 'Two', 'One'}

numbers={"One","Two","Three","Four"}

print(numbers) nums={1,2,3,4,5}

print(nums)

numbers.update(nums) print(numbers)

{'Two', 'One', 'Three', 'Four'}

{1, 2, 3, 4, 5}

{1, 2, 3, 4, 5, 'Four', 'Three', 'Two', 'One'}

(61)

Intersection Duplicates

numbers={1,3,5,6,7}

print(numbers) nums={1,2,3,4,5}

print(nums)

numbers.intersection_update(nums) print(numbers)

{1, 3, 5, 6, 7}

{1, 2, 3, 4, 5}

{1, 3, 5}

numbers={1,3,5,6,7}

print(numbers) nums={1,2,3,4,5}

print(nums)

newnums=numbers.intersection(nums)

{1, 3, 5, 6, 7}

{1, 2, 3, 4, 5}

{1, 3, 5}

(62)

Keep All but not duplicates

set1={25,10,36,45,63,30}

set2={52,66,33,45,25,30}

set1.symmetric_difference_update(set2) print(set1)

{66, 10, 33, 36, 52, 63}

Intersection

set1={25,10,36,45,63,30}

set2={52,66,33,45,25,30}

set3=set1.intersection(set2) print(set3)

{25, 45, 30}

(63)

Copy, difference and Difference Update

set1={25,10,36,45,63,30}

set2={52,66,33,45,25,30}

s3=set1.copy() print(s3)

s3=set1.difference(set2) print(s3)

set1.difference_update(set2) print(set1)

{36, 25, 10, 45, 30, 63}

{10, 36, 63}

{36, 10, 63}

(64)

Python dictionaries

• Dictionaries are used to store data in key:value pairs.

• Dictionaries are ordered*, changeable and does not allow duplicates

• Dictionaries are written in curly brackets with key:value pairs

students={

"Mubashhir":450,

"Mujahid":542,

"Monis":358,

"Ziya":420 }

print(students)

staff=dict(Name='Zubair', ID=123,

City='Mumbai',

Education='Graduate' )

print(staff)

{'Mubashhir': 450, 'Mujahid': 542, 'Monis': 358, 'Ziya': 420}

{'Name': 'Zubair', 'ID': 123, 'City': 'Mumbai', 'Education': 'Graduate'}

(65)

Get keys from dictionary

students={

"Mubashhir":450,

"Mujahid":542,

"Monis":358,

"Ziya":420 }

print(students)

for x in students:

print(x)

{'Mubashhir': 450, 'Mujahid': 542, 'Monis': 358, 'Ziya': 420}

Mubashhir Mujahid Monis Ziya

(66)

Get Values from dictionary

students={

"Mubashhir":450,

"Mujahid":542,

"Monis":358,

"Ziya":420 }

print(students)

for x in students:

print(students[x])

{'Mubashhir': 450, 'Mujahid': 542, 'Monis': 358, 'Ziya': 420}

450 542 358 420

(67)

Loop through a dictionary

students={

"Mubashhir":450,

"Mujahid":542,

"Monis":358,

"Ziya":420 }

print(students) for x in students:

print(x,":",students[x])

{'Mubashhir': 450, 'Mujahid': 542, 'Monis': 358, 'Ziya': 420}

Mubashhir : 450 Mujahid : 542 Monis : 358 Ziya : 420

(68)

Change a Value

• You can change the value of a specific item by referring to its key name.

students={

"Mubashhir":450,

"Mujahid":542,

"Monis":358,

"Ziya":420 }

print(students)

students["Ziya"]=520 print(students)

{'Mubashhir': 450, 'Mujahid': 542, 'Monis': 358, 'Ziya': 420}

{'Mubashhir': 450, 'Mujahid': 542, 'Monis': 358, 'Ziya': 520}

(69)

Accessing items by using get(),keys() and values() method

get() method:

students={"Laxman":46,

"Rahul":45,

"Irfan":36,

"Sachin":45,

"Yuraj":38 }

print(students)

x=students.get("Yuraj") print(x)

for x in students:

print(students.get(x))

{'Laxman': 46, 'Rahul': 45, 'Irfan': 36, 'Sachin': 45, 'Yuraj': 38}

38 46 45 36 45 38

print(students.keys()) print(students.values())

dict_keys(['Laxman', 'Rahul', 'Irfan', 'Sachin', 'Yuraj']) dict_values([46, 45, 36, 45, 38])

(70)

Add items to the dictionary

cities={

"Malegaon":450,

"Nashik":752,

"Pune":132,

"Aurangabad":423 }

print(cities)

cities["Nagpur"]=250 print(cities)

{'Malegaon': 450, 'Nashik': 752, 'Pune': 132, 'Aurangabad': 423}

{'Malegaon': 450, 'Nashik': 752, 'Pune': 132, 'Aurangabad': 423, 'Nagpur': 250}

cities.update({"Satara":123}) print(cities)

{'Malegaon': 450, 'Nashik': 752, 'Pune': 132, 'Aurangabad': 423, 'Nagpur': 250, 'Satara': 123}

(71)

Remove Item

cities={

"Malegaon":450,

"Nashik":752,

"Pune":132,

"Aurangabad":423 }

print(cities)

cities.pop("Pune") print(cities)

cities.popitem()

{'Malegaon': 450, 'Nashik': 752, 'Pune': 132, 'Aurangabad': 423}

{'Malegaon': 450, 'Nashik': 752, 'Aurangabad': 423}

{'Malegaon': 450, 'Nashik': 752}

(72)

Del and Clear

cities={

"Malegaon":450,

"Nashik":752,

"Pune":132,

"Aurangabad":423 }

mcities={

"Malegaon":450,

"Nashik":752,

"Pune":132,

"Aurangabad":423 }

print(mcities) del (mcities)

#print(mcities) cities.clear() print(cities)

{'Malegaon': 450, 'Nashik': 752, 'Pune': 132, 'Aurangabad': 423}

{}

(73)

Loop through dictionaries

{'Malegaon': 450, 'Nashik': 752, 'Pune': 132, 'Aurangabad': 423}

Display default Malegaon Nashik Pune

Aurangabad Display keys Malegaon Nashik Pune

Aurangabad Display Values 450

752 132 423

Display items ('Malegaon', 450) ('Nashik', 752) ('Pune', 132)

('Aurangabad', 423) mcities={

"Malegaon":450,

"Nashik":752,

"Pune":132,

"Aurangabad":423 }

print(mcities)

print("\nDisplay default ") for x in mcities:

print(x)

print("\nDisplay keys ") for x in cities.keys():

print(x)

print("\nDisplay Values ") for x in cities.values():

print(x)

print("\nDisplay items”) for x in cities.items():

print(x)

(74)

Copy a dictionary

marks={"Maths":45,"Physics":65,"Chemistry":40,"Biology":59}

print(marks)

'''copying by using = to will add a reference to the source dictionary, any chnages ,made in the source will be reflected in the distination'''

newmarks=marks print(newmarks)

marks["Geography"]=56 print(newmarks)

''' Copy by using constructor

The new dictionary is created , any chnages made in the source will not be reflected in the destination

'''

marksdata=dict(marks) print(marksdata)

marks.popitem() print(marks) print(marksdata)

{'Maths': 45, 'Physics': 65, 'Chemistry': 40, 'Biology': 59}

{'Maths': 45, 'Physics': 65, 'Chemistry': 40, 'Biology': 59}

{'Maths': 45, 'Physics': 65, 'Chemistry': 40, 'Biology': 59, 'Geography': 56}

{'Maths': 45, 'Physics': 65, 'Chemistry': 40, 'Biology': 59, 'Geography': 56}

{'Maths': 45, 'Physics': 65, 'Chemistry': 40, 'Biology': 59}

{'Maths': 45, 'Physics': 65, 'Chemistry': 40, 'Biology': 59, 'Geography': 56}

(75)

Nested Dictionaries

students={

"Student1":{"Name":"Ali","Roll":4,"Class":1},

"Student2":{"Name":"Umar","Roll":2,"Class":1},

"Student":{"Name":"Usman","Roll":3,"Class":1}, }

print(students)

for i in students.items():

print(i)

''' Another way of creating nested dictionary'''

state1={"Name":"Maharashtra","CapitaIncome":52500,"Rank":2}

state2={"Name":"Kerala","CapitaIncome":54500,"Rank":1}

state3={"Name":"Gujrath","CapitaIncome":46500,"Rank":4}

state4={"Name":"Punjab","CapitaIncome":49000,"Rank":2}

country={"s1":state1,"s2":state2,"s3":state3,"s4":state4}

print(country)

for i in country.items():

{'Student1': {'Name': 'Ali', 'Roll': 4, 'Class': 1}, 'Student2': {'Name': 'Umar', 'Roll': 2, 'Class': 1}, 'Student': {'Name': 'Usman', 'Roll': 3, 'Class': 1}}

('Student1', {'Name': 'Ali', 'Roll': 4, 'Class': 1}) ('Student2', {'Name': 'Umar', 'Roll': 2, 'Class': 1}) ('Student', {'Name': 'Usman', 'Roll': 3, 'Class': 1})

{'s1': {'Name': 'Maharashtra', 'CapitaIncome': 52500, 'Rank': 2}, 's2': {'Name':

'Kerala', 'CapitaIncome': 54500, 'Rank': 1}, 's3': {'Name': 'Gujrath',

'CapitaIncome': 46500, 'Rank': 4}, 's4': {'Name': 'Punjab', 'CapitaIncome':

49000, 'Rank': 2}}

('s1', {'Name': 'Maharashtra', 'CapitaIncome': 52500, 'Rank': 2}) ('s2', {'Name': 'Kerala', 'CapitaIncome': 54500, 'Rank': 1})

('s3', {'Name': 'Gujrath', 'CapitaIncome': 46500, 'Rank': 4}) ('s4', {'Name': 'Punjab', 'CapitaIncome': 49000, 'Rank': 2})

(76)

Collections in Python

Lists Tuples Sets Dictionaries

indexed ordered changeable

duplicates

indexed ordered unchangeable

duplicates

unindexed unordered unchangeable

no duplicates

keyed ordered changeable no duplicates

(77)

Control Statement

• If else

• While

• for

(78)

If else

Syntax:

If(condition):

One or more python statements else:

One or more python statements indent

marks=[25,44,55,66,33,22]

x=250

if x in marks:

print(x," is present ") else:

print(x," is not present ")

250 is not present

(79)

Short Forms

x=25 y=15

if(x>y):print(x," is larger ")

print(x," is larger ") if(x>y) else print(y," is larger ")

25 is larger

25 is larger

(80)

If elif else

data=list((705,10,22,33,55,55,20)) print(data)

x=25 y=75

if x in data:

print(x," is present ") elif y in data:

print(y," is present ") else:

print("Nothing present ")

[705, 10, 22, 33, 55, 55, 20]

Nothing present

(81)

Nested if else

ch=input("Enter a character: ")

x=ord(ch)

if (x>=65 and x<=90) or (x>=97 and x<=122):

if(x>=65 and x<=90):

print("Uppercase Alphabet ") else:

print("Lowercase Alphabet ") else:

if(x>=48 and x<=57):

print("Numeric Character ") else:

print("Symbolic Character ") print("ASCII Value: ",x)

Enter a character: ^ Symbolic Character ASCII Value: 94

(82)

Python while loop

Syntax:

Initialize loop counter;

while condition:

one or more python statements increment/decrement loop counter;

Example:

i=0

while i<5:

print(i, "Square = ",i*i) i+=1

0 Square = 0 1 Square = 1 2 Square = 4 3 Square = 9 4 Square = 16

(83)

Continue and break statements

print("The break statement will stop further execution of the loop ")

i = 0

while i < 10:

i += 1 if i == 3:

break print(i)

print("The continue statement will stop the current iteration and begin execution from next iteration ") i = 0

while i < 10:

i += 1 if i == 3:

continue

The break statement will stop further execution of the loop 1

2

The continue statement will stop the current iteration and begin execution from next iteration

1 2 4 5 6 7 8 9 10

(84)

While loop with else statement

i=0

while i<10:

print(i) i+=1 else:

print("The loop terminated at ",i)

0 1 2 3 4 5 6 7 8 9

The loop terminated at 10

(85)

For loop

• The for loop works like an iterator

• It is mostly used to access the elements from collections (list, tuple, set, dictionary)

marks1=[25,44,52,63,10]

marks2=(52,33,52,102,20) marks3={25,66,85,63,30}

student1={"Name":"Aarif","Age":18,"Gender":"M"}

print("Access list ") for x in marks1:

print(x)

print("Access Tuple ") for x in marks2:

print(x)

print("Access Set ") for x in marks3:

print(x)

print("Access Dictionary ") for x in student1:

print(x,":",student1[x])

Access list 25

44 52 63 10

Access Tuple 52

33 52 102 20

Access Set 66

85 25 30 63

Access Dictionary Name : Aarif Age : 18 Gender : M

(86)

For loop through a string

str1="Python"

mystr="Python Object Oriented Programming Language"

for x in str1:

print(x)

print("Split String a Spaces ") for x in mystr.split():

print(x)

P y t h o n

Split String a Spaces Python

Object Oriented

Programming Language

(87)

Break and continue in for

for x in ["Red","Green","Orange","Yellow","Blue"]:

print(x)

print("the break")

for x in ["Red","Green","Orange","Yellow","Blue"]:

if x=="Orange":

break print(x)

print("the continue")

for x in ["Red","Green","Orange","Yellow","Blue"]:

if x=="Orange":

continue print(x)

Red Green Orange Yellow Blue

the break Red

Green

the continue Red

Green Yellow Blue

(88)

For with range() function

print("With Only One Parameter ") for x in range(6):

print(x)

print("With Two Parameters ") for x in range(10,15):

print(x)

print("With Three Parameters ") for x in range(10,20,2):

print(x)

With Only One Parameter 0

1 2 3 4 5

With Two Parameters 10

11 12 13 14

With Three Parameters 10

12 14 16 18

(89)

Else in for loop

print("With Only One Parameter ") for x in range(6):

print(x) else:

print("Loop Stopped at ",x)

With Only One Parameter 0

1 2 3 4 5

Loop Stopped at 5

(90)

Nested for loop

print("Main Loop ")

for x in ["One","Two","Three"]:

print(x) for y in x:

print("\t",y)

One

O n e Two

T w o Three

T h r e e

(91)

Python Functions

• Functions are self contained block of statements, which perform an action when called.

• We can pass data (parameters) to a functions

• A function can return data as well

Body of a Function

Parameters Return value

(92)

Functions in Python

• Function Definition: A functions is defined by using the keyword def def myfunc():

print(“welcome to a function”)

• Calling a function: A Function performs an action, only when it is called. To call a function use the function name followed by parenthesis

myfunc()

• Arguments: The functions may receive arguments. These arguments are passed to the function while calling. The arguments are separated by comma (,)

def myfunc(n):

for i in range(n):

print("welcome") myfunc(3)

myfunc(5)

welcome welcome welcome

welcome welcome welcome welcome welcome

(93)

Functions with more than one arguments

def fullname(f, l):

print(f,“ ",l)

fname=input("Enter First Name ") lname=input("Enter Last Name ") fullname(fname, lname)

Enter First Name Shoaeb Enter Last Name Ansari Shoaeb Ansari

Arguments

(94)

Return Values

def total(x):

t=0

for i in x:

t=t+i return t def high(a):

a=list(a);

m=a[0]

for i in range(1,len(a)):

if(m<a[i]):

m=a[i]

return m l1=[1,2,3,4,5,6]

print("total of List = ",total(l1)) t1=(25,26,35,41)

print("total of Tuple elements =",total(t1)) s1={52,33,20,44,55}

print(high(s1))

total of List = 21

total of Tuple elements = 127 55

(95)

Passing a list, tuple, set or dictionary as argument

def display(x):

for i in x:

print(i)

l1=[45,66,62,12,32,10]

display(l1)

t1=(25,63,42,22,35) display(t1)

s1={10,25,63,85,60}

display(s1)

d1={"Red":25,"Green":45,"Blue":58};

display(d1)

List:

45 66 62 12 32 10 Tuple:

25 63 42 22 35 Set:

85 25 10 60 63

Dictionary:

Red Green Blue

(96)

Arbitrary Arguments

• If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.

• This way the function will receive a tuple of arguments

def students(*s):

print(s)

students("Ali","Danish","Faheem","Sachin","Bhushan","Abhishek",45,66,33,55,44)

(97)

Keyword argument

def employees(emp1,emp2,emp3):

if(emp1>emp2 and emp1>emp3):

print("First Employee Is Elder than others ") elif(emp2>emp1 and emp2>emp3):

print("Second Employee Is Elder than others ") else:

print("Third Employee Is Elder than others ")

employees(emp1=25,emp2=50,emp3=20)

Second Employee Is Elder than others

(98)

Arbitrary keyword arguments **kwargs

• If you 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

def disp(**emp):

print(emp)

disp(Ali=85,Ahmad=95,Abhishek=58,Bhushan=50,Shahid=50,Sachin=28)

{'Ali': 85, 'Ahmad': 95, 'Abhishek': 58, 'Bhushan': 50, 'Shahid': 50, 'Sachin': 28}

References

Related documents

While there are multiples seminars and workshops offered each year dealing either with engineering aspects of high potent manu- facturing or OEL categorization and monitoring of

Wavelet packet decomposition splits an input time series into approximation and detail components, and the decomposed time series are used as inputs to artificial neural network

Aplikasi network monitoring bertugas mengumpulkan statistik jaringan untuk beberapa kebutuhan seperti pelacakan flow dan jaringan dengan statistik paket yang luas ataupun juga

• Allow contractor staff performing the assessment to be available to the UTILITIES’ staff with interpretation and clarification of assessment report findings not to exceed 10

Mr A Rajagopal is an Information Technology Manager and Coordinator at Clinical Data Management Centre, Department of Biostatistics, Christian Medical College, Vellore. His area

Di dalam ketentuan mengenai fidusia sebagaimana diatur dalam Undang-Undang No. 42 Tahun 1999 tentang Jaminan Fidusia. Hak Cipta telah diakomodir sebagai objek jaminan melalui

• How are law firms affected by trends such as digitalisation of legal information, commodisation, e-matter management, integration of systems, convergence, globalisation and rise

The OWCP brought attention to the contextual elements of and curatorial strategies behind museum displays, and it made them relevant and intelligible through the appropriation