Python Basics
Python 3 intro
Types
Immutable types
Once these types are defined cannot be changed Immutable
bool
str
int
float
bytes
tuples
Example for tuples:
x =(1,2)
x[0] = 5 # This cannot be done!, the element cannot be changed but
x = (5,9) # x can be assigned a new tuple
Mutable types
The list below are mutable as they can be modified once they are defined.
list
set
dict
Variables
# Assign variables
apples = 1000
ticket = 99
gas = 300
# Adding numbers
total = apples + ticket + gas
print(total)
# Assigning power to a number
x = 3 ** 4 # Here 3 multiplied 4 times
print(x)
# Rounding the decimal number to 2
a = 5.4593049
print(round(a,2))
1399
81
5.46
Teting hello
strings
str1 = "Hello, World"
print(str1[0])
print(str1[2])
# Output
# H
# l
# str1[1] = "A" # Strings are immutable cannot be assigned - TypeError: 'str' object does not support item assignment
print(len(str1))
# Output
# 12
# start at 0 index and ends at 3 on both the print statements below
print(str1[0:3])
print(str1[:3])
# Output
# Hel
# Hel
# starts from 7th position and goes all the way to the end of the string
print(str1[7:12])
print(str1[7:])
# Output
# World
# World
Assigning string with multiple lines
str1 = '''Hello
World
ABCD
123456789
'''
Lists
items = ["Sam","Jack","Bob","Alice"]
print(items)
# Output
# ['Sam', 'Jack', 'Bob', 'Alice']
# print the last item in the list
print(items[-1])
# Output
# Alice
# print the first two items in the list
print(items[:2])
# Output
# ['Sam', 'Jack']
python list - append, insert, join, length, lookup
# append - adds the item to the list at the end of the list
items.append("Don")
print(items)
# Output
# ['Sam', 'Jack', 'Bob', 'Alice', 'Don']
# insert - insert the item at a specific position in the list (Remember index starts from 0)
items.insert(1, "Dog")
print(items)
# Output
# ['Sam', 'Dog', 'Jack', 'Bob', 'Alice', 'Don']
## Join two lists
fruits = ["Apple", "Banana"]
new_Items = items + fruits
print(new_Items)
# Output
# ['Sam', 'Dog', 'Jack', 'Bob', 'Alice', 'Don', 'Apple', 'Banana']
# Size of the list
print(len(new_Items))
# Output
# 8
# Lookup in the list
print("Apple" in new_Items)
# Output
# True
list comprehension
Creates a list of size 5 with values from 0 to 4
x = [i for i in range(5)]
print(x)
# Output
# [0, 1, 2, 3, 4]
list comprehension with condition
The comprehension can include a conditional statement. Create a list with all even number in it.
x = [i for i in range(10) if i % 2 == 0]
print(x)
# Output
# [0, 2, 4, 6, 8]
Create a List from a string
x = list("some-sting")
print(x)
# Output
# ['s', 'o', 'm', 'e', '-', 's', 't', 'i', 'n', 'g']
dict - dictionary
A dictionary is a key value pair collection. Key and value can of any data type or combination as below.
dictA = {
"same1": "abcd",
"same2": "abcd2",
"same3": "abcd3",
"d1": {
"a1": "try1",
"a2": "try2",
"a3": "try3",
},
1: ["a","b","c",1,2]
}
Accessing the data from the dictionary
print(dictA)
# {'same1': 'abcd', 'same2': 'abcd2', 'same3': 'abcd3', 'd1': {'a1': 'try1', 'a2': 'try2', 'a3': 'try3'}, 1: ['a', 'b', 'c', 1, 2]}
print(dictA["same1"])
# abcd
print(dictA["d1"])
# {'a1': 'try1', 'a2': 'try2', 'a3': 'try3'}
print(dictA["d1"]["a2"])
# try2
print(dictA[1])
# ['a', 'b', 'c', 1, 2]
Add data to dictionary
Adding data to the dictionary
dictA[2] = {
"h1" : "hello",
"w1" : "world"
}
print(dictA[2]["w1"])
# world
Updating the dictionary
dictA[2]["w1"] = "****ABCD****"
print(dictA[2]["w1"])
# ****ABCD****
get only the values
print(dictA[2].values())
# dict_values(['hello', '****ABCD****'])
Remove item with POP()
dict2 = {
"ab1" : "hello",
"ab2" : "world",
"c1" : {
"g1" : "b1",
"g2" : "b2",
},
"c2" : "Wonder",
"c3" : {
"ch1" : "Monkey",
"ch2" : "Cat",
},
}
print(dict2)
# {'ab1': 'hello', 'ab2': 'world', 'c1': {'g1': 'b1', 'g2': 'b2'}, 'c2': 'Wonder', 'c3': {'ch1': 'Monkey', 'ch2': 'Cat'}}
dict2.pop("c1")
print(dict2)
# {'ab1': 'hello', 'ab2': 'world', 'c2': 'Wonder', 'c3': {'ch1': 'Monkey', 'ch2': 'Cat'}}
clear the dictionary
The value of c3 is cleared.
dict2["c3"].clear()
print(dict2)
# {'ab1': 'hello', 'ab2': 'world', 'c2': 'Wonder', 'c3': {}}
Iterate through dictionary
# for k in dictA:
# or
for k in dictA.keys():
print(f"{k} : {dictA[k]}")
# same1 : abcd
# same2 : abcd2
# same3 : abcd3
# d1 : {'a1': 'try1', 'a2': 'try2', 'a3': 'try3'}
# 1 : ['a', 'b', 'c', 1, 2]
# 2 : {'h1': 'hello', 'w1': '****ABCD****'}
functions
Passing arguments and parameters types
positional parameters
Order of the parameters should me maintained when passing the arguments to the function
def some_data(x, y):
print(f"x= {x}, y={y}")
pass
some_data(5,9)
# Output
# x=5, y=9
passing by named arguments
def some_data(x, y):
print(f"x= {x}, y={y}")
pass
some_data(y = 10, x = 3)
Output show the order of passing the arguments are not required since the arguments were passed with name to the correct parameters
x=3, y=10
optional parameters
def some_data_optional(x, y, z = 100):
print(f"x= {x}, y= {y} z= {z}")
pass
some_data_optional(y = 9, x = 5)
z is assigned the default value to 100 even though z argument is not passed in the function
x= 5, y= 9, z= 100
*args - accepts any number of args
def some_data_args(x, y, *args):
print(f"x= {x}, y= {y} args= {args}")
print(type(args))
pass
some_data(100,22,44,555,666,77777)
args
accepts any number of positional arguments and args is of the type tuple
x= 100, y= 22 args= (44, 555, 666, 77777)
<class 'tuple'>
**kwargs - accepts keyword arguments
def some_kwargs(x, *args, **kwargs):
print(f"x= {x}, args= {args}, kwargs= {kwargs}")
print(f"args type: {type(args)}")
print(f"kwargs type: {type(kwargs)}")
pass
some_kwargs(x=40, j=66, my="John", pack={"some","day"})
x= 40, args= (), kwargs= {'j': 66, 'my': 'John', 'pack': {'some', 'day'}}
args type: <class 'tuple'>
kwargs type: <class 'dict'>
passing arguments with deconstruction
def some_dcon(x, y, a, b, c):
print(f"a= {a}, b= {b}, c={c}, x={x}, y={y}")
pass
some_dcon(*[100,9], **{"a":"hello","b": "world", "c": "again"})
Output
a= hello, b= world, c=again, x=100, y=9