Python Learning

You can use the Jupyter notebook to code with Python programming language in cells in addition to adding some text using the markdown language.

And also in the jupyter notebook, you can import any Python package in the Python library and use it directly, for example, Numpy Matplotlib and Pandas libraries, you can use all of them by importing them, using the import statement.

A list is a mutable and ordered collection of items.

1
2
3
4
5
6
7
8
#List creation
new_list = []
new_list1 = list()
print(new_list)
print(new_list1)

#Type of list
type(new_list)
1
2
3
4
5
6
#List of numbers
nums = [1, 2, 3, 4, 5]
nums1 = list((10, 15, 20))

print(type(nums))
print(type(nums1))
1
2
3
#List of strings
str_list = ["blue", "red", "yellow"]
print(str_list)
1
2
3
#Muliple types in a list
mixed_list = ["Blue", True, 1, 3.5]
print("The mixed list:", mixed_list)
1
2
3
#List in a list
nums = [1, 2, [3, 3.1, 3.5], 4, 5]
print(nums)
1
2
3
4
5
6
7
#Accessing list items with the index number
print(nums[0])
print(nums[1])
print(nums[2])

#Knowing the number of items in list
len(nums)
1
2
3
4
5
6
nums[0:3] # [1, 2, [3, 3.1, 3.5]]
nums[:3]  # [1, 2, [3, 3.1, 3.5]]
nums[3:]  # [4, 5]

print(nums[-1])
print(nums[-2])
1
2
3
4
5
6
7
colors = ["red", "black", "white"]

"white" in colors         # False
"blue" not in colors      # True

colors.append("yellow")
print(colors)             # ['red', 'black', 'white', 'yellow']
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
colors.insert(2, "green")
colors # ['red', 'black', 'green', 'white', 'yellow']

colors.pop(3)  # 'white'
colors         # ['red', 'black', 'green', 'yellow']

colors.extend(["indigo", "orange"]) 
colors          # ['red', 'black', 'green', 'yellow', 'indigo', 'orange']

del colors[0]
colors        # ['black', 'green', 'yellow', 'indigo', 'orange']
1
2
3
4
5
6
7
8
nums = tuple((1, 2, 3, 4, 5))
nums1 = (1, 2, 3, 4, 5, 6, 7, 8)

print(type(nums))   # <class 'tuple'>
print(type(nums1))  # <class 'tuple'>

type(nums)          # tuple
len(nums1)          # 8
1
2
3
4
5
6
7
8
9
nums1[0]            # 1
nums1[0:3]          # (1, 2, 3)
nums[1] = 10
# ---------------------------------------------------------------------------
# TypeError                                 Traceback (most recent call last)
# Input In [3], in <cell line: 1>()
# ----> 1 nums[1] = 10
#
# TypeError: 'tuple' object does not support item assignment

You cannot change the value of the second item from the nums tuple. But if you want to change the variable that is called nums, you can change the whole variable. You can change the tuple completely, not a specific item.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
new_fruits = tuple(("Orange", "Cherry", "Lemon"))
"Orange" in new_fruits          # True
"Cherry" not in new_fruits      # False
del new_fruits
new_fruits
# ---------------------------------------------------------------------------
# NameError                                 Traceback (most recent call last)
# <ipython-input-75-3881ea8ebbd2> in <module>
# ----> 1 new_fruits
#
# NameError: name 'new_fruits' is not defined

If you want to access the new_fruits after that, after deleting it, you will get an error after that because this tuple doesn’t exist anymore.

Dictionary is mutable key value pairs to store collections. Syntax: {key:value} or dict({key:value})

1
2
3
4
5
new_D = {"Ronaldo": 36, "Jane": 34, "Smith": 27}
new_D1 = dict({'Daniel': 33, 'Samuel': 24, 'Sunny': 30})

print(type(new_D))     # <class 'dict'>
print(type(new_D1))    # <class 'dict'>
1
2
3
4
5
6
7
8
#Sequence of tuples
children = dict({
    ("Child1", "5"),
    ("Child2", "6"),
    ("Child3", "7"),
})
type(children)         # dict
# It's possible to insert tuples, in a dictionary.
1
2
3
4
5
6
7
8
9
new_D["Jane"]          # 34
new_D["Jane"] = "35"
new_D                  # {'Ronaldo': 36, 'Jane': '35', 'Smith': 27}
del new_D["Jane"]
new_D                  # {'Ronaldo': 36, 'Smith': 27}
"Lucas" in new_D       # False
# You should know that a dictionary items are changeable or mutable so you can change the value.

of any key, you can change the value of any item from inside a dictionary.

Set is unordered and immutable collection, no duplicates in sets. Syntax: {1,2,3} or set([1,2,3])

1
2
3
4
5
6
set_nums = set((2, 4, 6, 8, 10))
set_nums1 = {1, 2, 3, 4, 5, 6}
print(set_nums)           # {2, 4, 6, 8, 10}
print(set_nums1)          # {1, 2, 3, 4, 5, 6}
print(type(set_nums))     # <class 'set'>
print(type(set_nums1))    # <class 'set'>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
set('Python')             # {'P', 'h', 'n', 'o', 't', 'y'}
x = set({1: "name", 2: "age"})
type(x)                   # set
del x
x
# ---------------------------------------------------------------------------
# NameError                                 Traceback (most recent call last)
# Input In [33], in <cell line: 1>()
# ----> 1 x
#
# NameError: name 'x' is not defined

You can use the For loop to execute a part of code once for each element in sequence or collection of elements, or you can use it to iterate over sequences or over collection of values. For example, you can use the follow up to iterate over lists, to iterate over tuples and so on.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
for chars in "Arknights":
    print(chars)
# A
# r
# k
# n
# i
# g
# h
# t
# s
1
2
3
4
5
6
7
for i in range(5):
    print("Arknights")
# Arknights
# Arknights
# Arknights
# Arknights
# Arknights
1
2
3
4
5
6
7
for i in range(5, 15):
    print(i + i)
# 10
# 12
# 14
# 16
# 18
1
2
3
4
5
for i in [1,2,3]:
    print(i)
# 1
# 2
# 3
  • Functions: block of related statements to perform actions.
  • Function types: Built-in and User-Defined Functions
  • Call it to work and you can call it many time.
1
2
3
4
5
6
7
abs(11)                              # 11
abs(-15.33)                          # 15.33
bool(1)                              # True
bool(0)                              # False
complex(3, 4)                        # (3+4j)
x = dict(name = "Ahmed", age = 28)  
x                                    # {'name': 'Ahmed', 'age': 28}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
dir(x)
# ['__class__',
# '__class_getitem__',
# '__contains__',
# '__delattr__',
# '__delitem__',
# '__dir__',
# '__doc__',
# '__eq__',
# '__format__',
# '__ge__',
# '__getattribute__',
# '__getitem__',
# '__gt__',
# '__hash__',
# '__init__',
# '__init_subclass__',
# '__ior__',
# '__iter__',
# '__le__',
# '__len__',
# '__new__',
# '__or__',
# '__reduce__',
# '__reduce_ex__',
# '__repr__',
# '__reversed__',
# '__ror__',
# '__setattr__',
# '__setitem__',
# '__sizeof__',
# '__str__',
# '__subclasshook__',
# 'clear',
# 'copy',
# 'fromkeys',
# 'get',
# 'items',
# 'keys',
# 'pop',
# 'popitem',
# 'setdefault',
# 'update',
# 'values']
# We used the dir function to get all the attributes and methods related to the variable that stores our dictionary type or our dictionary data structure.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
x = input("Entered name: ")
# Entered name: ...
print("Hi, Functions!")
# Hi, Functions!
sum([1, 2, 3])  # 6
x = [1, 2, 3]
y = [4, 5, 6]
z = zip(x, y)
print(list(z))
# [(1, 4), (2, 5), (3, 6)]
# Z, the variable that contains the zip operation, this will design a list based on tuples. You will see all the tuples inside that list, as in the output, as you can see, exactly one from the first list and four from the second list. The first item on the first item, the second item and the second item.

There are different uses for the Lambda Function.

1
2
3
4
5
6
multiply = lambda x: x * 20
print(multiply(2))              # 40

remaind = lambda n: n % 2
print(remaind(11))              # 1
print(remaind(20))              # 0
1
2
3
4
5
def testing(n):
    return lambda i: i * n
r1 = testing(120)
print(r1(5))                                # 600
print(r2(10))                               # 2000
1
2
3
4
5
6
7
8
9
# return a generic function, then use lambda expression.
def handle(f, x):
    return f(x)
def is_even(x):
    return x % 2 == 0
kq1 = handle(lambda x: x ** 2, 9)
print("kq1= ", kq1)                         # 81
kq2 = handle(lambda x: is_even(x), 7)        
print("kq2= ", kq2)                         # False
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# using function and lambda in switch-case dict.
from math import *
def indirect(i,f=0,x=0):
    switcher = {
        0: lambda:'zero',
        1: lambda: exp(x),
        2: lambda: f(x)
    }
    func = switcher.get(i,lambda: "Invalid")
    return func()
print(indirect(0))                          # zero
print(indirect(2,lambda x: x ** 2,9))       # 81
print(indirect(1))                          # 1
print(indirect(1,0,1))                      # 2.718281828459045
print("A= ", indirect(2,lambda x: log1p(x),9)) #Return the natural logarithm of 1+x (base e)
# 2.302585092994046
print(indirect(3,lambda x: exp(x),9))       # Invalid