- Table of Contents
- Day 1:
- Commmand to check python version
- Different data types in python:
- 1. Number
- 2. String
- 3. Boolean: True or False data
- 4. List: used to store multiple items in a single variable. List items are ordered, changeable, and allow duplicate values.
- 5. Dictionary: an unordered collection of data in a key value pair format.
- 6. Tuple: similar like list but cannot modified once it has been created. Tutples are written with round brackets.
- 7. Set: is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
- Day 2:
- Day 3:
- Day 4:
- Strings are any data type written as a text. Strings are surrounded by single, double or triple quotes.
- String Concatenation is merging strings together.
- Escape sequences: \ followed by a character is an escape sequence.
- String format:
- Python Strings as Sequences of Characters
- Slicing Python Strings
- Different string methods
- Day 5:
- There are 4 buil-in data types in Python used to stored data namely: list, tuple. set, dictionary.
- How to creat list:
- Unpacking List Items
- Slicing Items from a List
- Modifying Lists
- Checking Items in a List
- Adding Items to a List
- Inserting Items into a List
- Removing Items from a List
- Clearing List Items
- Copying a List
- Joining Lists
- Counting Items in a List
- Finding Index of an Item
- Reversing a List
- Sorting List Items
- Day6:
- Day7:
- A set is used to store multiple items in a single variable
- A set is written with curly brackets
- Create a set
- The syntax returns the differences between two sets
- Day8:
- Dictionaries
- A dictionary is a collection of unordered, modifiable(mutable) paired (key: value) data type.
- Creating a Dictionary
- Dictionary Length
- Accessing Dictionary Items
- Modifying Items in a Dictionary
- Checking keys
- Removing Key and Value Pairs
- change dictionary to a list of items
- Clearing a Dictionary
- Deleting a Dictionary
- Copy a Dictionary
- Getting Dictionary Keys as a List
- Getting Dictionary Values as a List
- Day9:Conditionals
- Day 10: Loops
- Day 11:
python --version
- To start type python and enter python scripts after >>>
- To exist type exit() after >>> and click Enter
Noted: use * to represent multiply in python not x ** is the exponential operator. Eg 3**2 = 3^2 = 3*3
- to start a comment in python use #. For multiple comments, write them in between two triple quotes set """
- python file has an extension .py
a. Integer: Round numbers b. Float: numbers with decimala
4. List: used to store multiple items in a single variable. List items are ordered, changeable, and allow duplicate values.
Example:
>>> thislist = ["apple", "banana", "cherry", "apple", "cherry"]
>>> print(thislist)
['apple', 'banana', 'cherry', 'apple', 'cherry']
Example:
>>> thisdict = {
... "brand": "Ford",
... "model": "Mustang",
... "year": 1964
... }
>>> print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
>>>
6. Tuple: similar like list but cannot modified once it has been created. Tutples are written with round brackets.
Example:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
>>>
Example: duplicate value will be ignored.
>>> thisset = {"apple", "banana", "cherry", "apple"}
>>> print(thisset)
{'cherry', 'banana', 'apple'}
- use type () command to check data types:
>>> type ((1,2,4,10))
<class 'tuple'>
https://docs.python.org/3.9/library/functions.html
- must start with a letter or underscore character
- cannot start with a number
- can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- case-sensitive
firstname last_name
first-name last-name
>>> number_string=234.56
>>> print('number_integer',int(number_string))
number_integer 234
>>> print('number_float', float(number_string))
number_float 234.56
Link to examples of different typea of operators: https://www.w3schools.com/python/python_operators.asp
They are used to assign values to variables.
They are used with numberic values to perform commmon mathematical operators.
Addition(+): a + b Subtraction(-): a - b Multiplication(*): a * b Division(/): a / b Modulus(%): a % b Floor division(//): a // b Exponentiation(**): a ** b
They are used to compare two values and check if a value is greater or less or equal to other value.
They are used to combine conditional statement. Key words are and, or and not.
Strings are any data type written as a text. Strings are surrounded by single, double or triple quotes.
Eg:
>>> first_name='Tina'
>>> last_name='Bui'
>>> full_name=first_name + " " + last_name
>>> print(full_name)
\n: new line
\t: Tab means(8 spaces)
\: Back slash
': Single quote (')
": Double quote (")
Eg:
print('How are you?\nAnd you ?')
%s - String (or any object with a string representation, like numbers) %d - Integers %f - Floating point numbers "%.number of digitsf" - Floating point numbers with fixed precision
Eg:
base = 2
height = 4
area = 1/2 * base * height
formated_string = 'The area of triangle with base = %d and height = %d is %d.' %(base, height, area)
print(formated_string)
Eg:
base = 2
height = 4
area = 1/2 * base * height
formated_string = 'The area of triangle with base = {} and height = {} is {}'.format(base, height, area)
print(formated_string)
String start with f - f.string and data can be injected in their corresponding position.
Eg:
a = 2
b = 4
print(f'1/2 * {a} * {b} = {1/2*a*b}')
name = 'Tina_Bui'
a,b,c,d,e,f,g,h = name#
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
In Python counting starts from 0, the first letter of the string is 0 and the last letter of the string is the length of the string - 1
name = 'Tina_Bui'
first_letter = name [0]
print(first_letter)
last_letter = name[-1]
print(last_letter)
name = 'Tina_Bui'
first_three = name [0:3]
print(first_three)
last_three = name[5:8]
print(last_three)
# Another way
last_three = name[-3:]
print(last_three)
name = 'Tina_Bui'
print(name[::-1])
a_string[start:stop:step]
name = 'Tina_Bui'
Ta = name[0:5:3]
print(Ta)
https://www.w3schools.com/python/python_ref_string.asp
Note: by default default Python‘s print() function ends with a newline
To print on the same line use end = " "
Eg:
company = 'Coding For All'
x = company.split()
for company in x:
print(company [0], end="")
They are collection which are:
- ordered
- changeable
- allows duplicate members
- can be empty or have different data type items
- indexed, the first item has index [0]
- ordered
- unchangeable or unmodifiable(imutable)
- allow duplicate members
- unordered
- un-indexed and unmodofiable
- allow new items to the set
- not alllow duplicate members
- unordered
- changeable(modifiable) and indexed
- not alllow duplicate members
Eg:
x = list(('chanel', 'gucci', 'dior'))
print(x)
Eg:
wish_list = ["chanel", "gucci", "dior"]
print(wish_list)
list = [] # empty list
print(list)
list = ["chanel", 5000, False, 1, "high_end"]
wish_list = ["chanel", "gucci", "dior"]
first_item = wish_list[0]
-1 refers to the last item, -2 refers to the second last item
wish_list = ["chanel", "gucci", "dior"]
second_item = wish_list[-2]
If you want to unpack the first few elements of a list and don’t care about the other elements, you can:
- First, unpack the needed elements to variables.
- Second, pack the leftover elements into a new list and assign it to another variable. By putting the asterisk (*) in front of a variable name, you’ll pack the leftover elements into a list and assign them to a variable.
Eg:
colors = ['red', 'blue', 'green']
red, blue, *other = colors
print(red)
print(blue)
print(other)
Output:
red
blue
['green']
https://www.pythontutorial.net/python-basics/python-unpack-list/
We can specify a range of indexes by specifying the start, end and step, the return value will be a new list. (default values for start = 0, end = len(lst) - 1 (last item), step = 1) Eg:
wish_list = ["chanel", "gucci", "dior", "ysl"]
full_wish_list = wish_list[0:4] # it returns all values
# this will also give the same result as the one above
full_wish_list = wish_list[0:] # if we don't set where to stop it takes all the rest
gucci_dior = wish_list[1:3] # it does not include the first index
gucci_dior_ysl = wish_list[1:]
gucci_ysl = wish_list[::2] # here we used a 3rd argument, step. It will take every 2cnd item
Eg:
wish_list = ["chanel", "gucci", "dior", "ysl"]
wish_list[0] = 'zara'
print(wish_list) # ['zara', 'gucci', 'dior','ysl']
last_index = len(wish_list - 1
wish_list[last_index] = 'aje'
print(fwish_list) # ['chanel', 'gucci', 'dior', 'aje']
Eg:
wish_list = ["chanel", "gucci", "dior", "ysl"]
does_exist = 'channel' in wish_list
print(does_exist) # True
does_exist = 'zara' in wish_list
print(does_exist) # False
# syntax
lst = list()
lst.append(item) #To add item to the end of an existing list
wish_list = ["chanel", "gucci", "dior", "ysl"]
wish_list.append('zara')
print(wish_list) #['chanel', 'gucci', 'dior', 'ysl','zara']
# syntax # use insert() method to insert a single item at a specified index in a list. Note that other items are shifted to the right. The insert() methods takes two arguments:index and an item to insert
lst = ['item1', 'item2']
lst.insert(index, item)
wish_list = ["chanel", "gucci", "dior", "ysl"]
wish_list.insert(2, 'zara')
print(wish_list) # ['chanel', 'gucci', 'zara', 'dior', 'ysl']
# syntax
lst = ['item1', 'item2']
lst.remove(item)
# syntax# pop() method removes the specified index, (or the last item if index is not specified)
lst = ['item1', 'item2']
lst.pop() # last item
lst.pop(index)
Eg:
wish_list = ["chanel", "gucci", "dior", "ysl"]
wish_list.pop()
print(wish_list # ['chanel', 'gucci', 'dior']
# syntax
lst = ['item1', 'item2']
del lst[index] # only a single item
del lst # to delete the list completely
Eg:
wish_list = ["chanel", "gucci", "dior", "ysl"]
del wish_list[1:3] # this deletes items between given indexes, so it does not delete the item with index 3!
print(wish_list) # ['chanel', 'ysl']
# syntax #empties the list
lst = ['item1', 'item2']
lst.clear()
Eg:
wish_list = ["chanel", "gucci", "dior", "ysl"]
wish_list.clear()
print(wish_list) #[]
# syntax
lst = ['item1', 'item2']
lst_copy = lst.copy()
lst_copy is a reference of lst, any changes make in lst_copy will also modify the original.
Plus Operator (+)
# syntax
list3 = list1 + list2
# syntax
list1 = ['item1', 'item2']
list2 = ['item3', 'item4', 'item5']
list1.extend(list2)
# syntax #count() method returns the number of times an item appears in a list
lst = ['item1', 'item2']
lst.count(item)
# syntax
lst = ['item1', 'item2']
lst.index(item)
# syntax
lst = ['item1', 'item2']
lst.reverse()
sort(): this method modifies the original list in ascending order
# syntax
lst = ['item1', 'item2']
lst.sort() # ascending
lst.sort(reverse=True) # descending
sorted()
: returns the ordered list without modifying the original list
Tuples is a collection which is ordered and unchangeable. Tuples are written with round bracket.
- empty tuple
empty_tuple = ()
- tuple with initial values
# syntax
tpl = ('item1', 'item2','item3')
# syntax
tpl = ('item1', 'item2', 'item3')
len(tpl)
- Positive Indexing
# Syntax
tpl = ('item1', 'item2', 'item3')
first_item = tpl[0]
second_item = tpl[1]
- Negative Indexing: -1 refer to the last item
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
first_item = tpl[-4]
second_item = tpl[-3]
- Range of Positive Indexes
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
all_items = tpl[0:4] # all items
all_items = tpl[0:] # all items
middle_two_items = tpl[1:3] # does not include item at index 3
- Range of Negative Indexes
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
all_items = tpl[-4:] # all items
middle_two_items = tpl[-3:-1] # does not include item at index 3 (-1)
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
lst = list(tpl)
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
'item2' in tpl # True
# syntax
tpl1 = ('item1', 'item2', 'item3')
tpl2 = ('item4', 'item5','item6')
tpl3 = tpl1 + tpl2
# syntax
tpl1 = ('item1', 'item2', 'item3')
del tpl1
- unordered
- unchangeable ( but can remove and add new items)
- unindexed
# syntax
st = {}
# or
st = set()
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
len(st)
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
print("Does set st contain item3? ", 'item3' in st) # Does set st contain item3? True
- Add one item using add()
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
st.add('item5')
- Add multiple items using update()
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
st.update(['item5','item6','item7'])
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
st.remove('item2')
- The pop() methods remove a random item from a list
fruits = {'banana', 'orange', 'mango', 'lemon'}
fruits.pop() # removes a random item from the set
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
st.clear()
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
del st
- Converting set to a list removing duplicates
# syntax
lst = ['item1', 'item2', 'item3', 'item4', 'item1']
st = set(lst) # {'item2', 'item4', 'item1', 'item3'} - the order is random, because sets in general are unordered
- Union This method returns a new set
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item5', 'item6', 'item7', 'item8'}
st3 = st1.union(st2)
- Update This method inserts a set into a given set
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item5', 'item6', 'item7', 'item8'}
st1.update(st2) # st2 contents are added to st1
A set can be a subset or super set of other sets:
Subset: issubset() Super set: issuperset
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
st2.issubset(st1) # True
st1.issuperset(st2) # True
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
st2.difference(st1) # set()
st1.difference(st2) # {'item1', 'item4'} => st1\st2
- It returns a set that contains all items from both sets, except items that are present in both sets, mathematically: (A\B) ∪ (B\A)
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
# it means (A\B)∪(B\A)
st2.symmetric_difference(st1) # {'item1', 'item4'}
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
st2.isdisjoint(st1) # False
# syntax
empty_dict = {}
# Dictionary with data values
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(len(dct)) # 4
- access Dictionary items by referring to its key name
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct['key1']) # value1
- or can access used get method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key1'] = 'value-one'
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print('key2' in dct) # True
print('key5' in dct) # False
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct.pop('key1') # removes key1 item
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct.popitem() # removes the last item
del dct['key2'] # removes key2 item
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct.clear()) # None
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
del dct
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
keys = dct.keys()
print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4'])
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
values = dct.values()
print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
Use to check if a condition is true and to execute the block code.
# syntax
if condition:
this part of code runs for truthy conditions
If condition is true the first block will be executed, if not the else condition will run.
# syntax
if condition:
this part of code runs for truthy conditions
else:
this part of code runs for false conditions
Use elif when have multiple conditions.
# syntax
if condition:
code
elif condition:
code
else:
code
Link: https://www.programiz.com/python-programming/if-elif-else
If only have one statement to execute, one for if, and one for else, can be put on the same line
code if condition else code
This is when have if statements inside another if statements.
# syntax
if condition:
code
if condition:
code
Alternatively, can use logical operator and instead of nested condition.
# syntax
if condition and condition:
code
# syntax
if condition or condition:
code
To handle repetitive task, programing languages use loops.
- while loop
- for loop
- It is used to execute block of statement repeatly until a given condition is satisfied. When the condition becomes false, the lines of code after the loop will be continued to be executed.
# syntax
while condition:
code goes here
- If want to run block of code once the condition is no longer true, use else
# syntax
while condition:
code goes here
else:
code goes here
- Use break when want to get out or stop the loop
# syntax
while condition:
code goes here
if another_condition:
break
- Use continute to skip the current iteration
# syntax
while condition:
code goes here
if another_condition:
continue
- loop is used for iterating over a sequence (either a list, a tuple, a dicionary, a set or a string)
# syntax
for iterator in lst:
code goes here
# syntax
while condition:
code goes here
if another_condition:
break
# syntax
for iterator in sequence:
code goes here
if condition:
continue
- range()function is used list of numbers. The range(start, end, step) takes three parameters: starting, ending and increment. By default it starts from 0 and the increment is 1.
# syntax
for iterator in range(start, end, step):
- write loops inside a loop
# syntax
for x in y:
for t in x:
print(t)
- to execute some message when the loop ends
# syntax
for iterator in range(start, end, step):
do something
else:
print('The loop ended')
- use pass to avoid errors or as a placeholder for future statements.
for number in range(6):
pass
- Function is a reuseable block of code or programing statements designed to perfom a certain task. Def keyword is use to define a function in Python.
# syntax
# Declaring a function
def function_name():
codes
codes
# Calling a function
function_name()
Eg:
def generate_full_name ():
first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
full_name = first_name + space + last_name
print(full_name)
generate_full_name () # calling a function
def add_two_numbers ():
num_one = 2
num_two = 3
total = num_one + num_two
print(total)
add_two_numbers()
def generate_full_name ():
first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
full_name = first_name + space + last_name
return full_name
print(generate_full_name())
def add_two_numbers ():
num_one = 2
num_two = 3
total = num_one + num_two
return total
print(add_two_numbers())
-
We can pass different data types as a parameter in a function
-
Single parameter:
# syntax
# Declaring a function
def function_name(parameter):
codes
codes
# Calling function
print(function_name(argument))
Eg:
def learner (name):
message = name + ' is learning Python.'
return message
print(learner('Tina'))
- Two Parameter:
# syntax
# Declaring a function
def function_name(para1, para2):
codes
codes
# Calling function
print(function_name(arg1, arg2))
Eg:
def generate_full_name (first_name, last_name):
space = ' '
full_name = first_name + space + last_name
return full_name
print('Full Name: ', generate_full_name('Tina','Bui'))
# syntax
# Declaring a function
def function_name(para1, para2):
codes
codes
# Calling function
print(function_name(para1 = 'John', para2 = 'Doe')) # the order of arguments does not matter here
Eg:
def generate_full_name (first_name, last_name):
space = ' '
full_name = first_name + space + last_name
return full_name
print(generate_full_name(first_name = 'Tina', last_name = 'Bui'))
# syntax
# Declaring a function
def function_name(param = value):
codes
codes
# Calling function
function_name()
function_name(arg)
Eg:
def learner (name = 'Nancy'):
message = name + ' is learning Python.'
return message
print(learner('Tina'))
Result: Tina is learning Python.
If we do not pass argument when calling a fucntion, it will return the default value
def learner (name = 'Nancy'):
message = name + ' is learning Python.'
return message
print(learner())
Result: Nancy is learning Python.
If do not know the number of arguments pass to a function, can create a function which can take arbitrary number of arguments by adding * before the parameter name.
# syntax
# Declaring a function
def function_name(*args):
codes
codes
# Calling function
function_name(param1, param2, param3,..)
Eg:
def sum_all_nums(*nums):
total = 0
for num in nums:
total += num # same as total = total + num
return total
print(sum_all_nums(2, 3, 5)) # 10