Maroof - Sar Python Coding - A Beginner - S Guide To Programming Independently Published - 2024
Maroof - Sar Python Coding - A Beginner - S Guide To Programming Independently Published - 2024
You can start from the very beginning. I assume you have
already worked with IDEs, and installing the development
environment wouldn't be an issue.
In this output, the user enters the character "$," and the program draws a
triangle with the dollar symbol.
Output of the code
Enter a character: $
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
2 Secret Number
CH 5: Example 2A
Write a program that allows users to guess a secret number from 1 to 10. If
the user's guess number is correct, the program confirms that the guess
number is correct; otherwise, it is incorrect.
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
5 Lottery
CH 11: Exercise 1
Create a program allowing users to shuffle the names in the list below.
Upon executing the program, the names order is selected randomly. The
winners are determined based on the following ranking:
lottery.py
from random import shuffle
names = ["Emma", "David", "Jack", "George", "Ronald", "Vera", "Bruce"]
# add the rest of your code here.
The output of the program is shown below. Remember that the winners will
be randomly different each time you run the program.
The names randomly:
['Vera', 'Emma', 'Bruce', 'Ronald', 'David', 'Jack', 'George']
The winner of one million dollars is: Vera
The winner of 500 thousand dollars is: Emma
The winner of 100 thousand dollars is: Bruce
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
7 Select Cards
CH 11: Example 3B
The following program declares a list with the card elements and values.
The choice function allows you to select a card randomly.
cards.py
from random import choice
cards = ["clubs", "Diamonds", "Hearts", "Spades"]
card_value = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
# add your code here
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
8 Registration Date
CH 12: Exercise 1
Upon registering on your website, the system automatically captures and
saves the registration date and time. Develop a program that allows users to
enter their names, and the program displays the user's name alongside the
current registration date and time.
Output: The user enters Jack, and the program automatically prints the
current date and time.
Enter your name: Jack
Jack's registration was recorded on
03/02/2024 At 07:35:33 PM
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
10 Function Calculator
CH 9: Quiz 1
What happens if the following code is run?
calculator.py
def calculator(nr1, nr2, nr3): # line 1
result = nr1 + nr2 - nr3 # line 2
return result # line 3
print(calculator(22, 20, 10)) # line 4
The solution(s) of this code issue and its explanation, including many more,
are covered in this book.
1. A Beginner's Guide
It is recommended that you read this chapter if you are a total beginner in
programming. In the following chapters, many programs are presented, and
testing them by running them is essential. That gives you an idea of how
running code and displaying the output of a program works.
Notice
You must first download and install Python before installing the IDE
program. That would make the installation easier and avoid errors.
After installing Python and the IDE, you can open the IDE Program, as
shown in the following illustration. You can find the instructions on the IDE
provider's website.
After installing your IDE successfully and opening it, you will see
something as shown in the image below. Most of the IDE screens are
divided into three areas.
First area: In the upper left, you see your files with Python
extensions such as "register.py."
Second area: If you double-click on the file, the content of the
file appears in the upper right area, called the editor, where you
can write, edit, or update your code.
Third area: This is the output area at the bottom of the screen;
you can run the program by clicking on the green arrow at the
top or on the left of the output area. Once you click the green
arrow, also called the run button, the code output appears, as
shown in the image below.
Notice
The buttons for running the program and others could differ from one IDE
to another. For more information, read the instructions of the IDE
provider.
Declaring Variables
In Python, creating variables is similar to other programming languages. It
starts with the name of the variable and assigning a value to it.
That is because the variables are declared, and values are assigned to them
only in the memory. Programmers have control over when and where to
display those data.
Notice
The string variable value should be enclosed in either single or double
quotes, as demonstrated in the following example.
register.py
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
To print variable values, we use the function print, which ends with opening
parenthesis and closing it: print(). The variable's name should be passed as a
parameter to the print function between the parenthesis, as shown in the
example below.
The variable values are printed to the standard output if the following program
is run.
register.py
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
# printing the variable values
print(name)
print(age)
print(is_married)
print(wage)
Output
<class 'str'>
<class 'int'>
<class 'bool'>
<class 'float'>
To print a text, use the print function and enclose the text with double or single
quotes, as shown below.
To print a combination of variable values and strings, you can separate them
with a comma.
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
'''
To print a combination of variable values and
texts, you can separate them with a comma.
'''
print("Name: ", name)
print("Age: ", age)
print("Married: ", is_married)
print("Wage: ", wage)
Output
Name: George
Age: 22
Married: False
Wage: 2300.4557
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
'''
To print a combination of variable values and
texts, you can separate them with a comma.
'''
# by name the sign + is used
print("Name: "+ name)
print("Age: ", age)
print("Married: ", is_married)
print("Wage: ", wage)
Output
Name: George
Age: 22
Married: False
Wage: 2300.4557
Example 4C: Printing Texts
You can also enclose the text with a single quote, as shown in the code below.
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
'''
To print a combination of variable values and
texts, you can separate them with a comma.
'''
print('Name: ', name)
print('Age: ', age)
print('Married: ', is_married)
print('Wage: ', wage)
Output
Name: George
Age: 22
Married: False
Wage: 2300.4557
wage = 2348.55
country = "United States"
print("Wage: $", wage)
'''
the sep="" specifies that no space or any other
characters are used between the dollar sign and the wage.
'''
print("Wage: $", wage, sep="")
print("Country", country)
'''
the sep=": " signifies the instruction to separate the
country and its corresponding value using a colon and a space.
'''
print("Country", country, sep=": ")
Output
Wage: $ 2348.55
Wage: $2348.55
Country United States
Country: United States
Output
Country
United States
Country: United States
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
print(f"{name} is {age} years old.")
Output
George is 22 years old.
# declaring variables
name = "George"
age = 22
is_married = False
wage = 2300.4557
# the first way to round to two decimal places
print("The wage of",name,"is: $%.2f" % wage+".")
# the second way to round to two decimal places
print(f"The wage is ${wage:.3f}.")
Output
The wage of George is: $2300.46.
The wage is $2300.456.
Using Comments
The interpreter ignores comments during the execution of the program. The
primary usage of comments is to enhance the code's readability and explain the
code to other programmers.
Python's two primary types of comments are single-line comments and multi-
line comments.
A single-line comment starts with a hash (#), while a multi-line comment
starts and is enclosed with a triple "single quote" or starts and is enclosed with
a triple "double quote."
Example 7: Comments
The following code contains single and multiline comments.
register.py
# this is a single-line comment.
'''
this is a multi-line comment
this is a multi-line comment
this is a multi-line comment
'''
"""
this is a multi-line comment
this is a multi-line comment
this is a multi-line comment
"""
Example 8: Multi-String
In the following example, we try to create a rectangle by multiplying a string
by a number.
shape.py
print('# ' * 10)
print('# ' * 10)
print('# ' * 10)
print('# ' * 10)
print('# ' * 10)
print('# ' * 10)
Type Casting
Type casting is converting one data type into another type. That is sometimes
necessary because of the calculation or the operation that is required to be
performed by the code. That can be accomplished in Python by using the
functions int(), string(), float(), char(), bool(), etc.
As shown in the output, the code causes an error because we tried to add the
salary of 3200 to the wages of "2800". As shown in the code, double quotes
enclose Emma's salary, which indicates that the wage is a string type, not a
float type.
To solve the issue, we have to convert Emma's salary to a float using the
function float, as shown below.
total_salary = salary_jack + float(salary_Emma)
Output
Total salaries: $ 6000.0
Output
Age Difference: 12
laptop.py
brand = "Dell"
price = 2400.3572
year = 2030
is_defect = False
# add your code
The output of the program after adding your code is as shown below.
The expected output
The Variable Values
Brand: Dell
Price: $2400.36
Year: 2030
Is Defect? False
Output
3400.96
Answer Quiz 2
Combining the print and the type function prints the variable's
type, not its value. Therefore, the code writes a string type of the
name's variable. The short name of a string in Python is "str."
Answer Quiz 3
180
Answer Quiz 4
The escape sequence \' prints a single quote; therefore, the output
is "What does 'Database' mean?".
Answer Exercise 1
Here below is the answer to exercise 1.
brand = "Dell"
price = 2400.3572
year = 2030
is_defect = False
print("The Variable Values")
print("Brand: ", brand)
print("Price: $%.2f" % price)
print("Year: ", year)
print("Is Defect? ", is_defect)
print()
print("The Variable Types")
print("Type of brand is: ", type(brand))
print("Type of price is: ", type(price))
print("Type of year is: ", type(year))
print("Type of is_defect is:", type(is_defect))
Output
The Variable Values
Brand: Dell
Price: $2400.36
Year: 2030
Is Defect? False
Answer Exercise 2
Below is the answer to exercise 2.
print('U ' * 1)
print('U ' * 2)
print('U ' * 3)
print('U ' * 4)
print('U ' * 5)
print('U ' * 6)
Output
U
UU
UUU
UUUU
UUUUU
UUUUUU
3. Operators in Python
There are several operator types in Python, such as arithmetic, assignment,
comparison, logic, identity, and membership. The value that the operator
operates on is called the operand.
Table 1: Arithmetic Operators
Arithmetic operators are used with numeric values to perform mathematical
operations. The arithmetic operations include addition, subtraction,
multiplication, division, and exponentiation. The operators, modulus, and
floor division might be unknown to beginners.
Modulus
When a number is divided by another, the remainder is called modulus. The
percentage symbol "%" represents modulus; see the following examples.
Examples
Operations Explanation
10 % 3 = 1 10 divided by 3 = 3, and the remainder is 1
24 % 6 = 0 24 divided by 6 = 4, and the remainder is 0
21 % 8 = 5 21 divided by 8 = 2, and the remainder is 5.
Explanation
10 % 3 = 1 10 divided by 3 is 3.
3 * 3 = 9.
remainder = 10 -9 = 1.
24 % 6 = 0 24 divided by 6 is 4.
6 * 4 = 24.
remainder = 24 - 24 = 0.
21 % 8 = 21 divided by 8 is 2
5 2 * 8 = 16.
remainder = 21 -16 = 5.
Example 2: Modulus
The following code clarifies how the modulus works.
modulus.py
print(10 % 3) # remainder is 1
print(24 % 6) # remainder is 0
print(21 % 8) # remainder is 5
Output
1
0
5
Floor Division
The floor division is an arithmetic operation that divides a number by
another, rounds the result to the integer, and ignores the remainder. The
double slash symbol "//" is used for the floor division.
Examples
Operation Explanation
30 // 4 = 7 30 divided by 4 = 7
4 * 7 = 28 the rest is 2 less than 7
22 // 5 = 4 22 divided by 5 = 4
4 * 5 = 20 the rest is 2 less than 5
20 // 4 = 5 20 divided by 4 = 5
5 * 4 = 20 the rest is 0
9 // 2 = 4 9 divided by 2 is 4
the rest is 1 less than 2
15 // 6 = 15 divided by 6 = 12
12 the rest is 3 less than 6.
Output
7
4
5
4
2
Output
8
1
10
4.0
1
125
Output
Jack David Emma
Output
Jack David Emma
Output
True
False
True
True
False
Examples
Operation Explanation
4 == 4 and 3 > 2 The first condition returns true because four is equal
to 4.
The second condition also returns true because three is
greater than 2.
The result is "true" because both conditions return
true.
8 >= 3 and 2 > 5 The first condition returns true because eight is greater
or equal to 3.
The second condition returns false because two is not
greater than 5.
The result is "false" because one of the conditions
returns false.
8 >= 3 or 2 > 5 The first condition returns true because eight is greater
or equal to 3.
The second condition returns false because two is not
greater than 5.
The result is "true" because one of the conditions
returns true. Remember that the result is true if only
one condition returns true by the "or" operator.
not (8 >= 3 or 2 > The result of the previous condition was true. By
5 applying the 'not' operator, the outcome will be
inverted to false."
Output
True
False
True
True
False
Operator Description
is Returns true if the variables are the same
is not Returns true if the variables are not the same
Output
True
False
True
Output
2 4 16
Answer Quiz 2
x=5
Output
6
Answer Quiz 3
x =5, y = 6
Answer Quiz 4
nr1 = 3, nr2 = 4, nr3 = 5.
The first statement print(nr1 < nr2 and nr3 != 5) checks whether
nr1 is smaller than nr2, which is true, but the second one checks
whether nr3 is not equal to 5, which is false. Using the logical
operator "and," all the statements should return true; otherwise,
the result will be false.
The second statement print(nr1 < nr2 or nr3 != 5) is precisely
the same as the previous statement, but this time, the logical
operator "or" is used, and by using or if one statement returns
true, the result is true.
The correct answer is b.
Output
False
True
Answer Quiz 5
brand1 = "IBM", brand2 = "Dell", brand 3 = brand1.
Output
False
True
True
Answer Quiz 6
colors = "blue, red, green, black, white, yellow"
Answer Exercise 1
fruit.py
fruits = "apple, banana, orange, mango, strawberry"
print("Is orange on the list? The answer is:","orange" in fruits)
print("Is grape on the list? The answer is:","grape" in fruits)
Output
Is orange on the list? The answer is: True
Is grape on the list? The answer is: False
Answer Exercise 2
job.py
print("Five years of experience. Is he accepted?", 5 >= 5)
print("Seven years of experience. Is he accepted?", 7 >= 5)
print("Four years of experience. Is he accepted?", 4 >= 5)
Output
Five years of experience. Is he accepted? True
Seven years of experience. Is he accepted? True
Four years of experience. Is he accepted? False
4. User Input and Strings
User Input
In the previous chapters, we worked with variable values. In many cases, we
don't have the values of the variables; instead, we need to ask the users to enter
their data. Most well-known web applications ask users for their names,
birthdates, occupations, etc.
You can also ask users in Python to enter their data using the function input(),
as shown in the following examples.
Notice
When you test the following program, the program first allows you to enter
your first name. Each time you enter your data, you must press the enter
button on your keyboard to insert the rest.
register.py
'''
assign the values that the user enters to the
variables first name, last name, age, and occupation
'''
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
age = input("Enter your age: ")
occupation = input("Enter your occupation: ")
# use "\n" for new line
print("\n..... Info of",first_name, last_name, ".....")
# use \t for tab
print("Name: \t\t\t", first_name, last_name)
print("Age: \t\t\t", age)
print("Occupation: \t", occupation)
Output
Enter your first name: George
Enter your last name: Smith
Enter your age: 34
Enter your occupation: Programmer
..... Info of George Smith .....
Name: George Smith
Age: 34
Occupation: Programmer
triangle.py
symbol = input("Enter a character: ")
print(symbol * 1)
print(symbol * 2)
print(symbol * 3)
print(symbol * 4)
print(symbol * 5)
print(symbol * 6)
print(symbol * 7)
calculator.py
weight1 = input("Enter the weight of the first person: ")
weight2 = input("Enter the weight of the second person: ")
weight3 = input("Enter the weight of the third person: ")
# check the variable types
print(type(weight1))
print(type(weight2))
print(type(weight3))
# calculate the total weight
total_weight = weight1 + weight2 + weight3
print("The total weight is: ", total_weight, "pounds")
It is clear from the output that Python sees all three variables, weight1,
weight2, and weight3, as strings.
Output
Enter the weight of the first person: 199
Enter the weight of the second person: 192
Enter the weight of the third person: 177
<class 'str'>
<class 'str'>
<class 'str'>
The total weight is: 199192177 pounds
As already explained in this book, you can convert the string type in Python to
an integer by using the function int as int(weight1), as shown in the code.
The output clearly shows that the total weight is 568 pounds, which exceeds
the maximum weight of 551 pounds allowed in the elevator.
Output
Enter the weight of the first person: 199
Enter the weight of the second person: 192
Enter the weight of the third person: 177
The total weight is: 568 pounds
Notice
The user input is a string, even if the user enters a number. Therefore,
converting the input to an "int" type for integers or a "float" type for decimal
numbers is crucial. Otherwise, the result of the arithmetic operation would be
incorrect.
String Index
Each character within a string has a positive and negative index position
number.
We use the index number enclosed by brackets to determine each letter within
a string.
For example, if we want to print the letter n of the title, we use the statement
print(title[4]) or print(title[-6]) as shown in the following code.
Substring
It is also possible to display a substring or a part of the string by indicating
from which index position number to start and the end index position of the
substring.
By printing a substring of a string, we also use the enclosed brackets; a colon
separates the start and the end index ":" examples are title[6:9] and title[0:5].
In the previous example, we can separate the substring "Java" by determining
the first index position number and leaving the end index position empty as
title[6:]; it is also possible to use title[6:10].
Notice
The start index is inclusive, but the end index is exclusive. Therefore, we use
the end index of 10, which doesn't exist but indicates excluding 10. It is
recommended to leave it empty if you want to reach the end of the characters.
Output
Java
Java
Java
Java
Learn
Learn
Learn
Learn
Learn Java
Learn Java
Using Operators With Strings
As shown in the following examples, Python comparison operators could also
be used with strings such as "==" and "!=".
Output
True
False
True
False
True
True
In the following output, the user seeks France, which is not on the list.
Therefore, the program's answer is "false".
Current List: United States, United Kingdom, Germany, India, Brazil, Spain, Italy, Canada, Japan,
Mexico
Notice
The provided list represents the top 10 nations worldwide where, to date, my
books are the most popular, ranked by their level of popularity.
Challenge
If you enter an existing country on the list using different letter cases, the
program's answer would be "false, " which is undesirable.
In the following output of the same previous code, the user enters "germany"
starting with a lowercase, but the program mentions that "germany" is not on
the list. That is because Python is case-sensitive.
Current List: United States, United Kingdom, Germany, India, Brazil, Spain, Italy, Canada, Japan,
Mexico
The answer to the question is in the following topic of the string functions.
That will teach you how to manipulate strings in that case and many others.
String Functions
The following functions are essential for programmers to manipulate strings.
Table 1: String Functions
Functions that take an action or update the string.
Function Description
capitalize() Capitalizes the initial character.
count() Counts the numbers of a specified value in a string.
find() Locates the position of a specified value in a string.
index() Locates the position of a specified value in a string.
lower() Converts the entire string to lowercase.
replace() Replaces a specified value with another in the string.
swapcase() Swaps the case of characters; lowercase becomes uppercase
and vice versa.
title() Capitalizes the first character of each word.
upper() Converts the entire string to uppercase.
len() Determines the length (number of characters) of the string.
The user enters "GeRMany", which is on the list, but the program ignores the
letter case and returns true this time.
Current List: United States, United Kingdom, Germany, India, Brazil, Spain, Italy, Canada, Japan,
Mexico
Output
I am from spain
2
10
6
i am from spain
i am from US
I AM FROM sPAIN
I Am From Spain
15
Output
True
True
True
True
True
True
True
True
True
Notice
As a programmer, it is crucial to understand code and to have an expectation regarding the output.
However, experts can see what the code does faster, but training yourself for that is essential; therefore,
I offer quizzes in most of my books.
Quiz 1: Conversion
When executed, this code prompts the user to input the bread price, then the
milk prices, and then calculates the total by summing both prices. Assuming
the user enters prices of $2.50 for bread and $3.50 for milk, what will be the
outcome of running this code?
calculator.py
bread_price = input("Enter the price of bread: ")
milk_price = input("Enter the price of milk: ")
total_price = bread_price + milk_price
print(total_price)
Quiz 2: Conversion
Which shape do you expect to be created with the letter "X" in the output of the following program?
shape.py
symbol = " X "
print(symbol * 10)
print(symbol * 10)
print(symbol * 10)
print(symbol * 10)
print(symbol * 10)
print(symbol * 10)
string_manipulation.py
text = "Python course price: $2400"
# insert the statement here
string_function.py
quote = "A journey of a thousand miles begins with a single step"
# add your code
find.py
historical_figures = "Darwin, Einstein, Lincoln, Gandhi, Bonaparte, Tolstoy"
# add your code
If you join two strings with a "+" sign, the second string will be
appended to the end of the first one.
The prices are 2.50 and 3.50.
Therefore, the answer is 2.503.50.
The correct answer is b.
Output
Enter the price of bread: 2.50
Enter the price of milk: 3.50
2.503.50
Answer Quiz 2
When a string is multiplied by a number in Python, the string is replicated by
that specified number. In the example, the character 'X' is multiplied by ten
and subsequently printed. As a result, the character 'X' is printed ten times
across six rows, forming a rectangular shape. Therefore, the correct answer is
option c.
Output
X X X X X X X X X X
X X X X X X X X X X
X X X X X X X X X X
X X X X X X X X X X
X X X X X X X X X X
X X X X X X X X X X
Answer Quiz 3
As shown in the table of string functions, the function replace is used to
replace a substring. In this case, the word "price" is replaced with the word
"amount".
The correct answer is a.
Answer Quiz 4
The title "Python for Beginners" contains 20 characters, including
two spaces.
The statement print(title[7]) prints the character in the seventh
position, starting with the zero position. Therefore, it prints the
letter "f" to the output, as shown below.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
P y t h o n f o r B e g i n n e r s
Answer Exercise 1
Here below is the code required by the exercise.
string_functions.py
quote = "A journey of a thousand miles begins with a single step"
# add your code
print(quote[2:9])
print(quote[2:9].upper())
print(quote.upper())
print(len(quote))
print(quote.isalnum())
Output
journey
JOURNEY
A JOURNEY OF A THOUSAND MILES BEGINS WITH A SINGLE STEP
55
False
Answer Exercise 2
find.py
historical_figures = "Darwin, Einstein, Lincoln, Gandhi, Bonaparte, Tolstoy"
# add your code
hf = input("Enter a name of a historical figure: ")
hf_ignore_case = hf.lower()
hf_list_ignor_case = historical_figures.lower()
print("Is the name", hf, "on the list? ", hf_ignore_case in hf_list_ignor_case)
Output
Enter a name of a historical figure: EINSTEIN
Is the name EINSTEIN on the list? True
5. Conditional Statements
So far, the statements of the previous programs were executed from the top
to the bottom. Sometimes, we need only a statement executed if it meets a
specific condition; otherwise, the program should ignore it.
For example, a particular shopping website offers a discount to subscribed
customers, but an unsubscribed customer should pay the total price of a
specific Item. In Python and other programming languages, conditional
statements are used to determine whether a particular part of the code is
executed or ignored.
Conditional statements are if statements, if else statements, and if elif
statements.
If... Statements
If the condition meets specific requirements, the statements within the if-
block are executed.
The if-block starts with if followed by the condition, then ends with a colon
":"
The if condition is followed by its block statements, which are recognized
by a tab space, as shown in the code below.
The statements within the if-block could be one or more statements. Once
the if condition returns true, all the statements within the if-block are
executed.
wage.py
basic_wage = 3200
is_certified = True
years_experience = 4
age = 43
total_wage = basic_wage
if is_certified:
total_wage += 200
if years_experience >= 4:
total_wage += 500
if age >= 40:
total_wage += 600
print("Total wage: $",total_wage, sep='')
The basic wage is still $3200; the programmer is not certified; therefore, he
will not receive the extra $200. However, he gets the additional $500
because he has five years of experience. He is 34 years old; therefore, he
doesn't receive the extra $500 because he is under 40. His salary would be
3200 + 500 = 3700.
wage.py
basic_wage = 3200
is_certified = True
years_experience = 4
age = 43
total_wage = basic_wage
if is_certified:
total_wage += 200
if years_experience >= 4:
total_wage += 500
if age >= 40:
total_wage += 600
print("Total wage: $",total_wage, sep='')
Quiz 3: If Statements
What happens if the following code is run?
if_else.py
grade = 6
display = ""
if grade == 6:
display += "X "
if grade > 5:
display += "N "
if grade > 9:
display += "P "
else:
display += "K "
print(display)
Select the correct answer:
a. The code prints "X N" to the output.
b. The code prints "X " to the output.
c. The code prints "X K" to the output.
d. The code prints "X N K " to the output.
e. The code prints nothing to the output.
The expected output of the program is shown below. The user enters a
height of 185 cm, an age of 19 years, and an experience of 2 years. The
program selects the player.
Enter the height of the player: 185
Enter the age of the player: 19
Enter years of experience: 2
The player is accepted.
The expected output of the program is shown below. The user enters a
height of 188 cm, an age of 26 years, and an experience of 3 years. The
program rejects the player because his age doesn't meet the requirements.
Enter the height of the player: 188
Enter the age of the player: 26
Enter years of experience: 3
The player is rejected.
Answer Quiz 2
Output
9300
Answer Quiz 3
The variable display is an empty string.
Output
XNK
Answer Quiz 4
Output
K
Answer Quiz 6
Answer Quiz 7
Output
800
Answer Exercise 1
currency.py
amount_euro = input("Enter an amount in Euros: ")
# convert the euro amount to float
amount_euro = float(amount_euro)
amount_dollar = amount_euro * 1.10
print("The amount of",amount_euro, "is $%.2f" %amount_dollar)
Output
Enter an amount in Euros: 200
The amount of 200.0 is $220.00
Answer Exercise 2
volleyball.py
height = input("Enter the height of the player: ")
# convert the height to an integer
height = int(height)
age = input("Enter the age of the player: ")
# convert the age to an integer
age = int(age)
experience = input("Enter years of experience: ")
# convert the experience to an integer
experience = int(experience)
if height >= 185 and age >= 18 and age <= 25 and experience >= 2:
print("The player is accepted.")
else:
print("The player is rejected. ")
Output
Enter the height of the player: 190
Enter the age of the player: 24
Enter years of experience: 1
The player is rejected.
6. Loops Statements
A loop controls the repetition of a specific statement(s) by determining the
number of times executed. A loop contains a head and a body, with the head
specifying the frequency of statement execution within the loop's body.
In Python, the loop's body is positioned beneath the head and should be
indented with a "tab" to the right, as shown in the code below.
nr = 1
while nr < 5: # head of the loop
print(nr, 'is smaller than 5') # body: statement 1
nr += 1 # body: statement 2
print("number is: ", nr) # doesn't belong to the loop
The value "1" is assigned to the variable "nr" in the example. The
body is executed as long as the while condition returns true.
The initial value of the variable nr is 1. The head of the loop
checks whether the value 1 is smaller than 5, and it is. Therefore,
the loop's head condition returns true.
The body's statements of the while-loop are executed, and print "1
is smaller than 5."
The statement "nr += 1" increments the value of the variable nr by
one. Therefore, the value of nr becomes 2.
The program returns to the head and checks whether the value 2 is
smaller than 5. The answer is true; therefore, the loop's body is
executed, and the statement "2 is smaller than 5" is printed.
When the value of variable nr reaches "5", the head of the loop
checks whether "5" is smaller than "5," and that returns false
because it is not. Therefore, the execution of the loop's body is
terminated.
The output of the program is.
1 is smaller than 5
2 is smaller than 5
3 is smaller than 5
4 is smaller than 5
number is: 5
while True:
print("How old are you?")
break
nr = 0
while nr < 10:
nr += 1
if(nr == 4 or nr == 6 or nr == 8):
continue # skip
print(nr)
nr = 0
while nr < 5:
if nr == 3:
print(nr)
else:
pass
nr += 1
The first parameter is the "start" or the initial value of the variable
The second parameter is the value where the loop should stop.
The start value is incremented each time by one by default.
Example Description
range(3, 7) It starts with 3, ends with 6 (7 is not included), and the start each
time by default increments by one. So, the reeks numbers are: 3,
4, 5, 6.
range(5, 8) It starts with 5, ends with 7 (8 is not included), and the start by
default increments by one. So, the reeks numbers are: 5, 6, 7.
The first parameter is the "start" or the initial value of the variable
The second parameter is the value where the loop should stop.
The third parameter's value determines with which number each
time the variable starts is incremented.
Examples Description
range(3, 10, Starts with 3, ends with 9 (10 is not included), and the start
2) each time is incremented by 2. So, the reeks numbers are: 3, 5,
7, 9.
range(2, 11, Starts with two and ends with 10 (11 is not included), and the
3) start each time is incremented by 3. So, the reeks numbers are:
2, 5, 8. The end number is eight because if we increment eight
by 3, we reach 11, which is not included.
while_loop.py
id = 6
while id < 10:
print(id, end=' ') # statement 1
id += 1 # statement 2
Select the correct answer:
a. The code prints "1 2 3 4 " to the output.
b. The code prints "10 " to the output.
c. The code prints "6 7 8 9 " to the output.
d. The code prints "6 7 8 " to the output.
e. The code prints nothing to the output.
while_loop.py
id = 6
while id < 10:
print(id, end=' ') # statement 1
continue_statement.py
nr = 1
while nr < 6:
nr += 1
# if the rest = 0 as a result of dividing the nr by 2.
if nr % 2 == 0:
continue
else:
print(nr, end=' ')
pass.py
nr = 0
while nr < 10:
if nr >= 5 or nr < 3:
pass
else:
print(nr, end = ' ')
nr += 1
for_loop.py
for number in range (5):
print(number, end = ' ')
range_2param.py
for number in range (8, 10):
print(number, end = ' ')
range_3param.py
for number in range (2, 10, 7):
print(number, end = ' ')
while_loop.py
nr = 0
while nr < 10:
nr += 1
# add your code here
print(nr, end=", ")
Current output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Answer Quiz 2
The initial value of the variable id is 6.
The statement "while id < 10" checks whether the value of id is
smaller than 10, which is smaller. Therefore, the value 6 is printed
to the output.
The next time, the value 6 hasn't changed; therefore, 6 is printed
again to the output.
Since the value 6 doesn't change, printing 6 to the output
continues.
The program doesn't stop with printing 6 to the output because the
while loop repeatedly checks whether 6 is smaller than 10, and it
is.
The correct answer is d.
Output
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
6666666666666666666666666666666666666666666666666666666
66666
Answer Quiz 3
The initial value of the variable nr is 2.
Output
345
Answer Quiz 4
The initial value of the variable nr is 1.
The statement "while nr < 6" returns true because the value of nr is
1.
The statement "nr+=1" increments the value of nr by one, and its
value becomes 2.
The statement "if nr % 2 == 0" checks whether the value of nr
divided by two doesn't have a remainder. In that case, the continue
statement skips it. Therefore, the values 2 and 4 are skipped
because if you divide 2 or 4 by 2, the remainder is zero.
The code prints 3 5 to the standard output.
The correct answer is c.
Output
35
Answer Quiz 5
The initial value of the variable nr is 0.
The statement "while nr < 10" checks whether the nr, which is 0, is
smaller than 10, and it is.
The statement "if nr >= 5 or nr < 3" checks the nr values if it is
smaller than 3 and the numbers equal or larger than 5.
In other cases, the value of the nr is printed to the output.
The correct answer is c.
Output
34
Answer Quiz 6
The for loop in range (5) repeats the execution of the loop's body
from 0 to 4. Remember that 5 is exclusive, and the start is 0 by
default.
Output
01234
Answer Quiz 7
The for loop range (8, 10) starts with 8 and stops at 10.
Answer Quiz 8
The for loop range (2, 10, 7) starts with 2 stops at 10 and
increments the value by 7 each time.
Output
29
Answer Exercise 1
while_loop.py
nr = 0
while nr < 10:
nr += 1
if(nr > 4 and nr < 8):
continue
print(nr, end=", ")
Output
1, 2, 3, 4, 8, 9, 10,
Answer Exercise 2
while_loop.py
for number in range(10, 20, 3):
print(number, end=' ')
Output
10 13 16 19
7. Lists in Python
A list is a data structure that stores multiple elements. In the real world, we
often need lists of similar objects, for example, a list of cars, a list of students,
a list of computers, and a list of items.
Python allows the creation of a list, as shown in the code below. By declaring a
list, you have to choose an appropriate name for the list.
In the following example, we have declared a list to store cars; therefore, we
call the list cars. Brackets enclose elements of a list in Python.
0 1 2 3 4
Audi Tesla Volvo BMW Toyota
Declaring a List
In Python, you can create a list by following the next steps.
Choose an appropriate name for the list; in this case, the name cars
is appropriate.
Open a bracket and start with the elements you want in the list.
Separate the element's names with a comma.
The name of the list ended with open and closed brackets.
Pass the index of the element to the bracket.
Use the name of the list and the index of "1" to print the brand Tesla in the list,
as shown below.
print(cars[1])
List Modification
In the real world, a list doesn't remain the same. For example, a list of
students. Some students could leave the university, and some students could
join later. Think about how a student's address or other data can be changed in
the future. Therefore, it is necessary to have functions that allow adding,
removing, and updating list elements. We need even more functions to know
how many elements are in the list or how to sort the elements of a list
alphabetically..etc.
The output clearly shows that Cadillac is added to the end of the list.
Audi Tesla Volvo BMW Toyota Cadillac
In the ouput we see clearly that the brand Jaguar is added to the third position
or the index position 3 of the list.
Audi Tesla Volvo Jaguar BMW Toyota
The output of the code shows that the sport cars are added to the list cars.
Audi Tesla Volvo BMW Toyota Aston Martin Ferrari Bugatti
Removing Elements From a List
The following examples show how to remove elements from a list using the
pop, remove, and clear functions.
The output of the code shows that the element Volvo is removed from the list.
Audi Tesla BMW Toyota
cars.py
# declare a list
cars = ["Audi", "Tesla", "Volvo", "BMW", "Toyota"]
# remove the element "Volvo" from the list
cars.pop(3)
# display all the elements of the list
for element in cars:
print(element, end=' ')
The output of the code shows that the element BMW is removed from the list.
Audi Tesla Volvo Toyota
Example 7: Removing All the Elements
We use the function clear to remove all the elements of a list.
cars.py
# declare a list
cars = ["Audi", "Tesla", "Volvo", "BMW", "Toyota"]
# the clear function removes all the elements of the list
cars.clear()
# display all the elements of the list
for element in cars:
print(element, end=' ')
The output of the code shows nothing because the function clear has removed
all the cars from the list.
The output of the code shows that the number of the elements is "5".
5
-----reverse-------
Volvo Toyota Tesla BMW Audi
The output is "1" because the Tesla brand is in the index position of 1.
1
Answer Quiz 2
The for loop iterates through the elements of the loop.
The if i == 2 or i == 4 selects the elements with the index 2 and 4,
which are Robert and Daniel.
Answer Quiz 3
The statement freelancers.pop(2) removes the freelancer Robert
from the list, because his index is 2.
The statement freelancers.append("Emma") adds Emma to the end
of the list.
The correct answer is a.
Output
Edward Jeff John Daniel Emma
Answer Quiz 4
The statement freelancers.remove("Daniel") removes Daniel from
the list.
The remove statements removes also Robert, Jeff and Edward
from the list.
The statement freelancers.insert(0, "Emma") adds Emma to the
first position of the list.
Answer Quiz 5
The statement freelancers2 = freelancer.copy(), copies the list
freelancers.
The statement freelancers2.sort() sorts the freelancers2 list
alphabetically.
The statement print(freelancers2[1], freelancers[1]) the
freelancers2 list is sorted alphabetically. Therefore, the name
Edward is the at the index postion 1.\
The freelancers is not sorted; therefore, the first index position is
Jeff.
Answer Exercise 1
petslist.py
pets = ["Dog", "Cat", "Snake", "Rabbit", "Fish"]
pets.pop(2)
pets.remove("Fish")
pets.append("Lizard")
print(pets)
Output
['Dog', 'Cat', 'Rabbit', 'Lizard']
Answer Exercise 2
petslist.py
pets = ["Dog", "Cat", "Snake", "Rabbit", "Fish"]
pets.sort()
print("Sorted alphabetically: ", pets)
print("Elements number: ", len(pets))
Output
Sorted alphabetically: ['Cat', 'Dog', 'Fish', 'Rabbit', 'Snake']
Elements number: 5
8. Dictionary
A dictionary in Python is a modifiable collection of a pair of keys and
values. The keys and the values are associated, such as persons and emails,
persons and their ages, an English word and its meaning in Spain or other
languages. Dictionaries don't allow duplicate entries. So, the key values pair
are unique.
products.py
# declare a dictionary
# the keys are the products and the values are the prices
products = {'milk':2.55, 'eggs':3.45, 'chips':2.15, 'bread':1.85}
# print the dictionary
print(products)
# print the prices (values) of the following products(keys)
print(products['eggs'])
print(products['bread'])
The output shows that the user has inserted the product "chips," and the
program types the price of the chips.
Enter the name of the product: chips
Price of chips is: $ 2.15
Suppose the user enters the product's name with different cases than the one
in the dictionary.
In the following output, the user types the product "Eggs" starting with
uppercase. The name Eggs in the dictionary is in lowercase. An error occurs
because Python is case-sensitive.
KeyError: 'Eggs'
The output shows that the user entered the product eggs in uppercase, but
this time, it doesn't matter because we convert the product entered by users
to lowercase. When you compare two products all in lowercase, it will be
found.
The user enters the "EGGS" product in this output, and the program finds it.
Enter the name of the product: EGGS
Price of eggs is: $ 3.45
Output
Keys: dict_keys(['milk', 'eggs', 'chips', 'bread'])
Values: dict_values([2.55, 3.45, 2.15, 1.85])
----------keys-------------
Key: milk
Key: eggs
Key: chips
Key: bread
----------values-------------
Value: 2.55
Value: 3.45
Value: 2.15
Value: 1.85
----------keys & values-------------
milk : 2.55
eggs : 3.45
chips : 2.15
bread : 1.85
products.py
# declare a dictionary
# the keys are the products and the values are the prices
products = {'milk':2.55, 'eggs':3.45, 'chips':2.15, 'bread':1.85}
# display the products (key) for the items in a sorted order
for element in sorted(products.keys()):
print(element)
print("-------------")
# display the price (value) for the items in a sorted order
for element in sorted(products.values()):
print(element)
The output shows that both water and coffee with their prices are added to
the dictionary products.
{'milk': 2.55, 'eggs': 3.45, 'chips': 2.15, 'bread': 1.85, 'water': 1.35, 'coffee': 4.55}
products.pop("eggs")
Remove the chips product by using the statement del.
del products["chips"]
products.py
the keys are the products and the values are the prices
products = {'milk':2.55, 'eggs':3.45, 'chips':2.15, 'bread':1.85}
# remove eggs by using pop function
products.pop("eggs")
# remove chips by using the del keyword
del products["chips"]
# display the products dictionary
print(products)
The output shows that eggs and chips are removed from the products.
{'milk': 2.55, 'bread': 1.85}
Notice
the statement len(countries) prints the number of the elements within the
dictionary.
countries.py
# the keys are the countries and the values are the capitals
countries = {'United States':'Washington', 'Germany':'Berlin', 'France':'Paris', 'Spain':'Madrid'}
countries.pop("United States")
del countries["France"]
print(len(countries))
countries.py
# the keys are the countries and the values are the capitals
countries = {'United States':'Washington', 'Germany':'Berlin', 'France':'Paris', 'Spain':'Madrid'}
print(len(countries), end= " ")
countries["United Kingdom"] = "London"
countries["Brazil"] = "Brasília"
print(len(countries))
laptop.py
laptops = {'Dell': 2200, 'HP': 1100, 'Acer': 800, 'IBM': 2300}
# add your code here
Output
2
Answer Quiz 2
The statement print(len(countries)) prints the number of
elements in the dictionary, which is four.
Output
46
Answer Quiz 3
The for loop statement prints all the keys and the values to the
standard output.
Answer Exercise 1
The statement of line 1 asks the user to enter an English word.
dictionary.py
eng_dictionary = {'Happy': 'Pleased', 'Fast': 'Quick', 'Big': 'Large', 'Smart': 'Clever'}
en_word = input('Enter an English word: ') #.....line 1
# convert the user input to lowercase
en_word = en_word.lower() #.....line 2
# convert the first letter to upper case
en_word = en_word.capitalize() #.....line 3
element = eng_dictionary[en_word] #.....line 4
print("The synonymous of the word " + en_word, "is", element)
Output
Enter an english word: HAPPY
The synonymous of the word Happy is Pleased
Answer Exercise 2
laptops.py
laptops = {'Dell': 2200, 'HP': 1100, 'Acer': 800, 'IBM': 2300}
max_price = input("Please enter a maximum price: ") #... line 1
max_price = float(max_price) #... line 2
print("----------Selected Laptops-------------")
# iterating over the key:vlaue pairs using .items() method
for(key, value) in laptops.items(): #... line 3
if(value <= max_price): #... line 4
print(key, ':', value) #... line 5
A function can be invoked(called) using its name and its possible arguments.
The output of this code displays all the contact data of the company Nano
Mail. Suppose we need to display this contact data in many places in the
application or a website.
Output
Name: Nano Mail
Phone: 033-44556677
Email: [email protected]
------------
Copying and pasting the code to the places where you want to display the
contact data is very poor. The reason is that by updating an email address,
mobile number, or any other company data, the programmer should seek many
places to update the data in every single place.
However, by writing a function to display the data and call the function, we
can achieve the goal with one block of reusable code, as shown in the
following example. In addition, duplicating the same code in various parts of
the program unnecessarily increases its size.
In the previous example, we called the function twice; therefore, the contact
data is printed twice in the output.
contact.py
Name: Nano Mail
Phone: 033-44556677
Email: [email protected]
------------
Name: Nano Mail
Phone: 033-44556677
Email: [email protected]
------------
The user enters the name David, and then the program prints the entered name.
Enter your name: David
Student name is: David
student_info.py
def student_data(name, age):
print("Student name is: ", name)
print("Student age is: ", age)
username = input("Enter your name: ")
age = input("Enter your age: ")
# call (invoke) the function
student_data(username, age)
The users are asked to enter their names and ages.
Enter your name: Emma
Enter your age: 22
Student name is: Emma
Student age is: 22
The user enters an amount of 200 euros and the program converts it to dollars.
Enter an amount in euro: 200
The entered amount is: $220.00
Output 2: The user enters a gross salary of 4000 and a tax rate of %20
Enter your gross salary: $4000
Enter the tax rate in your country: %20
Net wage: $3200.00
Line 2 calculates the result, which is the sum of the first and
second parameters minus the third parameter.
Line 3 returns the result.
Line 4 invokes the function with the parameters 22, 20, and 10.
The program prints the result, which is 22 + 20 - 10 = 32.
The correct answer is c.
Output
32
Answer Quiz 2
Line 1 declares a function with three parameters.
Answer Quiz 3
Line 1 declares a function with three parameters.
Answer Exercise 1
net_wage.py
def net_wage(gross_salary, taxrate):
tax_amount = (taxrate / 100) * gross_salary
net_salary = gross_salary - tax_amount
return net_salary
gross_wage = input("Enter your gross salary: $")
gross_wage = float(gross_wage)
country_taxrate = input("Enter the tax rate in your country: %")
taxrate = int(country_taxrate)
net_wage = net_wage(gross_wage, taxrate)
# print the net wage rounded to the nearest decimals.
print("Net wage: $%.2f" % net_wage)
Output
Enter your gross salary: $4000
Enter the tax rate in your country: %20
Net wage: $3200.00
Answer Exercise 2
largest.py
def largest(nr1, nr2, nr3):
if nr1 > nr2 and nr1 > nr3:
print("The largest is:", nr1)
elif nr2 > nr1 and nr2 > nr3:
print("The largest is:", nr2)
elif nr3 > nr1 and nr3 > nr2:
print("The largest is:", nr3)
else:
print("Please enter unique numbers")
# ask the user to enter three numbers, one at a time
nr1 = input("Enter the first number: ")
nr2 = input("Enter the second number: ")
nr3 = input("Enter the third number: ")
# convert the numbers to integers.
nr1 = int(nr1)
nr2 = int(nr2)
nr3 = int(nr3)
# invoke the function by entering the user's numbers.
largest(nr1, nr2, nr3)
10. Exceptions
Exceptions may occur during the execution of a program, and it is essential
to handle them appropriately, as summarized in this chapter. Ignoring an
exception can lead to the termination of the program. For example, if a
program attempts to divide a number by zero, it triggers an exception
because the result of such a division is undefined. It is crucial to implement
exception-handling mechanisms to prevent the unexpected termination of a
program.
When developing a program, three types of errors may arise: syntax,
runtime, and logical errors.
Syntax errors
The interpreter identifies syntax errors in Python before the program is
executed. These errors occur when incorrect Python language syntax is
used.
Runtime errors
If a program is free of syntax errors, it can be executed by the Python
interpreter. However, during execution, the program may terminate if a
runtime error occurs. Examples of runtime errors include division by zero
or attempting to access an element in a list that doesn't exist.
Logical errors
Logical errors pose a challenge in debugging as they occur during program
execution without causing a crash, yet they yield incorrect results.
Identifying and fixing such errors requires carefully reviewing the code to
specify and address the underlying issue.
Handling Exception
If an exception occurs, the program is terminated. Therefore, handling the
expected exceptions during the program's runtime is essential. Python, like
the other programming languages, has a method to handle exceptions by
using the following keywords.
Handling Exceptions
try... except
try... except... except
try... except... else
try... finally
zero_division.py
nr = 2
try:
print(20/nr)
except:
print("The result of division by zero is unknown.")
Type Error
If a calculation involves a string, boolean type can cause an exception
because they are not numbers.
number1 = "40"
number2 = 10
print(number1/number2)
The output prints the automatically generated error message and the error
that the programmer determines.
unsupported operand type(s) for /: 'str' and 'int'
The number1 variable type is a string
Index Error
The index error occurs if you try to access an element index that doesn't
exist.
Multiple Exception
Multiple exceptions are helpful if more than one exception is expected. The
more specific exceptions are located at the top, while general exceptions are
located at the bottom, as shown below.
multiple_exceptions.py
number = input("Enter a number: ")
try:
int_number = int(number)
print("The result is: ", 20/int_number)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter a number!")
multiple_exceptions.py
# the list contains 4 elements
list_brand = ["HP", "Dell", "IBM", "Acer"]
number = input("Enter a number: ")
try:
# convert the number to int
int_number = int(number)
print("The brand is:", list_brand[int_number])
except IndexError:
print("Element",number,"doesn't exist.")
except ValueError:
print("Please enter a number!")
multiple_exceptions.py
# the list contains 4 elements
list_brand = ["HP", "Dell", "IBM", "Acer"]
number = input("Enter a number: ")
try:
# convert the number to int
int_number = int(number)
print("The brand is:", list_brand[int_number])
except IndexError:
print("Element doesn't exist.")
except Exception:
print("Something went wrong.")
Quiz 3: Exception
What happens if the following code is run?
except.py
cars = ["Audi", "Ford", "Jeep", "Volvo", "Toyota"]
try:
car = cars["z"]
print("Kia", end = " ")
except IndexError:
print("Tesla", end = " ")
except Exception:
print("BMW", end = " ")
finally:
print("Jeep", end = " ")
Answer Quiz 2
Output
Tesla
Answer Quiz 3
The statement car = car["z"] tries to access the index "z" in the
list, which should be a number.
Output
BMW Jeep
Answer Exercise 1
items.py
items = ["Notebook", "Sunglasses", "Smartphone", "Headphones", "Backpack"]
try:
item_index = input("Enter the index of an item: ")
item_index = int(item_index)
print("The item at index", item_index, "is:", items[item_index])
except IndexError:
print("The index", item_index, "is out of range.")
except ValueError:
print("Invalid input. Please enter a valid index.")
finally:
print("The program executed successfully.")
Answer Exercise 2
calculator.py
try:
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
result = numerator / denominator
print("The result of" ,numerator,"/",denominator,"is:", result)
except ZeroDivisionError:
print("Zero is not allowed as a denominator.")
except ValueError as ve:
print("Please enter a valid input. ")
finally:
print("Program executed successfully.")
Random Randrage
You can import the random module in Python by using the keyword import.
The function "randrange" within the module random allows two parameters.
The first parameter is the start number, which is included. The stop number,
or the second one, is the number that is excluded from the random number.
Example 1: randrage(2, 7) possible random numbers are 2, 3, 4, 5, 6.
Output: The generated random number is four, and the possibilities are 1, 2,
3, 4, 5 and 6.
4
dice.py
# a dice range is from one to six
from random import randrange
dice1 = randrange(1, 7)
dice2 = randrange(1, 7)
print(dice1, "", dice2)
Random Shuffle
The shuffle function allows to change the order of the list elements
Quiz 1: Random
What happens if the following code is run?
random.py
from random import randrange
random_nr = randrange(1, 2)
print(random_nr)
Quiz 2: Random
Which values should be passed to the randrange function
to select a random number from 10 to 20, inclusive?
random.py
from random import randrange
random_nr = randrange(0, 0)
print(random_nr)
Exercise 1: Lottery
Create a program allowing users to shuffle the names in the list below.
Upon executing the program, the names order is selected randomly. The
winners are determined based on the following ranking:
lottery.py
from random import shuffle
names = ["Emma", "David", "Jack", "George", "Ronald", "Vera", "Bruce"]
# add the rest of your code here.
The output of the program is shown below. Remember that the winners will
be randomly different each time you run the program.
The names randomly:
['Vera', 'Emma', 'Bruce', 'Ronald', 'David', 'Jack', 'George']
The winner of one million dollars is: Vera
The winner of 500 thousand dollars is: Emma
The winner of 100 thousand dollars is: Bruce
Exercise 2: Card Game
Write a program randomly assigning a card from a predefined list, using the
provided lists for both cards and their corresponding values.
cards = ["clubs", "Diamonds", "Hearts", "Spades"]
card_values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
# add your code here.
The output of the program is shown below. Remember that a random card is
selected each time you run the program.
Output 1
Your selected card is: Ace of clubs
Output 2
Your selected card is: 4 of Diamonds
Output 3
Your selected card is: 4 of clubs
Answer Quiz 2
Answer Exercise 1
lottery.py
from random import shuffle
names = ["Emma", "David", "Jack", "George", "Ronald", "Vera", "Bruce"]
shuffle(names)
print("The names randomly: \n",names)
print("The winner of one million dollars is:", names[0])
print("The winner of 500 thousand dollars is:", names[1])
print("The winner of 100 thousand dollars is:", names[2])
The output of the program is shown below. Remember that the winners will
be randomly different each time you run the program.
The names randomly:
['Vera', 'Emma', 'Bruce', 'Ronald', 'David', 'Jack', 'George']
The winner of one million dollars is: Vera
The winner of 500 thousand dollars is: Emma
The winner of 100 thousand dollars is: Bruce
Answer Exercise 2
from random import choice
cards = ["clubs", "Diamonds", "Hearts", "Spades"]
card_values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
# select a random card
random_card = choice(cards)
# select a random card value
random_card_value = choice(card_values)
print("Your selected card is: ", random_card_value, "of", random_card)
The output of the program is shown below. Remember that a random card is
selected each time you run the program.
Output 1
Your selected card is: Ace of clubs
Output 2
Your selected card is: 4 of Diamonds
Output 3
Your selected card is: 4 of clubs
12. Date and Time
Python enables the management of date and time, including the retrieval of
the current date and time, by importing the date or the datetime module.
Symbo Description
l
%a Sun, Mon ..
%A Sunday, Monday....
%d 01, 02, ..31
%b Jan, Feb ... Dec
%B January, February ...December
%m 01, 02, ... 12
%y 00, 02, 99
%Y 1900, 1998, 2018
Symbo Description
l
%H hour in 24-hour clock
%I Hour in 12-hour clock
%p AM or PM
%M minutes
%S seconds
Quiz 1: Date
What happens if the following code is run?
today.py
from datetime import date
current_date = date(year=2024, month=7, day=10)
format = current_date.strftime("%B %d %Y")
print(format)
Quiz 2: Date
What happens if the following code is run?
fixed_date.py
from datetime import date
current_date = date(year=2024, month=4, day=21)
format = current_date.strftime("%m %d %Y")
print(format)
Answer Quiz 2
Read the symbols %m %d %Y in the table 1 format date.
Answer Exercise 1
registration.py
from datetime import datetime
# get the current date and time
now = datetime.now()
# format the date in (MM/DD/YYYY)
format = now.strftime("%m/%d/%Y At %I:%M:%S %p")
name = input("Enter your name: ")
print(name,"'s registration was recorded on\n",format, sep="")
Output: The user enters David, and the program automatically prints the
current date and time.
Enter your name: David
David's registration was recorded on
03/04/2024 At 08:23:11 PM
Answer Exercise 2
current_datetime.py
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Format the date in (MM/DD/YYYY)
format = now.strftime("%A %m/%d/%Y %H:%M:%S")
print("The current date and time is:", format)
Output
The current date and time is: Monday 02/26/2024 19:08:26
13. Files Directories and OS
In online shopping, downloading invoices directly is a common practice.
These invoices are automatically generated by the programming language
operated by the software or website. Python facilitates the creation and
manipulation of files through some essential functions.
Notice
After running the following code, check the path where your Python code
"make_dir.py" exists, and you will see that the map "_generated_map" is
automatically created there.
make_dir.py
import os
# you can choose another path
path_dir = "_generated_map"
os.mkdir(path_dir)
Notice
This code creates the map "_generated_map" and the subdirectory "submap."
within it. If the directory "_generated_map" is already created on your path,
you will see an error because you cannot create two directories with the same
name on the same path.
Delete the directory "_generated_map" first and run the following code.
make_dir.py
import os
path_dir = "_generated_files"
os.mkdir(path_dir)
path_subdir = path_dir + "/submap"
os.mkdir(path_subdir)
Mode Description
x Opens the file exclusively for creation in Python 3, failing if
the file already exists.
r Opens a file in read-only mode with the file pointer
positioned at the beginning of the file.
r+ Opens a file for reading and writing, positioning the file
pointer at the beginning of the file.
w Opens a file in write-only mode, overwriting the content if
the file exists. Creates a new file if it doesn't exist.
w+ Opens a file for writing and reading, overwriting the content
if the file exists. Creates a new file for reading and writing if
it doesn't exist.
a Opens a file in append mode, positioning the file pointer at
the end if the file exists. Creates a new file for writing if it
doesn't exist.
a+ Opens a file for both appending and reading, positioning the
file pointer at the end if the file exists. Opens the file in
append mode. Creates a new file for reading and writing if it
doesn't exist.
Mode Description
w (write) Overwrites any existing content of the file.
a (append) Appends text to the end of the file.
Notice
Open the created file "MyFile.txt," where the code "file_writer.py" exists.
You will see that both quotes are written into the file automatically.
The following program opens MyFile.txt and then reads the first three lines of
the file's content.
file_readline.py
# open the file to read the first three lines
file_reader = open("MyFile.txt")
print(file_reader.readline())
print(file_reader.readline())
print(file_reader.readline())
file_reader.close()
The file MyFile.txt is created on the given path by running the previous
program. The output of the following code prints the first three lines of the file
content MyFile.txt.
United States - Washington.
Germany - Berlin.
By running the program, the output prints the content of the file.
United States - Washington.
Germany - Berlin.
Brazil - Brasília.
Spain - Madrid.
Output
['list_maps_files.py']
Output
linux
current_dir.py
import os
print(os.getcwd())
Output
The Godfather
Wall Street
The Pianist
The Matrix
course_2.txt
Course Info
Java: $3500
course_3.txt
Course Info
HTML: $2900
course_4.txt
Course Info
SQL: $2800
Answer Quiz 2
The following code explains all the lines of the quiz code.
path_dir = "MyFile.txt"
'''
opens the file 'MyFile.txt' for writing,
creating it if it doesn't exist.
'''
file1 = open(path_dir, "w")
# A. Einstein
q1 = "In the middle of difficulties lies opportunities."
q2 = "What we think, we become." # Buddha
# writes q1 to the file
file1.write(q1)
# closes the file
file1.close()
# opens the file again
file1 = open(path_dir, "w")
# overwrites the content
file1.write(q2)
# closes the file
file1.close()
Answer Exercise 2
Here is the code of the exercise.
course.py
courses = ["Python: $3000", "Java: $3500", "HTML: $2900", "SQL: $2800"]
for i in range(len(courses)):
# generate the file name
path = "course_" + str(i+1) +".txt"
# open the file for writing and create it if it doesn't exist
f = open(path, "w")
# write the course information into the file
f.write("Course Info\n")
f.write(courses[i])
f.close()
course_1.txt
Course Info
Python: $3000
course_2.txt
Course Info
Java: $3500
course_3.txt
Course Info
HTML: $2900
course_4.txt
Course Info
SQL: $2800
TABLE OF INDEX
Alphabetical Index
A
arithmetic 52, 54, 63, 77, 192
Arithmetic 52, 54, 63, 77, 192
Assignment 52, 55, 56, 63
Assignment 52, 55, 56, 63
B
bool 32, 42, 43, 45
boolean 32, 42, 43, 45
Break 118, 124, 130, 223
C
Card Game 202
Cards 23, 199-203, 205
Casting 32, 42, 43, 45
Comment 40
Comments 40
Comparison 52, 58, 59, 64, 81
Conditional 59, 96, 99, 113, 119
Conditional Statements 59, 96, 119
Continue 118, 119, 124, 125, 129, 130, 132
Courses 227
Current Date 209
D
Data Types 30, 32, 33
Date 24, 27, 67, 72, 83-85, 87, 128, 166, 206-214
Dices 198
Dictionary 21, 23, 30-32, 34-36, 38, 47, 49, 50, 52, 55, 57, 58, 72, 100, 120, 128, 131, 152-
163, 170, 200-203, 205
Directories 215-217, 224
Discount 96, 97
Dollar 20, 22, 108, 170, 202, 204
Dollars 20, 22, 108, 170, 202, 204
E
end 15, 18, 26, 29, 31, 36-38, 79, 80, 82, 87, 88, 93, 96, 99, 111, 120-128, 132, 133, 135,
137-143, 146-149, 151, 159, 160, 165, 168, 179, 183, 184, 188, 206, 219, 220, 223
errors 26, 177, 216
Escape Sequences 44, 46
Escape Sequences 44, 46
Euro 20, 108, 114, 170, 208
Exceptions 177, 178, 183-187
F
Files 27, 29, 215, 218, 224, 225
Finally 178, 188, 189, 194, 195
Float 32, 42, 43, 45
Float 32, 33, 42, 43, 45, 50, 77, 163, 170
For Loop 120, 126-128, 131, 132, 149, 162, 163
For Loop Range 126, 127, 132
Formatting Date 208
Formatting Time 210
Function 29, 40, 42, 84, 86, 87, 94, 136-138, 140, 165, 168, 170
Functions 29, 40, 42, 84, 86, 87, 94, 136-138, 140, 165, 168, 170
Functions Return 87
I
IDE 26-28
identity 52, 61
Identity 61, 65, 66
Install 1
Installing 1
int 32, 42, 43, 45
Int 15, 18, 20, 22-27, 29-58, 61-71, 73-77, 79-83, 85, 86, 88-91, 93-95, 97-109, 116-133,
135, 136, 138-162, 166-173, 177-191, 193-195, 197-202, 204-207, 209, 211-213, 218, 219, 221-225
integer 32, 42, 43, 45
K
Keys 152-159, 162, 163
Keys and Values 156
L
Lists 134, 139, 202
logical 60, 69, 112, 113, 177
logical 59, 60, 69, 106, 107, 112, 113, 177
Logical 59, 60, 106, 107, 177, 238
Loops 116, 119
Lottery 21, 22, 202, 204
M
Membership 52, 62
Methods 29
Module 29, 197
Modules 29
modulus 52-54
Modulus 52-54
Movie List 226
Multiple Exception 183
Multiple Exceptions 183
O
Operator 52, 55-66, 81
operators 52, 55-66, 81
Operators 52, 55-66, 81
P
Packages 29
Pass 31, 119-122, 125, 135, 165, 168, 169, 174, 201, 215, 222
Pass keyword 119
Printing 31, 33-35, 37, 41, 45-48, 63-66
R
Random 21-23, 197-205
Random Choice 199
Randrage 197, 198, 202-204
Range 66, 67, 70, 120-122, 126-128, 131-133, 182, 192, 195, 197-199, 201, 202, 204
Read a File 221, 222
Readline 221-223
Rounding 39
Runtime 177, 178
S
Secret Number 20, 98
sep 29, 33-38, 57, 79, 80, 97, 98, 100-102, 152, 156, 221, 225
Sort 22, 137, 138, 142, 143, 145, 147-151, 156
string 32, 42, 43, 45
String 32-36, 38, 41-44, 48, 49, 57, 58, 72, 75-82, 84, 86-88, 90, 91, 93, 94, 111, 180, 181
Substring 80
Syntax 38, 48
T
Time 22, 24, 41, 42, 69, 72, 75, 85, 93, 96, 97, 116, 121, 122, 129, 132, 136, 154, 177, 178,
197, 198, 202-207, 209, 210, 212-214
Triangle 19
U
User Input 72, 77, 85, 93, 154, 183-185, 188, 191, 192
V
Values 23, 30-32, 34-36, 38, 47, 49, 50, 52, 55, 57, 58, 72, 100, 120, 128, 131, 152-159, 162,
163, 170, 200-203, 205
Variable 29-35, 38, 39, 45, 47, 55, 61, 72, 76
Variables 29, 30, 32, 45, 63
W
While 40, 116-119, 123-125, 127-133, 183, 197, 223