2. Contents
python basics
installing python
running python
Jupiter note book
python syntax basics
application of python
variables in python
arithmetic operations
comparison operators
python data types
Float and integer
String
List
Dictionaries
Conditional statement
if statement
elif statement
else
loops
for loops
while loops
3. Python basics
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.
Interpreted:- Python is processed at runtime by the interpreter. i.e. you do not need to
compile your program before executing it
Interactive :-You can interact with the interpreter directly to write your programs
Portable :- It can run on wide range of hardware Platforms
Object-Oriented :- Python supports Object-Oriented style and Procedural Paradigms
Known as Beginner’s Language :- It’s a great language for the beginner-level
programmers
Provides very high-level dynamic data types and supports dynamic type checking.
Has a huge collection of standard library
4. Python basics(2)
Characteristics of Python
• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
5. Python basics(3)
Installing Python
Python distribution is available for a wide variety of platforms.
Here are the steps to install Python on Windows machine.
Open a Web browser(chrome, Mozilla etc. ) and go
to https://www.python.org/downloads/.
Follow the link for the Windows installer python 3.10.6(latest version)
Save the installer file to your local machine and then run it to find out if your machine
supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really easy to
use. Just accept the default settings, wait until the install is finished, and you are done.
6. Python basics (4)
Running Python
There are different ways to run python script
Script from the Command-line(Python Interpreter) :- to run python shell
open the command prompt or windows power shell
write the word python in the command line and press enter. (this will allow us to
enter into the Python interactive shell where we can actually type Python
commands)
A python prompt comprising of three greater than >>> appears. enter a single
statement and get the result.
N.B: Python Shell executes a single statement
to execute multiple statements
write your scripts on note pad and save it
write python and the file name in cmd.
To exit the Python interpreter, you can either type exit()
7. Python basics (5)
Running Python(continued)
By using Integrated Development Environment:
when python is installed, a program called IDLE(Integrated Development and Learning Environment) is also
installed along with it.
IDLE can be used to execute a single statement (Python Shell window)and also to create, modify, and
execute Python scripts(Editor window)
IDLE python shell window
To start an IDLE interactive shell, search for the IDLE icon in the start menu and double click on it.
start writing and executing codes
The window editor
To start using the editor window , create a new file by selecting File -> New File from the menu.
Enter multiple statements and save the file with extension .py using File -> Save.
finally, press F5 to run the script in the editor window.
8. Python basic (6)
Jupyter note book
The other most common way of writing python scripts is using Jupyter note book
Jupyter Notebook is an open-source web-based text editor used to write, edit and execute programs, display
outputs and writing texts.
When you first install Python, Jupyter does not come as a default installation along with the python . It has
to be installed separately.
To install Jupyter, write pip install Jupyter in the command prompt window
After successful installation, we can start the Jupyter editor from the command by typing Jupyter notebook
The Jupyter note book will be opened in your default browser( chrome, Firefox, safari etc.)
Jupyter will display files and folders from the Python installation folder.
You can create, open, and execute python scripts from the appropriate folders.
Start a new notebook by choosing Python 3 from the "new" dropdown
9. Python basics (7)
Jupyter note book
When you create a new notebook document, you will be presented with the notebook name,
a menu bar, a toolbar and an empty code cell.
Menu bar: The menu bar presents different options that may be used to manipulate the way the
notebook functions.
Toolbar: The tool bar gives a quick way of performing the most-used operations within the notebook,
by clicking on an icon.
Code cell: the default type of cell; read on for an explanation of cells.
10. Popular applications for Python
• Web Development
• Data Science — including machine learning, data analysis, and data visualization
• Scripting
• Game Development
• CAD Applications
• Embedded Applications
11. Python syntax basics
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character () to denote that the line should continue.
Statements contained within the [], {}, or () brackets do not need to use the line continuation character.
Use the semicolon ; to separate multiple statements in a single line.
In a Python script, the symbol # indicates the start of a comment line. It is effective until the end of the line in
the editor.
if 100 > 99 and 200 <= 300 and True != False:
print('Hello World!')
if 100 > 99 and
200 <= 300 and
True != False:
print('Hello World!')
print('id: ', 1);print('First Name: ', ‘Amare');print('Last Name: ', 'Jobs')
# this is a comment
print("Hello World")
print("Welcome to Python Tutorial") # to say welcome.
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
12. Python syntax basics
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same
type of quote starts and ends the string.
The Python program can contain variables, functions, classes, modules, packages, etc. Identifier is the name
given to these programming elements.
Identifiers in Python are case sensitive, which means variables named age and Age are different.
Class names should use the Title Case convention. It should begin with an uppercase alphabet letter
e.g. MyClass, Employee, Person
Function names should be in lowercase. Multiple words should be separated by underscores,
e.g. add(num), calculate_tax(amount)
Module and package names should be in lowercase
e.g., mymodule, tax_calculation
word = 'word'
sentence = "This is a sentence.“
paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
13. Python key words
There are words that have important purposes in Python and are called keywords(reserved words).
These are reserved words and you cannot use them as constant or variable or any other identifier names.
Except for the first three (False, None and True), the other keywords are entirely in lowercase.
help(“keywords) will a print a list of keywords in python
14. Variables in python
In Python, variable is the name given to a value, so that it becomes easy to refer a value later on.
The equal sign (=) is used to assign values to variables.
e.g >>> n = 10
In any case, whatever term is on the left side, is now a name for whatever value is on the right side.
Once a value has been assigned to a variable name, you can access the value from the variable name.
During variable assignment, variable names should be descriptive ,
Only use ordinary letters, numbers and underscores in your variable names.
They can’t have spaces, and need to start with a letter or underscore
Variable names cannot be a reserved keywords in Python.
Variable names in Python are case sensitive. So, NAME, name, nAME, and nAmE are treated as different
variable names
The pythonic way to name variables is to use all lowercase letters and underscores to separate words.
.
my_height = 168
my_weight = 65
my_color = ‘black’
my height = 168
MYWEIGHT = 65
Mycolor = ‘black’
15. Arithmetic operations in variables
Different operations can be performed on variables using various operators based on the type of variables.
For example, the + operator sums up two integer variables, whereas it concatenates two string type variables,
as shown below.
Other mathematical operations that cab be performed in python are
Subtraction (-)
Multiplication (*)
Division(/)
Mod (%) : gives us the remainder after dividing
Exponentiation (**)
// : Divides and rounds down to the nearest integer
>>> x=5
>>> y=4
>>> x+y
9
>>> x='Hello '
>>> y='World‘
>>> x+y
'Hello World‘
>>> x=5
>>> y=4
>>> x*y
20
>>> x=10
>>> y=4
>>> x%y
2
>>> x=27
>>> y=4
>>> x//y
6
16. Exercise
My electricity bills for the last three months have been 230 birr, 320 birr and 640 birr. What is the average
monthly electricity bill over the three month period? Write an expression to calculate the mean, and
use print() to view the result.
The comments in this quiz (the lines that begin with #) have instructions for creating and modifying variables.
After each comment write a line of code that implements the instruction. Note that this code uses scientific
notation to define large numbers. 4.445e8 is equal to 4.445 * 10 ** 8 which is equal to 444500000.0.
# The current volume of a water reservoir (in cubic meters)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic meters)
rainfall = 5e6
# decrease the rainfall variable by 10% to account for runoff
# add the rainfall variable to the reservoir_volume variable
# increase reservoir_volume by 5% to account for storm water that flows into the reservoir in the days
following the storm
# decrease reservoir_volume by 5% to account for evaporation
# subtract 2.5e5 cubic metres from reservoir_volume to account for water that's piped to arid regions.
# print the new value of the reservoir_volume variable
17. Python Data Types
Data Types represent the kind of value variables can hold and what all operations can be performed on a
particular data.
You can check the type by using the ”type” function
you can create a value that follows the data type by using the following syntax:
>>> x = 10
>>> print(type(x))
int
>>>y = float(4)
>>>print(type(y))
Float
18. Python Number Types: int, float, complex(1)
Python includes three numeric types to represent numbers: integers, float, and complex number
In Python, integers are zero, positive or negative whole numbers without a fractional part and having unlimited
precision, e.g. 0, 100, -10.
All integer literals or variables are objects of the ”int” class. Use the type() method to get the class name
The int() function converts a string or float to integer.
In Python, floating point numbers (float) are positive and negative real numbers with a fractional part denoted by
the decimal symbol . or the scientific notation E or e, e.g. 1234.56, 3.142, -1.55, 0.23.
>>> x = 100
>>>type(x)
<class 'int'>
>>> x = 100.21
>>>type(x)
<class ‘float'>
>>> int(x)
100
>>> f=1.2
>>> type(f)
<class 'float'>
19. Python Number Types: int, float, complex(2)
The float()function covert integer or string into float type numbers.
A numeric object of one type can be converted in another type using the following function
Built-in Function Description
int Returns the integer object from a float or a string containing digits.
float Returns a floating-point number object from a number or string containing digits with
decimal point or scientific notation.
complex Returns a complex number with real and imaginary components.
hex Converts a decimal integer into a hexadecimal number with 0x prefix.
oct Converts a decimal integer in an octal representation with 0o prefix.
pow Returns the power of the specified numbers.
abs Returns the absolute value of a number without considering its sign.
round Returns the rounded number.
>>>x = 5
>>> float(x)
5.0
20. Python strings(1)
Strings in Python are shown as the variable type ”str”
It is the sequence of Unicode characters wrapped inside single, double, or triple quotes
We can create them simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
You can also include a in your string to be able to include one of these quotes:
Var1 = 'This is a string in Python' # string in single quotes
Var2 = "This is a string in Python" # string in double quotes
Var3 = '''This is a string in Python''' # string in triple quotes
Var4 = """This is a string in Python""" # string in triple double-quotes
>>> this_string = 'Simon's skateboard is in the garage.'
>>> print(this_string)
Simon's skateboard is in the garage.
21. Python strings(2)
There are a number of operations you can use with strings as well
len() is a built-in Python function that returns the length of an object, like a string.
The length of a string is the number of characters in the string
>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)
HelloThere
>>> print(first_word + ' ' + second_word)
Hello There
>>> print(first_word * 5)
HelloHelloHelloHelloHello
>>> print ( len(first_word))
5
>>>print(len("ababa") / len("ab"))
2.5
22. Python strings(3)
a string is a sequence characters. The sequence uses an index, starting with zero to fetch a certain item (a
character in case of a string) from it.
Use the str() function to convert a number to a string. Other common string methods with description is given
below
>>> greet='hello'
>>> greet[0]
'h'
>>> greet[1]
'e'
>>> greet[2:4]
‘ll'
>>> greet[:3]
‘hel'
>>> greet[-1]
'o'
>>>num = 100
>>> num1 = str(num)
>>> print(num1)
‘100’
>>> print(type(num1))
str
23. Python strings(4)
String methods
A method in Python behaves similarly to a function. Methods actually are functions that are called using dot
notation.
Methods are specific to the data type for a particular variable.
So there are some built-in methods that are available for all strings, different methods that are available for all
integers, etc.
the following methods are built in pythons associated with strings
ethod Description
str.capitalize() Returns the copy of the string with its first character capitalized and the rest of the letters are in lowercased.
string.count() Searches (case-sensitive) the specified substring in the given string and returns an integer indicating occurrences of the substring.
string.endswith() Returns True if a string ends with the specified suffix (case-sensitive), otherwise returns False.
string.find() Returns the index of the first occurence of a substring in the given string (case-sensitive). If the substring is not found it returns -1.
string.islower() Checks whether all the characters of a given string are lowercased or not. It returns True if all characters are lowercased and False even if
one character is uppercase.
string.isnumeric() Checks whether all the characters of the string are numeric characters or not. It will return True if all characters are numeric and will return
False even if one character is non-numeric.
string.lower() Returns the copy of the original string wherein all the characters are converted to lowercase.
string.replace() Returns a copy of the string where all occurrences of a substring are replaced with another substring.
string.split() Splits the string from the specified separator and returns a list object with string elements.
string.title() Returns a string where each word starts with an uppercase character, and the remaining characters are lowercase.
string.upper() Returns a string in the upper case. Symbols and numbers remain unaffected.
24. Python strings(5)
Example
the format() method is one of the most widely method in python string.
>>> my_string = “sebastian thrun”
>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3
>>> my_string.upper()
‘SEBASTIAN THRUN’
>>> my_string.split()
[‘SEBASTIAN’, ‘THRUN’]
>>> animal = "dog"
>>> action = "bite"
>>> print("Does your {} {}?".format(animal, action))
Does your dog bite?
>>> maria_string = "Maria loves {} and {}"
>>> print(maria_string.format("math", "statistics"))
Maria loves math and statistics
25. Exercise: given the following string, answer the questions that follows
verse = "If you can keep your head when all about you Are losing theirs and blaming it on you If you can
trust yourself when all men doubt you But make allowance for their doubting too If you can wait and not
be tired by waiting Or being lied about, don’t deal in lies Or being hated, don’t give way to hating And yet
don’t look too good, nor talk too wise:"
1. What is the length of the string variable verse?
2. What is the index of the first occurrence of the word 'and' in verse?
3. What is the index of the last occurrence of the word 'you' in verse?
4. What is the count of occurrences of the word 'you' in the verse?
26. Booleans, Comparison Operators, and Logical Operators
The bool data type holds one of the values True or False, which are often encoded as 1 or 0, respectively.
There are 6 comparison operators that are common to see in order to obtain a bool value:
There are three logical operators you need to be familiar with:
Symbol Use Case Bool Operation
5 < 3 False Less Than
5 > 3 True Greater Than
3 <= 3 True Less Than or Equal To
3 >= 5 False Greater Than or Equal To
3 == 5 False Equal To
3 != 5 True Not Equal To
Comparison Operators
Logical Use Bool Operation
(5 < 3) and (5 == 5) False and - Evaluates if all provided statements are True
(5 < 3) or (5 == 5) True or - Evaluates if at least one of many statements is True
not 5 < 3 True not - Flips the Bool Value
27. Exercise
Write code to compare these densities. Is the population of San Francisco more dense than that of Rio de
Janeiro? Print True if it is and False if not
.
>>> sf_population, sf_area = 864816, 231.89
>>>rio_population, rio_area = 6453682, 486.5
>>>san_francisco_pop_density = sf_population/sf_areario_
>>>de_janeiro_pop_density = rio_population/rio_area
# Write code that prints True if San Francisco is denser than Rio, and False otherwise
28. Python list(1)
A list object contains one or more items of different data types in the square brackets [] separated by a
comma
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value
available at that index.
>>> mylist=[] # empty list
>>> print(mylist)
[]
>>> names=["Jeff", "Bill", "Steve", "Mohan"] # string list
>>> print(names)
['Jeff', 'Bill', 'Steve', 'Mohan']
>>>item=[1, "Jeff", "Computer", 75.50, True] # list with heterogeneous data
>>> print(item)
[1, 'Jeff', 'Computer', 75.5, True]
>>> list2 = [1, 2, 3, 4, 5, 6, 7 ]
>>>print (list2[0])
1
>>> Print(list2[1:4])
[2,3,4]
29. Python list (2)
To remove a list element, you can use either the del statement if you know exactly which element(s) you are
deleting or the remove() method if you do not know.
Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.
>>>list1 = ['physics', 'chemistry', 1997, 2000]
>>> print list1
['physics', 'chemistry', 1997, 2000]
>>>del list1[2]
>>> print(list1)
['physics', 'chemistry', 2000]
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
30. Python list (3)
like any other data types in python, list also posses its own built any functions and methods.
Sr.No. Function with Description
1 cmp(list1, list2): Compares elements of both lists.
2 len(list): Gives the total length of the list.
3 max(list): Returns item from the list with max value.
4 min(list) : Returns item from the list with min value.
5
6
7
list.append(obj): Appends object “obj” to list
list.remove(obj): Removes object “obj” from list
list.count(obj): Returns count of how many times “obj” occurs in list
>>> names=["Jeff", "Bill", "Steve", "Mohan"]
>>> names[0]="Newton" # update 1st item at index 0
>>> names[1]="Ram" # update 2nd item at index 1
>>> names.append("Abdul") # adds new item at the end
>>> print(names)
['Newton', 'Ram', 'Steve', 'Mohan', 'Abdul']
31. Python – Dictionary(1)
The dictionary is an unordered collection that contains key: value pairs separated by commas inside curly
brackets.
One approach for creating a dictionary is to use curly braces {} and colons to separate keys and values:
You can access, insert, or set elements using the same syntax as for accessing elements of a list
You can check if a dictionary contains a key using the same syntax used for checking whether a list or tuple
contains a value:
>>> capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
>>> Print(capitals)
{'USA': 'Washington D.C.', 'France': 'Paris', 'India': 'New Delhi'}
>>> my_dicti = {'a': 'some value', 'b': [1, 2, 3, 4]}
>>> my_dicti[7] = "an integer" # inserting a new element into my dicti
>>> Print(my_dicti)
{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
>>> print(d1["b"])
[1, 2, 3, 4]
>>> "b" in my_dicti # note that “in” and “not in” are called member ship operators
True # used to check if a given element is a member of sequential type data structure or not
>>> “b” not in my_dicti
False
32. Python – Dictionary(2)
You can delete values using either the ”del ”keyword or the ”pop” method (which simultaneously returns the
value and deletes the key):
The ”keys” and ”values” method gives you iterators of the dictionary's keys and values, respectively.
>>> My_dicti = {'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
>>> del My_dicti[“a”]
>>> print(My_dicti)
{ 'b': [1, 2, 3, 4], 7: 'an integer'}
>>>My_dicti.pop(“b”)
[1, 2, 3, 4]
>>> print(My_dicti)
{ 7: 'an integer'}
>>> My_dicti = {'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
>>>print(My_dicti.keys()
dict_keys([“a”,”b”,7])
>>> print(My_dicti.values())
dict_values(['some value', [1, 2, 3, 4], 'an integer’])
33. Exercise
Consider the following table
Define a dictionary named ”population” that contains the above data
print a list contains only the keys of your dictionary
write a code that check whether Addis Ababa is in the data or not.
Insert the following element ( Addis Abeba with 10 million population into your dictionary)
Can you explain the difference between list and tuples?
Given the following dictionnairy:
room_numbers = { ['Freddie', 'Jen']: 403, ['Ned', 'Keith']: 391, ['Kristin', 'Jazzmyne']: 411, ['Eugene', 'Zach']: 395}
what is wrong with the dictionary?
City Population(in millions)
Shanghai 17.8
Istanbul 13.3
Karachi 13.0
Mumbai 12.5
34. Python tuple
A tuple is immutable sequence of Python objects separated by a comma.
They are often used to store related pieces of information( two or more closely related values which always
used together)
The easiest way to create one is with a comma-separated sequence of values wrapped in parentheses:
tuples can also used to assign multiple variables
x = (4, 5, 6)
Y= 4, 5, 6
You can convert any sequence or iterator to a tuple by
invoking tuple
Z= tuple([4, 0, 2])
W = tuple(‘hello')
>>> Dimension = 45, 50 , 60
>>> Weight, height, width = Dimension
35. Python sets
sets is a data type for mutable unordered collection of unique elements
are used to remove duplicate values from a list and store only unique values
Sets support the in operator the same as lists do
You can add elements to sets using the add method, and remove elements using the pop method, similar to
lists.when you pop an element from a set, a random element is removed.
Methods like union, intersection, and difference are easy to perform with sets, and are much faster than such
operators with other containers.
>>> numbers = [1, 2, 6, 3, 1, 1, 6]
>>> unique_nums = set(numbers)
>>> print(unique_nums)
fruit = {"apple", "banana", "orange", “pineapple"}
print("watermelon" in fruit)
fruit.add("watermelon")
print(fruit)
print(fruit.pop())
print(fruit)
Set1 = {2,4,5}
Set2 = { 3,4,5)
Set1.union(set2)
Set1.difference(set2)
36. Summary
A good understanding of data structures is integral for programming and data analysis.
Data Structure Ordered Mutable Constructor Example
List Yes Yes [ ] or list() [5.7, 4, 'yes', 5.7]
Tuple Yes No ( ) or tuple() (5.7, 4, 'yes', 5.7)
Set No Yes {}* or set() {5.7, 4, 'yes'}
Dictionary No No** { } or dict() {'Jun': 75, 'Jul': 89}
37. Exercise
Given the following list
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
create a set named “set1” from the above list
Find the difference in the number of elements between the two python objects
insert “ 8” into set1
Remove “1” from set1
create a set named set2 that contains all integers from 1 to 5
find a union of set 1 and set 2
find a difference of set1 and set 2
find the intersection between set 1 and set
38. Python – Conditional statements(1)
if statement
An ”if” statement is a conditional statement that runs or skips code based on whether a condition is true or
false.
An if statement starts with the if keyword, followed by the condition to be checked, and then a colon. The
condition is specified in a Boolean expression that evaluates to either True or False.
The expression ”price < 100” evaluates to True, so it will execute the block.
Indentation is very important in using if statements
>>> price = 50
>>>if price < 100:
>>>print("price is less than 100")
price is less than 100
>>>price = 50
>>>quantity = 5
>>> if price*quantity < 500:
print("price is less than 500")
print("price = ", price)
print("quantity = ", quantity)
IdentationError: unexpected indent
39. Python – Conditional statements(2)
If else Condition
Along with the if statement, the else condition can be optionally used to define an alternate block of
statements to be executed if the Boolean expression in the if condition evaluates to False
In the above example, the if condition price >= 100 is False, so the else block will be executed.
The else block can also contain multiple statements with the same indentation; otherwise, it will raise
the Indentation Error
Note that you cannot have multiple else blocks, and it must be the last block
>>>price = 50
>>>if price >= 100:
>>> print("price is greater than 100")
>>>else:
>>>print("price is less than 100")
price is less than 100
.
.
40. Python – Conditional statements(3)
elif Condition
Use the elif condition is used to include multiple conditional expressions after the if condition or between
the if and else conditions.
The elif block is executed if the specified condition evaluates to True
Syntax:
if [boolean expression]:
[statements]
elif [boolean expresion]:
[statements]
elif [boolean expresion]:
[statements]
else:
[statements]
price = 100
if price > 100:
print("price is greater than 100")
Elif price == 100:
print("price is 100")
else:
print("price is less than 100")
41. Exercise
You decide you want to play a game where you are hiding a number from someone. Store this number in a
variable called 'answer'. Another user provides a number called 'guess'. By comparing 'guess' to 'answer', you
inform the user if their guess is too high or too low. Write a python program to inform the user about how their
guess compares to the answer.
>>>answer = ----------- #provide answer
>>>guess = -------------#provide guess
>>>if -------------#provide conditional
>>> result = "Oops! Your guess was too low.“
>>> elif ------------------#provide conditional
>>> result = "Oops! Your guess was too high”.
>>>>elif --------------#provide conditional
>>>result = "Nice! Your guess matched the answer!“
>>> print(result)
42. Python: Loops(1)
Python has two kinds of loops - for loops and while loops. A for loop is used to "iterate", or do something
repeatedly, over an iterable.
For loops
An iterable is an object that can return one of its elements at a time. This can include sequence types, such as
strings, and lists, as well as non-sequence types, such as dictionaries and files.
range() is a built-in function used to create an iterable sequence of numbers. You will frequently
use range() with a for loop to repeat an action a certain number of times.
>>> cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
>>>for city in cities:
>>> print(city)
new york city
mountain view
chicago
los angeles
>>> for i in range(3):
>>> print("Hello!")
Hello!
Hello!
Hello!
43. While Loops
For loops are an example of "definite iteration" meaning that the loop's body is run a predefined number of
times.
This differs from "indefinite iteration" which is when a loop repeats an unknown number of times and ends
when some condition is met, which is what happens in a while loop.
Python: Loops(2)
>>> num =0
>>> while num < 5:
>>> num = num + 1
>>> print(num)
1
2
3
4
5
44. Exercise
given the following list of common applications
app_names = ['Facebook', 'Instagram', 'Clash of Clans', 'Fruit Ninja Classic', 'Minecraft: Pocket Edition']
print each of the applications
Given the following data set
Write a for loop to print all apps rating ( 4th element in each list) in the dataset.
Write a while loop that finds the largest square number less than an integer limit and stores it in a
variable nearest_square.
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
row_3 = ['Clash of Clans', 0.0, 'USD', 2130805, 4.5]
row_4 = ['Fruit Ninja Classic', 1.99, 'USD', 698516, 4.5]
row_5 = ['Minecraft: Pocket Edition', 6.99, 'USD', 522012, 4.5]
app_data_set = [row_1, row_2, row_3, row_4, row_5]
45. Zip ()and enumerate()
zip and enumerate are useful built-in functions that can come in handy when dealing with loops.
The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it
In addition to zipping two lists together, you can also unzip a list into tuples using an asterisk.
enumerate ()is a built in function that returns an iterator of tuples containing indices and values of a list.
>>> languages = ['Java', 'Python', 'JavaScript']
>>> versions = [14, 3, 6]
>>> result = zip(languages, versions)
>>>print(list(result))
[('Java', 14), ('Python', 3), ('JavaScript', 6)]
>>> some_list = [('a', 1), ('b', 2), ('c', 3)]
>>>letters, nums = zip(*some_list)
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> for i, letter in enumerate(letters):
>>> print(i, letter)
46. Exercise
1. Given the following:
x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
Use zip to write a for loop that creates a string specifying the label and coordinates of each point and appends it to the
list points and print each element of the list.
2. Use zip to create a dictionary ”cast” that uses names as keys and heights as values
cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
3. Unzip the cast tuple into two names and heights tuples.
cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))
47. List Comprehensions
In Python, you can create lists really quickly and concisely with list comprehensions.
List comprehensions are not found in other languages, but are very common in Python.
You can create a list comprehension with brackets [], including an expression to evaluate for each element in
an iterable.
You can also add conditionals to list comprehensions (listcomps). After the iterable, you can use
the if keyword to check a condition in each iteration.
Exercise: Given the following list, create a new list (capitalized_cities) containing elements with upper letters
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
-------------------------------------------------------------------------------------------------------------------
capitalized_cities = [city.upper () for city in cities]
Exercise: create a list named squares containing square numbers in the range of 9.
-------------------------------------------------------------------------------------------------------------------------------------------
squares = [x**2 for x in rage(9)]
>>> squares = [x**2 for x in range(9) if x % 2 == 0]
48. Exercise
Use a list comprehension to create a new list first_names containing just the first names in names in
lowercase
>>> names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
Use a list comprehension to create a list multiples_3 containing the first 20 multiples of 3.
Use a list comprehension to create a list of names passed that only include those that scored at least 65.
scores = { "Rick Sanchez": 70, "Morty Smith": 35, "Summer Smith": 82,
"Jerry Smith": 23, "Beth Smith": 98 }
49. Defining a function
In addition to use built-in functions, python will also allow us to write and use our own function
In Python, a function is a group of related statements that performs a specific task
A function definition includes several important parts.
The function header always starts with the def keyword, which indicates that this is a function definition.
Then comes the function name which follows the same naming conventions as variables.
Immediately after the name are parentheses that may include arguments separated by commas. Arguments,
or parameters, are values that are passed in as inputs when the function is called, and are used in the function
body. If a function doesn't take arguments, these parentheses are left empty.
Optional documentation string (docstring) to describe what the function does may also be included.
The header always end with a colon :
>>> def cylinder_volume(height, radius):
>>> ‘’’This function compute volume and takes height and radius as parameter ‘’’
>>>pi = 3.14159
>>> volume = height * pi * radius ** 2
>>> return volume
50. Defining function(2)
The body of a function is the code indented after the header line.
Within this body, we can refer to the argument variables and define new variables, which can only be used
within these indented lines.
The body will often include a return statement, which is used to send back an output value from the function
to the statement that called the function.
A return statement consists of the return keyword followed by an expression that is evaluated to get the output
value for the function.
If there is no return statement, the function simply returns None
We can add default arguments in a function to have default values for parameters that are unspecified in a
function call.
>>> def cylinder_volume(height, radius=5):
>>> pi = 3.14159
>>> return height * pi * radius ** 2
51. Exercise
Write a function named population_density that takes two arguments, population and land_area, and returns a
population density calculated from those values.
write a function that can compute absolute value of a number with the following docstring documentation
"""This function returns the absolute value of the entered number"""
Write a function named readable_timedelta. The function should take one argument, an integer days, and
return a string that says how many weeks and days that is. For example, calling the function and printing the
result like this: print(readable_timedelta(10)).the output must be 1 week(s) and 3 day(s).
52. Functions: lambda expressions
You can use lambda expressions to create anonymous functions.
That is, functions that don’t have a name.
They are helpful for creating quick functions that aren’t needed later in your code.
Components of a Lambda Function
The lambda keyword is used to indicate that this is a lambda expression.
Following lambda are one or more arguments for the anonymous function separated by commas, followed by
a colon :. Similar to functions, the way the arguments are named in a lambda expression is arbitrary.
Last is an expression that is evaluated and returned in this function. This is a lot like an expression you might
see as a return statement in a function.
With this structure, lambda expressions aren’t ideal for complex functions, but can be very useful for short,
simple functions.
Exercise: write a python function that can multiply any two numbers
------------------------------------------------------------------------------------------------------
multiply = lambda x, y: x * y
54. Classes and objects in python(1)
objects entities that represent real world
Object has characteristics and actions
Example:
car
person
Store
Student
Chair
etc
Sales person: characteristics :
name
Address
Phone number
Hourly pay
Sales person: action:
sell item
take item
T-shirt: characteristics :
colour
size
Style
Price
T-shirt: action:
Change price
55. Classes and objects in python(2)
In object oriented program, the focus is in individual characteristics of the object(characteristics) and what each object
can do (action). The characteristics of python objects are called attributes and the actions are known as methods
The two objects above have the same attributes and methods .That is they belongs to the same class.
Class: A blueprint consisting of methods and attributes. They serve as templates from which objects are
created. you only need to create class once and then you can create a specific objects over and over again from
that class
T_shirt_1: attributes :
colour: red
size :medium
Style: v
Price:500
T-shirt_1: methods: price_change :
Change price
T_shirt_2: attributes :
colour: blue
size :large
Style: circle
Price:700
T-shirt_2: methods: price_change :
Change price
56. Classes and objects in python(3)
Exercise
classify the following lists as class, object, attributes, methods and value
Stephen hawking, Angela merkel, Brad pitt
scientist, chancellor, actor
to train, to ring, to ripen
black , 22, false
colour, size, shape
57. Classes and objects in python(4)
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows the
keyword class followed by a colon as follows −
after the class is created , the next step is to define the attributes of the class
The first method __init__() is a special method, which is called class constructor or initialization method that
Python calls when you create a new instance of this class.
The __init__ method lets the class initialize the object’s attributes and serves no other purpose.
‘self’ stores the attributes such as colour, size and etc. and make them available through out the class
you have to pass ‘self’ as the first input in all your methods in order to have access to the attributes stored
inside it
Class Shirt:
Def __init__(self, shirt_color, shirt_size, shirt_style, shirt_price
Self.color = shirt_color
Self.size = shirt_size
Self.style = shirt_style
Self.price = shirt_price
58. Classes and objects in python(5)
methods can be created in the same technique as regular python functions
In order to create specific types of shirts object in python, we use the Shirt class and this is called instantiating
objects
new_shirt variable has attributes such as colour, price and etc. and in order to access these attributes, we use
the following commands
In order to access the methods however, we need to specify any inputs that the method require
Def change_price (self, new_price):
self. Price = new_price
Def discount(self, discount):
Return self. Price*(1-discount)
Shirt(“red”, ”s”, ”short sleeve”,500)
New_shirt = Shirt(“red”, ”s”, ”short sleeve”,500)
Print (new_shirt.color)
Print(new_shirt.price)
Print(new_shirt.style)
Print(new_shirt.size)
Print(new_shirt.change_price(450)
Print(new_shirt.discount(0.25))
59. Exercise
given the following three shirt objects defined from Shirt class
shirt_one = Shirt(‘black’,’M’, ‘short sleeve’ , 600)
shirt_two = Shirt(‘blue,’L’, ‘long sleeve’ , 700)
shirt_three= Shirt(‘purple’,’XL, ‘short sleeve’ , 500)
create a list that contains the three objects and print the colour of the objects by using for loop
Make a class that represents a bank account with two attributes : name and balance. The default value for
balance should be zero. Then create three methods named display, withdraw and deposit. In the display
method, display the values of the two instance variables(attributes). Both the methods withdraw and deposit
have amount as parameter. Inside withdraw, subtract the amount from balance and inside deposit, add the
amount to the balance. Create two instances of this class(objects) and call the methods on those instances.
60. Python libraries: numpy
NumPy stands for Numerical Python and it's a fundamental package for scientific computing in Python.
NumPy provides Python with an extensive math library capable of performing numerical computations effectively and
efficiently.
Download NumPy
NumPy is included with Anaconda.
either wise use one of the following techniques to install numpy
Benefits of using python numpy
one such feature is speed. When performing operations on large arrays NumPy can often perform several orders of
magnitude faster than Python lists.
Another great feature of NumPy is that it has multidimensional array data structures that can represent vectors and
matrices.
Another great advantage of NumPy over Python lists is that NumPy has a large number of optimized built-in mathematical
functions.
>>> pip install numpy -------------------on window terminal or jupyter notebook
61. Python numpy (2)
python numpy is used to create n_dimensional array
a ndarray is a grid that can take on many shapes and can hold either numbers or strings.
In many Machine Learning problems you will often find yourself using ndarray in many different ways.
For instance, you might use an ndarray to hold the pixel values of an image that will be fed into a Neural Network for
image classification.
But before we can dive in and start using NumPy to create ndarrays we need to import it into Python.
We can import packages into Python using the import command and it has become a convention to import NumPy
as np.
Therefore, you can import NumPy by typing the following command in your Jupyter notebook:
There are several ways to create ndarrays in NumPy. In the following lessons we will see two ways to create ndarrays:
by providing Python lists to the NumPy np.array() function.
Using built-in NumPy functions
Import numpy as np
62. Python numpy (3)
to create a simple one dimensional array, we can use np.array() function
numpy array has useful attributes that provide information about them
we can also create multidimensional array and use the same attribute
Import numpy as np
X = np.array([1,2,3,4,5])
x.dtype ---------returns the data types of the elements in the array
x.shape----------returns the tuples that specifies the size of each dimensions
x.size--------------returns the total number of elements in the array
x.ndim------------returns the rank of the array
Y = np.array([[1,2,3],[4,5,6],[7,8,9], [10,11,12]])
# We print information about Y
print( Y)
print(type(Y))
print(Y.dtype)
print(Y.shape)
print( Y.size)
63. Python numpy (3)
we can also use built in functions to create arrays
Exercise
Using the Built-in functions to create a 4 x 4 ndarray that only contains consecutive even numbers from 2 to
32 (inclusive)
X = np.zeros((3,4)) create array of zeros with 3 number of rows and 4 columns
Y = np.ones((3,2)) create array of ones with 3 number of rows and 2 number of columns
z = np.full((2,3), 5) create array of 5 with 2 number of rows and three number of columns
w = np.arange(10) create a one dimensional array that has sequential integers from 0 to 9
t = np.arange(1,14,3) create a one dimensional array that has sequence integers 1 to 13 in space of three
s= np.reshape(t, (4,5)) reshape t into multidimensional array
64. Python numpy(4)
We can access, delete, and inserting elements Into ndarrays
x = np.array([1, 2, 3, 4, 5])
x[0] ---------returns the first elements of the array
x[-1] --------returns the last element of the array
x[3] = 20----------------change the fourth element in x from 4 to 20
Y = np.array([[1,2,3],[4,5,6],[7,8,9]])
Y[0,0] --------------------------returns the 0,0 element in the array
Y[0,1]----------------------------returns the (0,1) Element in Y
Y[0,0] = 20 ---------------------change the (0,0) element in Y from 1 to 20
x = np.delete(x, [0,4])-------------------delete the first and last element of x
j = np.delete(Y, [0,2], axis=1)--------------We delete the first and last column of y
65. Python numpy (5)
arithmetic and Statistical Operations in python numpy array
Function/Method Description
numpy.add Element-wise add given arrays
numpy.subtract Subtract arguments of given arrays, element-wise.
numpy.multiply Multiply arguments of given arrays, element-wise.
numpy.divide Returns a true division of the inputs, element-wise.
numpy.exp Calculate the exponential of all elements in the input array.
numpy.power First array elements raised to powers from second array, element-
wise.
numpy.sqrt Return the non-negative square-root of an array, element-wise.
numpy.ndarray.min Return the minimum along the specified axis.
numpy.ndarray.max Return the maximum along a given axis.
numpy.mean
numpy.ndarray.mean
Compute the arithmetic mean along the specified axis.
numpy.median Compute the median along the specified axis.
66. Python pandas (1)
pandas is a package for data manipulation and analysis in Python.
Pandas is included with Anaconda.
we can also install in cmd by using pip install pandas command
Why pandas?
Allows the use of labels for rows and columns
Can calculate rolling statistics on time series data
Easy handling of NaN values(missing values)
Is able to load data of different formats into DataFrames
Can join and merge different datasets together
It integrates with NumPy and Matplotlib
67. Python pandas(2)
Pandas Series
A Pandas series is a one-dimensional array-like object that can hold many data types, such as numbers or
strings, and has an option to provide axis labels.
there are different ways to create pandas series
You can create Pandas Series by using the command pd.Series(data, index),
where index is a list of index labels.
there are different attributes that can applied on pandas series
import pandas as pd
groceries = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['eggs', 'apples', 'milk', 'bread'])
print(groceries.shape)
print( groceries.ndim)
print(groceries.size)
print(groceries.values) ----------------returns the values of the series
print(groceries.index)------------------returns the index of the series
68. Python pandas(3)
once the series is created, we can then access, insert and delete items (elements) from the series
Exercise :Given a list representing a few planets
planets = ['Earth', 'Saturn', 'Venus', 'Mars', 'Jupiter']
distance_from_sun = [149.6, 1433.5, 108.2, 227.9, 778.6]
Create a Pandas Series "dist_planets" using the lists above, representing the distance of the planet from the Sun.
Use the `distance_from_sun` as your data, and `planets` as your index.
Calculate the time (minutes) it takes light from the Sun to reach each planet. You can do this by dividing each
planet's distance from the Sun by the speed of light. Use the speed of light, c = 18, since light travels 18 x 10^6
km/minute.
Use Boolean indexing to select only those planets for which sunlight takes less than 40 minutes to reach them.
groceries['eggs'] ------------------- returns only the value of the index ‘egg’
groceries[['milk', 'bread']])------------returns the values of milk and bread
groceries.loc[['eggs', 'apples']])------------returns the values of egg and apple
groceries[[0, 1]] -------------------------------returns the first and second rows
groceries.iloc[[2, 3]] -------------------------------returns the first and second rows
groceries['eggs'] = 2 -------------------------------change the values of egg into 2
groceries.drop('apples'))-------------------------remove the elements of apple
69. Python pandas(4)
Pandas DataFrames
Pandas data frame are two-dimensional data structures with labelled rows and columns, that can hold many
data types.
Pandas DataFrames has the same structure as Excel's a spread sheet.
We can create Pandas DataFrames manually or by loading data from a file
one of the most convenient way of creating pandas data frame is to read from excel file by using
pandas.read_csv function (pandas.read_csv())
Like NumPy's ndarrays, pandas' DataFrames have a .shape attribute which returns a tuple representing the
dimensions of each axis of the object. We can also use type() function to inspect the data frame.
DataFrames can contain columns with multiple data types: including integer, float, and string. To view the first
few rows of our dataframe, we can use the DataFrame.head() method.
# import pandas as pd
import pandas as pd
# read excile file (ggg.csv)and store it as df
Df = pd.read_csv(‘ggg.csv’)