Python Basics Part 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 79

Python Basics

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)

You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
Strings are Arrays
Strings in Python are arrays of bytes representing unicode characters. However, Python does not
have a character data type, a single character is simply a string with a length of 1. Square
brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.

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.

txt = "The best things in life are free!"


print("free" in txt)
Output: True
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.

txt = "The best things in life are free!"


print("free" in txt)
Output: True
Check String
Use it in an if statement:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

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 to position 5 (not included):


b = "Hello, World!"
print(b[2:5])
Slicing Strings
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])

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 lower() method returns the string in lower case:


a = "Hello, World!"
print(a.lower())
Modify Strings
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“

The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J"))

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)

Use the format() method to insert numbers into strings:


age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Format - Strings
The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:

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 a message based on whether the condition is True or False:


a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Python Booleans
Evaluate two variables:
x = "Hello"
y = 15

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)

is Returns True if both variables are the same object x is y


is not Returns True if both variables are not the same object x is not y
in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y
Python Collections (Arrays)
There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate members.


Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.
Dictionary is a collection which is ordered and changeable. No duplicate members.

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.

thislist = ["apple", "banana", "cherry"]


print(thislist)
Output: ["apple", "banana", "cherry"]

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]

A list can contain different data types:


list1 = ["abc", 34, True, 40, "male"]
print(type(mylist)) # returns <class 'list'>
Access Items
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[1]) # prints the second element
print(thislist[-1]) # prints the last element
print(thislist[2:5]) # from 2 to 5 (5 not included)
print(thislist[:4]) # returns the items from the beginning to, but NOT including, "kiwi"
print(thislist[-4:-1]) # returns the items from "orange" (-4) to, but NOT including "mango" (-1)
Change List Items
To change the value of a specific item, refer to the index number:
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = “new"
print(thislist)

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:

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert()
method.
The insert() method inserts an item at the specified index:

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 = ["apple", "banana", "cherry"]

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)

The del keyword can also delete the list completely.


thislist = ["apple", "banana", "cherry"]
del 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.

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i]) #Print all items by referring to their index number:
Loop Lists
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list,
then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the
index by 1 after each iteration.
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1

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:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = [x for x in fruits if "a" in x]
print(newlist)

newlist = [expression for item in iterable if condition == True]


List Comprehension
Only accept items that are not "apple":
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"] #['banana', 'cherry', 'kiwi', 'mango']

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]

Accept only numbers lower than 5:


newlist = [x for x in range(10) if x < 5] #[0, 1, 2, 3, 4]
Expression
The expression is the current item in the iteration, but it is also the outcome, which you can
manipulate before it ends up like a list item in the new list:

Set the values in the new list to upper case:


newlist = [x.upper() for x in fruits]
Expression
The expression can also contain conditions, not like a filter, but as a way to manipulate the
outcome:
Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]

Exercise: Set all values in the new list to 'hello‘


fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
print(newlist)
Sort Lists
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Sort the list descending:


thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
Customize Sort Function
You can also customize your own function by using the keyword argument key = function. The function will return a
number that will be used to sort the list (the lowest number first):

Example
Sort the list based on how close the number is to 50:

def myfunc(n):
return abs(n - 50)

thislist = [100, 50, 65, 82, 23]


thislist.sort(key = myfunc)
print(thislist)
Exercise
You have a list of names, and you want to sort them by the length of each name. Write a Python
program that uses a customized key function to sort the list in ascending order based on the
length of the names. Ensure the names with the same length appear in their original order.
Solution
names = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank"]

# Define a custom key function to sort by name length


def custom_key(name):
return len(name)

# Sort the names using the custom key function


sorted_names = sorted(names, key=custom_key)

# Print the sorted list


print(sorted_names)
Exercise
By default the sort() method is case sensitive, resulting in all capital letters being sorted before
lower case letters:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

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)

Or Make a copy of a list with the list() method:


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Join Two Lists
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

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.

Convert the tuple into a list to be able to change it:


x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

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.

Duplicate values will be ignored:


thisset = {"apple", "banana", "cherry", "apple"}

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)

print(thisset) #{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}


Python Dictionaries
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is
ordered*, changeable and do not allow duplicates.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print(thisdict["brand"])

Duplicate values will overwrite existing values:


Access Dictionary Items
You can access the items of a dictionary by referring to its key name, inside square brackets:

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()

Exercise: Check if a key exists


Solution
To determine if a specified key is present in a dictionary use the in keyword:

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")

if a > b: print("a is greater than b") #short

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")

With the else statement we can run a block of code once


With the continue statement we when the condition no longer is true:
can stop the current iteration, and
continue with the next:
Python Functions
def my_function():
print("Hello from a function")

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)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


Default Parameter Value
The following example shows how to use a default parameter value. If we call the function without argument,
it uses the default value:

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)

fruits = ["apple", "banana", "cherry"]

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

print("Recursion Example Results")


tri_recursion(6)
Exercise
Write a Python program that acts as a simple calculator. It should take two numbers and an
operator (+, -, *, /) as input from the user and perform the corresponding operation.
Solution # Perform the operation based on the operator
if operator == "+":
result = num1 + num2
while True: elif operator == "-":
result = num1 - num2
# Input: Two numbers and an operator elif operator == "*":
num1 = float(input("Enter the first number: ")) result = num1 * num2
elif operator == "/":
operator = input("Enter an operator (+, -, *, /): ") if num2 == 0:
result = "Division by zero is not allowed"
num2 = float(input("Enter the second number: ")) else:
result = num1 / num2
else:
result = "Invalid operator"

# Print the result


print("Result:", result)
Solution
# Ask if the user wants to make another calculation
while True:
another_calculation = input("Do you want to make another calculation? (yes/no): ").lower()
if another_calculation == "yes":
break
elif another_calculation == "no":
break
else:
print("Invalid response. Please enter 'yes' or 'no'.")

if another_calculation == "no":
break

You might also like