Python Tutorials (NC)
Ghafar Ahmadi
March, 12,2024
Contents
1 Chapter 1
1.1 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 Python Basics: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3 Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.4 Python Conditions and If statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5 Python Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.6 Python Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.7 Python Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.8 math and cmath modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.9 numpy module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
2
2
2
4
4
5
7
20
21
22
1 Chapter 1
1.1 What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
1. web development (server-side),
2. software development,
3. mathematics,
4. system scripting.
What Can Python Do?
1. Python can be used on a server to create web applications.
2. Python can be used alongside software to create workflows.
3. Python can connect to database systems. It can also read and modify files.
4. Python can be used to handle big data and perform complex mathematics.
5. Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
1. Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
2. Python has a simple syntax similar to the English language.
3. Python has syntax that allows developers to write programs with fewer lines than some other programming
languages.
4. 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.
1.2 Python Basics:
Note 1. Start the python interpreter by one of the following ways:
1. Spyder IDE
2. Jupiter Notebook (or other IDE like PyCharm)
3. Python IDE
Note 2. Comments starts with a #, and Python will ignore them and do not execute it.
# This is an example of python c o m m e n t s .
print ( " Hello , Every One " )
Hello, Every One
Creating Variables in Python:
1. A variable is created the moment you first assign a value to it.
2. It is used to store values and make calculations easy.
Kinds of Python’s Variable:
1. Statics: It is constant and you can change it manually.
2. Dynamics: In Every run it want’s you to update it’s value. and define by input function.
# Python Statics
x = 49
yo = " Hello "
xx = " a "
Variables
# integer
# Sting
# Character
# Python D y n a m i c s V a r i a b l e s
x = input ( " Please enter a number " )
y = input ( " Please enter a name " )
# integer
# String
2
# You can chose the type of data .
x = int ( 4 )
y = str ( 4 )
# x will be integer
# y will be string
# You can Chose the type of v a r i a b l e at the b e g i n n i n g .
x = input ( int ( " please enter a number " ) )
# x will be integer
y = input ( str ( " Please enter a name " ) )
# y will be string
Rules for Naming Variables: A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total _volume). Rules for Python variables:
1. A variable name must start with a letter or the underscore character
2. A variable name cannot start with a number
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
5. A variable name cannot be any of the Python keywords.
# Example of Python ’s V a r i a b l e Name
myvar = " Well Come "
my_var = " Well Come "
_my_var = " Well Come "
myVar = " Well Come "
MYVAR = " Well Come "
myvar2 = " Well Come "
Python Data Type:
1. Text Type: str
2. Numeric Types: int, float, complex
3. Data Structure: list, tuple, set, dictionary
4. Boolean Type: bool
# Example of Python ’s data type
x
x
x
x
x
x
x
x
x
x
=
=
=
=
=
=
=
=
=
=
" Hello Every One "
# str
20
# int
20 . 5
# float
1j
# complex
[ " apple " , " banana " , " cherry " ]
( " apple " , " banana " , " cherry " )
range ( 6 )
# range
{ " name " : " Ahmad " , " age " : 36 }
{ " apple " , " banana " , " cherry " }
True
# bool
# list
# tuple
# dict
# set
Getting the Data Type: You can get the data type of any object by using the type() function:
# Example
x = 5
print ( type ( x ) )
<class ’int’>
Python Operators: Python Arithmetic Operators
#
*
*
*
*
*
*
*
Example
Addition :
x + y
Subtraction :
x - y
Multipl ication :
x * y
Division :
x / y
Modulus :
x % y
Floor division :
x // y
Exponen tiation :
x ** y
3
Python Comparison Operators:
#
*
*
*
*
*
*
Example
Equal
Not equal
Greater than
Less than
Greater than or equal to
Less than or equal to
x
x
x
x
x
x
== y
!= y
> y
< y
>= y
<= y
1.3 Python Modules
Time, Date and Random Modules in Python:
# At first you should import the module
# time module
import time
x1 = time . strftime ( " % H : % M : % S " )
print ( x1 )
# to delay a p r o g r a m m e use
x2 = time . sleep ( 10 )
# units is in second
# datetime
import datetime
x3 = datetime . date . today ()
print ( x3 )
# Random Number
import random
x4 = random . randint (2 , 20 ) # it g e n e r a t e a random number between 2 , 20
print ( x4 )
15:48:01
2024-04-30
11
1.4 Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
1. Equals: a == b
2. Not Equals: a! = b
3. Less than: a < b
4. Less than or equal to: a <= b
5. Greater than: a > b
6. Greater than or equal to: a >= b
Note 3. Indentation: Python relies on indentation (white space at the beginning of a line) to define scope in the
code.
# an example of c o n d i t i o n a l s t a t e m e n t s
a = 4
b = 3
if b > a :
print ( " b is greater than a " )
# an example of c o n d i t i o n a l s t a t e m e n t s
a = 200
b = 33
if b > a :
print ( " b is greater than a " )
elif a = = b :
print ( " a and b are equal " )
4
else :
print ( " a is greater than b " )
a is greater than b
Nested If: You can have if statements inside if statements, this is called nested if statements.
# an example of nested if
x = 41
if x > 10 :
print ( " Above ten " )
if x > 20 :
print ( " and also above 20 " )
else :
print ( " but not above 20 " )
Above ten
and also above 20
1.5 Python Loops
There are three Python Loops
1. For Loop or definite loop
2. while Loop or indefinite
3. Nested Loop or loop within loop
while loop With the while loop we can execute a set of statements as long as a condition is true.
# example : print i as long as i is less than 6
i = 1
while i < 6 :
print ( i )
i = i + 1
1
2
3
4
5
# example : it prints Hello 6 times
i =1
while i < = 6 :
print ( " Hello " )
i = i + 1
Hello
Hello
Hello
Hello
Hello
Hello
# example : it will sum one to 100
sum = 0
i = 1
while i < = 100 :
sum = sum + i
i = i + 1
5
print ( sum )
5050
for loop A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
# example : it will print all e l e m e n t s in the list bellow
fruits = [ " apple " , " banana " , " cherry " ]
for x in fruits :
print ( x )
apple
banana
cherry
# example : it will print all letters in banana
for x in " banana " :
print ( x )
b
a
n
a
n
a
# example : it will print the number and it ’s squared form 0 to 9
for i in range ( 10 ) :
print (i , i ** 2 )
00
11
24
39
4 16
5 25
6 36
7 49
8 64
9 81
Nested loop
# example :
adj = [ " red " , " big " , " tasty " ]
fruits = [ " apple " , " banana " , " cherry " ]
for x in adj :
for y in fruits :
print (x , y )
6
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
1.6 Python Data Structure
Kinds of Data Structure in Python
1. Lists
2. Tuples
3. Sets
4. Dictionaries
Lists
1. Lists are used to store multiple items in a single variable.
2. 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.
3. Lists are created using square brackets:
# example :
thislist = [ " apple " , " banana " , " cherry " ]
print ( thislist )
[’apple’, ’banana’, ’cherry’]
Note 4. List Items:
1. List items are ordered, changeable, and allow duplicate values.
2. List items are indexed, the first item has index [0], the second item has index [1] etc.
Note 5. Ordered:
1. When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
2. If you add new items to a list, the new items will be placed at the end of the list.
Note 6. Changeable:
1. The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Note 7. Allow Duplicates:
1. Since lists are indexed, lists can have items with the same value:
# example :
thislist = [ " apple " , " banana " , " cherry " , " apple " , " cherry " ]
print ( thislist )
[’apple’, ’banana’, ’cherry’, ’apple’, ’cherry’]
List Length
1. To determine how many items a list has, use the len() function:
7
# example :
thislist = [ " apple " , " banana " , " cherry " ]
print ( len ( thislist ) )
3
Access Items
1. 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 ] )
banana
Range of Indexes
1. You can specify a range of indexes by specifying where to start and where to end the range.
2. 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 ] )
[’cherry’, ’orange’, ’kiwi’]
By leaving out the start value, the range will start at the first item:
# example :
# This example returns the items from the b e g i n n i n g to , but NOT including , " kiwi ":
thislist = [ " apple " , " banana " , " cherry " , " orange " , " kiwi " , " melon " , " mango " ]
print ( thislist [ : 4 ] )
[’apple’, ’banana’, ’cherry’, ’orange’]
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 : ] )
[’cherry’, ’orange’, ’kiwi’, ’melon’, ’mango’]
Change List Items:
1. 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 )
8
[’apple’, ’blackcurrant’, ’cherry’]
Change a Range of Item Values:
1. 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 " b l a c k c u r r a n t " and " w a t e r m e l o n ":
thislist = [ " apple " , " banana " , " cherry " , " orange " , " kiwi " , " mango " ]
thislist [ 1 : 3 ] = [ " blackcurrant " , " watermelon " ]
print ( thislist )
[’apple’, ’blackcurrant’, ’watermelon’, ’orange’, ’kiwi’, ’mango’]
Insert Items
1. To insert a new list item, without replacing any of the existing values, we can use the insert() method.
2. The insert() method inserts an item at the specified index:
# example :
# Insert " w a t e r m e l o n " as the third item :
thislist = [ " apple " , " banana " , " cherry " ]
thislist . insert (2 , " watermelon " )
print ( thislist )
[’apple’, ’banana’, ’watermelon’, ’cherry’]
Add List Items
1. Append Items
2. 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 )
[’apple’, ’banana’, ’cherry’, ’orange’]
Extend List
1. To append elements from another list to the current list, use the extend() method.
# example :
# Add the e l e m e n t s of t r o p i c a l to t h i s l i s t :
thislist = [ " apple " , " banana " , " cherry " ]
tropical = [ " mango " , " pineapple " , " papaya " ]
thislist . extend ( tropical )
print ( thislist )
[’apple’, ’banana’, ’cherry’, ’mango’, ’pineapple’, ’papaya’]
Remove List Items
1. Remove Specified Item
2. The remove() method removes the specified item.
9
# example :
# Remove " banana ":
thislist = [ " apple " , " banana " , " cherry " ]
thislist . remove ( " banana " )
print ( thislist )
[’apple’, ’cherry’]
Note 8. If there are more than one item with the specified value, the remove() method removes the first occurance:
Remove Specified Index
1. The pop() method removes the specified index.
# example :
# Remove the second item :
thislist = [ " apple " , " banana " , " cherry " ]
thislist . pop ( 1 )
print ( thislist )
[’apple’, ’cherry’]
If you do not specify the index, the pop() method removes the last item.
# example :
# Remove the last item :
thislist = [ " apple " , " banana " , " cherry " ]
thislist . pop ()
print ( thislist )
[’apple’, ’banana’]
The del keyword also removes the specified index:.
# example :
# Remove the first item :
thislist = [ " apple " , " banana " , " cherry " ]
del thislist [ 0 ]
print ( thislist )
[’banana’, ’cherry’]
The del keyword can also delete the list completely.
# example :
# Delete the entire list :
thislist = [ " apple " , " banana " , " cherry " ]
del thislist
Clear the List.
1. The clear() method empties the list.
2. The list still remains, but it has no content.
10
# example :
# Clear the list content :
thislist = [ " apple " , " banana " , " cherry " ]
thislist . clear ()
print ( thislist )
[]
Tuple
1. Tuples are used to store multiple items in a single variable.
2. A tuple is a collection which is ordered and unchangeable.
3. Tuples are written with round brackets.
# example :
# Create a Tuple :
thistuple = ( " apple " , " banana " , " cherry " )
print ( thistuple )
(’apple’, ’banana’, ’cherry’)
Note 9. Tuple Items
1. Tuple items are ordered, unchangeable, and allow duplicate values.
2. Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Note 10. Ordered:
1. When we say that tuples are ordered, it means that the items have a defined order, and that order will not
change.
Note 11. Unchangeable:
1. Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Note 12. Allow Duplicates:
1. Since Since tuples are indexed, they can have items with the same value:
# example :
# Tuples allow d u p l i c a t e values :
thistuple = ( " apple " , " banana " , " cherry " , " apple " , " cherry " )
print ( thistuple )
(’apple’, ’banana’, ’cherry’, ’apple’, ’cherry’)
Tuple Length
1. To determine how many items a tuple has, use the len() function:
# example :
# Print the number of items in the tuple :
thistuple = ( " apple " , " banana " , " cherry " )
print ( len ( thistuple ) )
3
Access Tuple Items
1. You can access tuple items by referring to the index number, inside square brackets:
11
# example :
# Print the second item in the tuple :
thistuple = ( " apple " , " banana " , " cherry " )
print ( thistuple [ 1 ] )
banana
Range of Indexes
1. You can specify a range of indexes by specifying where to start and where to end the range.
2. When specifying a range, the return value will be a new tuple with the specified items.
# example :
# Return the third , fourth , and fifth item :
thistuple = ( " apple " , " banana " , " cherry " , " orange " , " kiwi " , " melon " , " mango " )
print ( thistuple [ 2 : 5 ] )
(’cherry’, ’orange’, ’kiwi’)
By leaving out the start value, the range will start at the first item:
# example :
# This example returns the items from the b e g i n n i n g to , but NOT included , " kiwi ":
thistuple = ( " apple " , " banana " , " cherry " , " orange " , " kiwi " , " melon " , " mango " )
print ( thistuple [ : 4 ] )
(’apple’, ’banana’, ’cherry’, ’orange’)
By leaving out the end value, the range will go on to the end of the tuple:
# example :
# This example returns the items from " cherry " and to the end :
thistuple = ( " apple " , " banana " , " cherry " , " orange " , " kiwi " , " melon " , " mango " )
print ( thistuple [ 2 : ] )
(’cherry’, ’orange’, ’kiwi’, ’melon’, ’mango’)
Set
1. Sets are used to store multiple items in a single variable.
2. A set is a collection which is unordered, unchangeable, and unindexed.
3. Sets are written with curly brackets.
# example :
# Create a Set :
thisset = { " apple " , " banana " , " cherry " }
print ( thisset )
’banana’, ’apple’, ’cherry’
Note 13. Set Items
1. Set items are unordered, unchangeable, and do not allow duplicate values.
12
Note 14. Unordered
1. Unordered means that the items in a set do not have a defined order.
2. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Note 15. Unchangeable:
1. Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Note 16. Duplicates Not Allowed:
1. Sets cannot have two items with the same value.
# example :
# D u p l i c a t e values will be ignored :
thisset = { " apple " , " banana " , " cherry " , " apple " }
print ( thisset )
’banana’, ’apple’, ’cherry’
Get the Length of a Set:
1. To determine how many items a set has, use the len() function.
# example :
# Get the number of items in a set :
thisset = { " apple " , " banana " , " cherry " }
print ( len ( thisset ) )
3
Access Items
1. You cannot access items in a set by referring to an index or a key.
2. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.
# example :
# Loop through the set , and print the values :
thisset = { " apple " , " banana " , " cherry " }
for x in thisset :
print ( x )
banana
apple
cherry
Add Items
1. To add one item to a set use the add() method.
# example :
# Add an item to a set , using the add () method :
thisset = { " apple " , " banana " , " cherry " }
thisset . add ( " orange " )
print ( thisset )
13
’orange’, ’banana’, ’apple’, ’cherry’
Add Sets
1. To add items from another set into the current set, use the update() method.
# example :
# Add e l e m e n t s from t r o p i c a l into thisset :
thisset = { " apple " , " banana " , " cherry " }
tropical = { " pineapple " , " mango " , " papaya " }
thisset . update ( tropical )
print ( thisset )
’mango’, ’apple’, ’pineapple’, ’banana’, ’papaya’, ’cherry’
Remove Item:
1. To remove an item in a set, use the remove(), or the discard() method.
# example :
# Remove " banana " by using the remove () method :
# If the item to remove does not exist , remove () will raise an error .
thisset = { " apple " , " banana " , " cherry " }
thisset . remove ( " banana " )
print ( thisset )
’apple’, ’cherry’
# example :
# Remove " banana " by using the discard () method :
# If the item to remove does not exist , discard () will NOT raise an error .
thisset = { " apple " , " banana " , " cherry " }
thisset . discard ( " banana " )
print ( thisset )
’apple’, ’cherry’
1. You can also use the pop() method to remove an item, but this method will remove a random item, so you
cannot be sure what item that gets removed.
2. The return value of the pop() method is the removed item.
# example :
# Remove a random item by using the pop () method :
thisset = { " apple " , " banana " , " cherry " }
x = thisset . pop ()
print ( x )
print ( thisset )
banana
’apple’, ’cherry’
14
# example :
# The clear () method empties the set :
thisset = { " apple " , " banana " , " cherry " }
thisset . clear ()
print ( thisset )
set()
# example :
# The del keyword will delete the set c o m p l e t e l y :
thisset = { " apple " , " banana " , " cherry " }
del thisset
print ( thisset )
————————————————————————— NameError Traceback (most recent call last)
5512077915618.py in <module>
3 del thisset
4 —-> 5 print(thisset)
NameError: name ’thisset’ is not defined
Join Sets There are several ways to join two or more sets in Python.
1. The union() and update() methods joins all items from both sets.
2. The intersection() method keeps ONLY the duplicates.
3. The difference() method keeps the items from the first set that are not in the other set(s).
4. The symmetric_difference() method keeps all items EXCEPT the duplicates.
# example :
# Join m u l t i p l e sets with the union () method :
set1
set2
set3
set4
=
=
=
=
{"a", "b", "c"}
{1 , 2 , 3 }
{ " John " , " Elena " }
{ " apple " , " bananas " , " cherry " }
myset = set1 . union ( set2 , set3 , set4 )
print ( myset )
1, ’c’, 2, 3, ’a’, ’bananas’, ’Elena’, ’apple’, ’John’, ’b’, ’cherry’
Dictionary
1. Dictionaries are used to store data values in key:value pairs.
2. A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
3. Dictionaries are written with curly brackets, and have keys and values:
# example :
# Create and print a d i c t i o n a r y :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
print ( thisdict )
’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964
15
Note 17. Dictionary Items
1. Dictionary items are ordered, changeable, and do not allow duplicates.
2. Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Dictionary Length
1. To determine how many items a dictionary has, use the len() function:
# example :
# Print the number of items in the d i c t i o n a r y :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
print ( len ( thisdict ) )
3
Accessing Items
1. You can access the items of a dictionary by referring to its key name, inside square brackets:
# example :
# Get the value of the " model " key :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
x = thisdict [ " model " ]
print ( x )
Mustang
# example :
# There is also a method called get () that will give you the same result :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
x = thisdict . get ( " model " )
print ( x )
Mustang
Get Keys
1. The keys() method will return a list of all the keys in the dictionary.
# example :
# Get a list of the keys :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
x = thisdict . keys ()
print ( x )
dict_keys([’brand’, ’model’, ’year’])
16
# example :
# The values () method will return a list of all the values in the d i c t i o n a r y .
# Get a list of the values :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
x = thisdict . values ()
print ( x )
dict_values([’Ford’, ’Mustang’, 1964])
Change Values You can change the value of a specific item by referring to its key name:
# example :
# Change the " year " to 2018 :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
thisdict [ " year " ] = 2018
print ( thisdict )
’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 2018
Update Dictionary
1. The update() method will update the dictionary with the items from the given argument.
2. The argument must be a dictionary, or an iterable object with key:value pairs.
# example :
# Update the " year " of the car by using the update () method :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
thisdict . update ( { " year " : 2020 } )
print ( thisdict )
’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 2020
Note 18. Adding Items
1. Adding an item to the dictionary is done by using a new index key and assigning a value to it:
# example :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
thisdict [ " color " ] = " red "
print ( thisdict )
’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964, ’color’: ’red’
17
Removing Items
1. There are several methods to remove items from a dictionary:
# example :
# The pop () method removes the item with the s p e c i f i e d key name :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
thisdict . pop ( " model " )
print ( thisdict )
’brand’: ’Ford’, ’year’: 1964
# example :
# The del keyword removes the item with the s p e c i f i e d key name :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
del thisdict [ " model " ]
print ( thisdict )
’brand’: ’Ford’, ’year’: 1964
# example :
# The clear () method empties the d i c t i o n a r y :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
thisdict . clear ()
print ( thisdict )
Loop Through a Dictionary You can change the value of a specific item by referring to its key name:
1. You can loop through a dictionary by using a for loop.
# example :
# Print all key names in the dictionary , one by one :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
for x in thisdict :
print ( x )
brand
model
year
# example :
# Print all values in the dictionary , one by one :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
18
" year " : 1964
}
for x in thisdict :
print ( thisdict [ x ] )
Ford
Mustang
1964
# example :
# You can also use the values () method to return values of a d i c t i o n a r y :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
for x in thisdict . values () :
print ( x )
Ford
Mustang
1964
# example :
# Loop through both keys and values , by using the items () method :
thisdict = {
" brand " : " Ford " ,
" model " : " Mustang " ,
" year " : 1964
}
for x in thisdict . values () :
print ( x )
brand Ford
model Mustang
year 1964
Nested Dictionaries A dictionary can contain dictionaries, this is called nested dictionaries.
# example :
# Create a d i c t i o n a r y that contain three d i c t i o n a r i e s :
myfamily =
" child1 "
" name "
" year "
},
" child2 "
" name "
" year "
},
" child3 "
" name "
" year "
}
}
{
: {
: " Emil " ,
: 2004
: {
: " Tobias " ,
: 2007
: {
: " Linus " ,
: 2011
print ( myfamily )
’child1’: ’name’: ’Emil’, ’year’: 2004, ’child2’: ’name’: ’Tobias’, ’year’: 2007, ’child3’: ’name’: ’Linus’, ’year’: 2011
# example :
# Print the name of child 2 :
myfamily = {
" child1 " : {
" name " : " Emil " ,
19
" year "
},
" child2 "
" name "
" year "
},
" child3 "
" name "
" year "
}
: 2004
: {
: " Tobias " ,
: 2007
: {
: " Linus " ,
: 2011
}
print ( myfamily [ " child2 " ] [ " name " ] )
Tobias
1.7 Python Functions
1. A function is a block of code which only runs when it is called.
2. You can pass data, known as parameters, into a function.
3. A function can return data as a result.
Creating a Function
1. 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.
# example :
def my_function () :
print ( " Hello from a function " )
my_function ()
Hello from a function
Arguments
1. Information can be passed into functions as arguments.
2. 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.
3. 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 " )
my_function ( " Linus " )
Emil Refsnes
Tobias Refsnes
Linus Refsnes
20
Number of Arguments
1. 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 f u n c t i o n expects 2 arguments , and gets 2 a r g u m e n t s :
def my_function ( fname , lname ) :
print ( fname + " " + lname )
my_function ( " Emil " , " Refsnes " )
Emil Refsnes
# example :
def my_function ( food ) :
for x in food :
print ( x )
fruits = [ " apple " , " banana " , " cherry " ]
my_function ( fruits )
apple
banana
cherry
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 ) )
15
25
45
1.8 math and cmath modules
1. This to modules comes with core python and you don’t need to install them.
2. just import them and these module have some basic mathematical function.
By three ways we can import the modules in Python
1. The last one is recommended for you because it’s avoid conflicting between function form different modules
# fist way
# this command will import all the f u n c t i o n s that exist on math module
from math import *
print ( sin ( pi / 2 ) )
1.0
# second way
# this command will import s p e c i f i c functon
from math import sin , log
print ( sin ( pi / 2 ) )
print ( log ( 10 ) )
21
1.0
2.0
# third way ( r e c o m m e n d e d way )
# now you have access to all f u n c t i o n inside a module
import math as m
print ( m . sin ( m . pi / 2 ) )
print ( m . log10 ( 100 ) )
1.0
2.0
dir() function will return all the function on a module
# example : dir () command
import math as m
print ( dir ( m ) )
cmath is like math module bu accept the complex number
# example : cmath module
# dir () will work for cmath also
import cmath as cm
print ( cm . sin ( 3 . 0 - 5 . 4j ) )
(15.622756309590116+109.59310968004854j)
1.9 numpy module
1. numpy module (library) is not part of the core python and sould installed separately.
2. to install numpy on spyder just write (pip install numpy) on cosole.
3. NumPy means numerical python and created in 2005 by Tarvis.
4. it works with array which is like list but faster than list
5. numpy is used with arrays in Linear algebra, matrices and fourier transform.
Creating Arrays
1. You can create arrray with one of the following methods
import numpy as np
# 1D_ arrays or Vectors
v1 = np . array ( [1 ,2 , 3 ] )
print ( v1 )
print ( type ( v1 ) )
print ( len ( v1 ) )
[1 2 3]
<class ’numpy.ndarray’>
3
import numpy as np
22
# 1D_ arrays or Vectors
# with arange f u n c t i o n 1 is strat 20 is end and 2 is steps
v2 = np . arange (1 , 20 , 2 )
print ( v2 )
[ 1 3 5 7 9 11 13 15 17 19]
import numpy as np
# 1D_ arrays or Vectors
# with l i n s p a c e f u n c t i o n 1 is start 5 is end 20 is numbers
v2 = np . linspace (1 , 25 , 5 )
print ( v2 )
[ 1. 7. 13. 19. 25.]
23
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )