Python
Python
at is Python?
hon is a popular programming language created by Guido van Rossum in 1991. It is used in many fields l
Web development (building websites & web apps)
oftware development (creating programs & tools)
Mathematics (solving equations, graphs, AI, etc.)
ystem scripting (automating tasks on a computer)
Example:
#This is a comment.
print("Hello, World!")
Visual presentation:
📝 ➝ # This is a comment. (Ignored by Python)
➝ "Hello, World!" (Displayed on screen)
• Comments can be placed at the end of a line, and Python will ignore the rest of the line.
Example:
print("Hello, World!") #This is a comment.
Explanation:
The print("Hello, World!") command displays "Hello, World!" on the screen.
# This is a comment. is written after the statement. Python ignores everything after #.
Multiline Comments:
Python does not really have a syntax for multiline comments. To add a multiline comment, you
could insert a # for each line.
Python Variables:
Variables are containers for storing data values. Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Variables do not need to be declared with any type, and can even change type after they
have been set.
Casting of variables:
If you want to specify the data type of a variable, this can be done with casting.
Example:
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
print(z)
Output:
3
3
3.0
Get the type:
You can get the data type of a variable with the type() function.
Single or Double quotes?
Example:
x = "John"
print(x)
#double quotes are the same as single quotes:
x = 'John'
print(x)
Output:
John
John
Case – Sensitive:
Variable names with more than one word can be difficult to read. There are several techniques
you can use to make them more readable.
1. Camel case:
Each word, except the first, starts with a capital letter
2. Pascal case:
Each word starts with a capital letter.
3. Snake case:
Each word is separated by an underscore character.
And you can assign the same value to multiple variables in one line:
Unpack a collection:
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Python Output Variables:
Example:
x = "🐍 Python is 😍 awesome"
print(x)
Output:
🐍 Python is 😍 awesome
Example:
x = "🐍 Python"
y = "💡 is"
z = "😍 awesome"
print(x, y, z)
Output:
🐍 Python 💡 is 😍 awesome
• You can also use the + operator to output multiple variables.
Example:
x = "🐍 Python"
y = "💡 is"
z = "😍 awesome"
print(x+y+z)
Output:
🐍 Python 💡 is 😍 awesome
Example:
x=5
y = 10
print(x + y)
Output:
15
Python Global Variable:
Variables that are created outside of a function (as in all of the examples in the previous pages)
are known as global variables. Global variables can be used by everyone, both inside of functions
and outside.
Example:
Create a variable outside of a function and use it inside the function.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Output:
Python is awesome
If you create a variable with the same name inside a function, this variable will be local, and
can only be used inside the function. The global variable with the same name will remain as
it was, global and with the original value.
Example:
Create a variable inside a function, with the same name as the global variable.
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Output:
Python is fantastic
Python is awesome
Lists in Python:
The data type list is an ordered sequence that is mutable and made up of one or more elements.
A list can have elements of different data types, such as integer, string, tuple or even another list.
List is very useful to group together elements of mixed data types.
Elements of lists are enclosed in squared brackets and are separated by coma.
List indices also starts from 0.
ample:
List1 of mixed data types.
t1 = [20,0.5, “python”]
nt(List1)
• List length:
To determine how many items a list has, use the len() function.
Example:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output: 3
• Type:
From Python's perspective, lists are defined as objects with the data type 'list’.
Example:
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Access items:
t items are indexed, and you can access them by referring to the index number.
ample:
slist = ["apple", "banana", "cherry"]
nt(thislist[1])
tput: banana
Negative indexing.
gative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item etc.
ample:
slist = ["apple", "banana", "cherry"]
nt(thislist[-1])
tput: cherry
nge of indexes:
an specify a range of indexes by specifying where to start and where to end the range. When specifying a ra
turn value will be a new list with the specified items.
ple:
t = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
thislist[2:5])
Append item:
o add an item to the end of the list, use the append() method.
xample:
hislist = ["apple", "banana", "cherry"]
hislist.append("orange")
rint(thislist)
here are more than one item with the specified value, the remove() method removes the first occurrence.
• Remove specified index:
The pop() method removes the specified index.
Example:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Example:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple’]
Output:
[23, 50, 65, 82, 100]
Sort list in descending order:
sort descending, use the keyword argument reverse = True.
ample:
slist = ["orange", "mango", "kiwi", "pineapple", "banana"]
slist.sort(reverse = True)
nt(thislist)
tput:
ineapple', 'orange', 'mango', 'kiwi', 'banana’]
ample:
slist = ["banana", "Orange", "Kiwi", "cherry"]
slist.sort()
nt(thislist)
tput:
iwi', 'Orange', 'banana', 'cherry']
an use built-in functions as key functions when sorting a list. So, if you want a case-insensitive sort function
tr.lower as a key function.
ple:
t = ["banana", "Orange", "Kiwi", "cherry"]
t.sort(key = str.lower)
thislist)
ut:
ana', 'cherry', 'Kiwi', 'Orange’]
verse order:
if you want to reverse the order of a list, regardless of the alphabet? The reverse() method reverses the cu
g order of the elements.
ple:
t = ["banana", "Orange", "Kiwi", "cherry"]
t.reverse()
thislist)
ut:
ry', 'Kiwi', 'Orange', 'banana']
opy a list:
cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes
e in list1 will automatically also be made in list2.
mple:
st = ["apple", "banana", "cherry"]
st = thislist.copy()
(mylist)
ut:
ple', 'banana', 'cherry’]
st() method:
her way to make a copy is to use the built-in method list().
mple:
st = ["apple", "banana", "cherry"]
st = list(thislist)
(mylist)
ut:
ple', 'banana', 'cherry']
Tuples in Python.
ut:
le', 'banana', 'cherry’)
ple items:
items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has in
econd item has index [1] etc.
dered:
n we say that tuples are ordered, it means that the items have a defined order, and that order will not chan
Unchangeable:
les are unchangeable, meaning that we cannot change, add or remove items after the tuple has been creat
llows duplicates:
ce tuples are indexed, they can have items with the same value.
mple:
tuple = ("apple", "banana", "cherry", "apple", "cherry")
t(thistuple)
put:
ple', 'banana', 'cherry', 'apple', 'cherry’)
uple length.
determine how many items a tuple has, use the len() function.
mple:
tuple = tuple(("apple", "banana", "cherry"))
t(len(thistuple))
put:
eate tuple with one item:
eate a tuple with only one item, you must add a comma after the item, otherwise Python will not recognize
ple.
mple:
uple = ("apple",)
(type(thistuple))
T a tuple
uple = ("apple")
(type(thistuple))
put:
ss 'tuple'>
ss 'str’>
(tuple3)
• Tuple data type:
Tuple items can be of any data type.
Example:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
Output:
('apple', 'banana', 'cherry’)
(1, 5, 7, 9, 3)
(True, False, False)
Example:
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)
Output:
('abc', 34, True, 40, 'male')
• Tuple type():
From Python's perspective, tuples are defined as objects with the data type 'tuple’.
Example:
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
Output:
<class 'tuple’>
Example:
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
Output:
('apple', 'banana', 'cherry')
• Access tuple items:
You can access tuple items by referring to the index number, inside square brackets.
Example:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Output:
banana
• Negative indexing:
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item et
Example:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Output:
cherry
ange of index:
can specify a range of indexes by specifying where to start and where to end the range. When specifying a
ge, the return value will be a new tuple with the specified items.
mple:
tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
t(thistuple[2:5])
put:
erry', 'orange', 'kiwi’)
eaving out the start value, the range will start at the first item:
mple:
tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
t(thistuple[:4])
put:
ple', 'banana', 'cherry', 'orange’)
By leaving out the end value, the range will go on to the end of the tuple:
Example:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:])
Output:
('cherry', 'orange', 'kiwi', 'melon', 'mango’)
Example:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[-4:-1])
Output:
('orange', 'kiwi', 'melon’)
Output:
{'apple', 'cherry', 'banana’}
Output:
{'banana', 'cherry', 'apple'}
• True and 1 is considered the same value.
Example:
thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)
Output:
{True, 2, 'banana', 'cherry', 'apple’}
Example:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Output:
3
• Data type:
Set items can be of any data type.
Example:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
Output:
{'cherry', 'apple', 'banana’}
{1, 3, 5, 7, 9}
{False, True}
Output:
{True, 34, 40, 'male', 'abc'}
• Type():
From Python's perspective, sets are defined as objects with the data type 'set’.
Example:
myset = {"apple", "banana", "cherry"}
print(type(myset))
Output:
<class 'set’>
Example:
thisset = set(("apple", "banana", "cherry"))
print(thisset)
Output:
{'banana', 'cherry', 'apple'}
cess item:
annot access items in a set by referring to an index or a key. But you can loop through the set items using
or ask if a specified value is present in a set, by using the in keyword.
mple:
et = {"apple", "banana", "cherry"}
in thisset:
t(x)
ut:
y
na
e
ut:
mple: Check if "banana" is NOT present in the set.
set = {"apple", "banana", "cherry"}
t("banana" not in thisset)
put:
e
hange item:
e a set is created, you cannot change its items, but you can add new items.
dd items:
e a set is created, you cannot change its items, but you can add new items. To add one item to a set use th
() method.
mple:
set = {"apple", "banana", "cherry"}
set.add("orange")
t(thisset)
put:
ange', 'banana', 'cherry', 'apple'}
set:
items from another set into the current set, use the update() method.
ple:
t = {"apple", "banana", "cherry"}
al = {"pineapple", "mango", "papaya"}
t.update(tropical)
hisset)
t:
e', 'mango', 'cherry', 'pineapple', 'banana', 'papaya’}
iterable:
bject in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionari
ple:
t = {"apple", "banana", "cherry"}
= ["kiwi", "orange"]
t.update(mylist)
hisset)
t:
ana', 'cherry', 'apple', 'orange', 'kiwi'}
Remove item:
To remove an item in a set, use the remove(), or the discard() method.
Example:
hisset = {"apple", "banana", "cherry"}
hisset.remove("banana")
print(thisset)
Output:
{'apple', 'cherry’}
If the item to remove does not exist, remove() will raise an error.
Example:
hisset = {"apple", "banana", "cherry"}
hisset.discard("banana")
print(thisset)
Output:
{'cherry', 'apple'}
can also use the pop() method to remove an item, but this method will remove a random item, so you cann
what item that gets removed. The return value of the pop() method is the removed item.
le:
= {"apple", "banana", "cherry"}
sset.pop()
) #removed item
hisset) #print the set
t:
a
ry', 'apple’}
t:
• The del keyword will delete the set completely.
Example:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
• Loop items:
You can loop through the set items by using a for loop.
Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
banana
apple
cherry
Python Dictionary:
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
rint(thisdict)
utput:
brand': 'Ford', 'model': 'Mustang', 'year': 1964}
ctionary items:
onary items are ordered, changeable, and do not allow duplicates. Dictionary items are presented in key:va
, and can be referred to by using the key name.
thisdict["brand"])
ut:
Duplicates are not allowed:
ictionaries cannot have two items with the same key.
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
rint(thisdict)
utput:
brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Length of dictionary:
o determine how many items a dictionary has, use the len() function.
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
rint(len(thisdict))
Data types:
he values in dictionary items can be of any data type.
xample:
isdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
int(thisdict)
utput:
brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue’]}
Type():
ctionaries are defined as objects with the data type 'dict’.
xample:
isdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
int(type(thisdict))
dist() Constructor:
t is also possible to use the dict() constructor to make a dictionary.
xample:
hisdict = dict(name = "John", age = 36, country = "Norway")
rint(thisdict)
Output:
'name': 'John', 'age': 36, 'country': 'Norway’}
Accessing item:
ou can access the items of a dictionary by referring to its key name, inside square brackets.
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
= thisdict["model"]
rint(x)
Output:
Mustang