Python Basics Part 2
Python Basics Part 2
Python Basics Part 2
part 2
Python Strings
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
a = "Hello"
print(a)
for x in “word":
print(x)
String Length
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
To check if a certain phrase or character is present in a string, we can use the keyword in.
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
txt = "The best things in life are free!"
print("expensive" not in txt)
Or Use it in an if statement:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Slicing Strings
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Get the characters from "o" in "World!" (position -5) to, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
Modify Strings
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
#returns
HelloWorld
String Concatenation
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
Format - Strings
We cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Format - Strings
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
String Methods
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
String Methods
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
String Methods
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
String Methods
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Python Booleans
Booleans represent one of two values: True or False.
print(10 > 9) #True
print(10 == 9) # False
print(10 < 9) # False
print(bool(x)) #True
print(bool(y)) #True
Python Operators
+ Addition x+y
- Subtraction x-y == Equal x
* Multiplication x*y == y
/ Division x/y != Not equal x != y
% Modulus x%y
> Greater than x>y
** Exponentiation x ** y
< Less than x<
y
// Floor division x // y
>= Greater than or equal to x
>= y
<= Less than or equal to
x <= y
Python Operators
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
NOTE: Set items are unchangeable, but you can remove and/or add items whenever you like.
NOTE: As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.
Python Lists
List items are ordered, changeable, and allow duplicate values. List items are indexed, the first
item has index [0], the second item has index [1] etc. The list is changeable, meaning that we
can change, add, and remove items in a list after it has been created.
print(len(thislist)) # returns 3
List Items - Data Types
List items can be of any data type:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Change the values "banana" and "cherry" with the values “blackberry" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = [" blackberry ", "watermelon"]
print(thislist)
Change List Items
If you insert more items than you replace, the new items will be inserted where you specified, and the remaining
items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items
will move accordingly:
Example
Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) # ['apple', 'banana', 'watermelon', 'cherry']
Add List Items
Using the append() method to append an item:
thislist.append("orange")
print(thislist) # ['apple', 'banana', 'cherry', 'orange']
thislist.insert(1, "orange")
print(thislist) # ['apple', 'orange', 'banana', 'cherry']
Lists
To append elements from another list to the current list, use the extend() method.
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist) # ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist) # ['apple', 'banana', 'cherry', 'kiwi', 'orange']
Remove List Items
The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # ['apple', 'cherry']
If there are more than one item with the specified value, the remove() method removes the
first occurrence:
The pop() method removes the specified index.
thislist.pop(1)
print(thislist) # ['apple', 'cherry']
If you do not specify the index, the pop() method removes the last item.
Remove List Items
The del keyword also removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Note: The clear() method empties the list. The list still remains, but it has no content.
Loop Lists
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
You can also loop through the list items by referring to their index number. Use the range() and len()
functions to create a suitable iterable.
A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an
existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
List Comprehension
With list comprehension you can do all that with only one line of code:
Exercise: Use list comprehension to print all fruits that do not start with letter a
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
You can use the range() function to create an iterable:
newlist = [x for x in range(10)] #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example
Sort the list based on how close the number is to 50:
def myfunc(n):
return abs(n - 50)
Luckily we can use built-in functions as key functions when sorting a list. Try to solve it.
Solution
Perform a case-insensitive sort of the list:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes
made in list1 will automatically also be made in list2.
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
for x in list2:
list1.append(x)
print(list1)
list1.extend(list2)
print(list1)
List Methods
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse()Reverses the order of the list
sort() Sorts the list
Python Tuples
Tuple items are ordered, unchangeable, and allow duplicate values. When we say that tuples are
ordered, it means that the items have a defined order, and that order will not change. Tuples are
unchangeable, meaning that we cannot change, add or remove items after the tuple has been
created.
Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")
Access Tuple Items
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
NOTE: You can perform all the other actions learned on the slides before. Ex: Negative indexing
and ranges..
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called. But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
print(x)
Add or Remove Items
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Note: Convert to list to remove.
Python Sets
Set items are unordered, unchangeable, and do not allow duplicate values. Unordered means
that the items in a set do not have a defined order. Set items can appear in a different order
every time you use them, and cannot be referred to by index or key.
print(thisset)
Add Items
Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use the
add() method.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
To add items from another set into the current set, use the update() method.
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
x = thisdict.get("model")
Access Dictionary Items
The keys() method will return a list of all the keys in the dictionary. x = thisdict.keys()
The values() method will return a list of all the values in the dictionary. x = thisdict.values()
The items() method will return each item in a dictionary, as tuples in a list. x = thisdict.items()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Change Dictionary Items
You can change the value of a specific item by referring to its key name:
thisdict["year"] = 2018
The update() method will update the dictionary with the items from the given argument. The
argument must be a dictionary, or an iterable object with key:value pairs.
thisdict.update({"year": 2020})
Add Dictionary Items
Adding an item to the dictionary is done by Add a color item to the dictionary by using the update()
using a new index key and assigning a value to it: method:
thisdict = {
thisdict = { "brand": "Ford",
"brand": "Ford", "model": "Mustang",
"model": "Mustang", "year": 1964
"year": 1964 }
} thisdict.update({"color": "red"})
thisdict["color"] = "red"
print(thisdict)
Remove Dictionary Items
The pop() method removes the item with the specified key name: thisdict.pop("model")
The popitem() method removes the last inserted item thisdict.popitem()
The del keyword removes the item with the specified key name: del thisdict["model"]
The del keyword can also delete the dictionary completely del thisdict
The clear() method empties the dictionary: thisdict.clear()
Loop Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
} You can also use the You can use the keys() method
for x in thisdict: values() method to return to return the keys of a
for x in thisdict: print(thisdict[x]) values of a dictionary: dictionary:
print(x)
Ford for x in thisdict.keys():
brand Mustang
for x in thisdict.values():
model print(x) print(x)
1964
year
Loop
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
brand Ford
model Mustang
year 1964
Nested Dictionaries
A dictionary can
contain dictionaries, myfamily = {
this is called nested "child1" : {
dictionaries. "name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
print(myfamily["child2"]["name"])
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Python If ... Else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a=2
b = 330
print("A") if a > b else print("B") # short Or use: print("A") if a > b else print("=") if a == b else print("B")
Python While Loops
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the break statement we can stop the loop even if the while condition is true:
Python While Loops
i=1 i=1
while i < 6: while i < 6:
print(i) print(i)
if i == 3: i += 1
continue else:
i += 1 print("i is no longer less than 6")
my_function()
Information can be passed into functions as arguments. Arguments are specified after the function
name, inside the parentheses. You can add as many arguments as you want, just separate them with a
comma.
def my_function(fname):
print(fname + " word")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments
does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
def my_function(food):
for x in food:
print(x)
my_function(fruits)
apple
banana
cherry
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Recursion
Python also accepts function recursion, which means a defined function can call itself.
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
if another_calculation == "no":
break