Chapter 5
The Solutions!
Finally, a chapter where you do not have to worry about solving exercises. You have gone through every curveball, every scenario and every exercise provided within this workbook, and for that, you deserve the heartiest congratulations. I am glad that you took your best shot at solving these exercises.
For every programmer, the beginning is always the biggest hurdle. Once you set your mind to things and start creating a program, things automatically start aligning. The needless information is automatically omitted by your brain through its cognitive powers and understanding of the subject matter. All that remains then is a grey area that we discover further through various trials and errors.
There is no shortcut to learn to program in a way that will let you type codes 100% correctly, without a hint of an error, at any given time. Errors and exceptions appear even for the best programmers on earth. There is no programmer that I know of personally who is able to write programs without running into errors. These errors may be as simple as forgetting to close quotation marks, misplacing a comma, passing the wrong value and so on. Expect yourself to be accompanied by these errors and try to learn how to avoid them in the long run. It takes practice but there is a good chance you will end up being a programmer who runs into these issues only rarely.
With that said, it is time to shift our focus back to the main part of this chapter, the solutions to the never-ending exercises. Some of these were incredibly simple while others were not as simple as they sounded. Regardless of how many you get right, you should never be afraid of nor let down by failure. It is a part of our learning cycle and hence should be accepted, understood and then corrected. The more you learn from your mistakes, the easier things will be in the future.
Chapter by Chapter Solutions
Chapter 1 Solutions
Below are the answers and the correct answer applicable to the question is highlighted in bold text.
Q-1:
The question asked to identify which of the codes mentioned used Python as its programming language.
●
Code 1: Unity C# - We do not use the statement ‘using’ in Python, nor do we use semicolons at the end.
●
Code 2: HTML – The second language in the list used HTML, which is used for developing websites.
●
Code 3: Python – Evident from the import statement and the missing semicolon.
●
Code 4: JavaScript – Similar to C# but with a few differences.
Q-2: How can you check if your system has Python 3.8.x installed on your system?
Let’s see what the correct method is to check for the same:
- PyCharm – PyCharm is an IDE and can be installed without having Python on board.
- Command on PyCharm – The given command will not work on PyCharm.
- Command on console/terminal – This is the correct method to locate the version of python.
- The website will not provide an indication of the version you have installed.
Q-3: What is the language named after?
This was related to the history that we covered in the previous book. If you got this wrong, it is okay. The correct answer is A. The language was named after the famous Monty Python’s flying circus.
Q-4: How does each line in Python end?
To be honest, this was one of the easiest questions. But surprisingly, people still tend to forget.
- With a colon ‘:’
- With a semicolon ‘;’
- With a full-stop/period ‘.’
-
None of the above
– Because every line in Python ends without any special character except when defining conditions or functions.
Q-5: What does the acronym IDE stand for?
We have discussed this in the previous book.
- International Day for Electronics
- Integrated Developing Environment
- Integrated Developer Environment
- Integrated Developing Engineering
Q-6: How is a string represented in Python?
- With a single quotation mark ‘’
- With a double quotation mark “”
- With either of the above. – We can create strings using single or double quotation marks.
- None of the above.
Q-7:
What is a variable?
Once again, an easy question.
- It’s a function in Python.
- It’s a method in Python.
- It’s a user-created container holding immutable values – close but not exactly the right answer as variables can change.
- It’s a user-created container holding values that can be modified.
Q-8: How would you print a string that says He said, “Yes!”?
- print(“He said, “Yes!”)
- print(f“He said, “Yes!”)
- print(‘He said, “Yes!”’) – Using double quotation marks would end the string at the start of “Yes”
- print(He said, Yes!)
Q-9: Running the code as shown, what will the output be?
num = '5' * '5'
print(num)
- 25
- 5, 5, 5, 5, 5
- ‘5’ * ‘5’
- TypeError: Can’t multiply sequence by non-int of type ‘str’ – A string cannot be multiplied by another string.
Q-10: If you run a code that ends up with an error, it will cause PyCharm to crash.
- True
- False – PyCharm is a safe working environment that is designed to test codes. If the code will crash, the IDE returns the kind of error code to inform users that this will crash when used outside PyCharm.
- Depends on the type of code written
- None of the above
Q-11:
Which is the correct method to set the value for a bool ‘is_married’?
- “True”
- True
- ‘True’
- true
Q-12:
Which of the following is a formatted string?
Code-1
:
name = "Jiovanni"
age = 41
print("Hi, I am naming and I am age years old")
Code-2
:
name = "Jiovanni"
age = 41
print(f"Hi, I am {name} and I am {age} years old")
This is the correct way to format a string. There are other ways you can format strings, but I personally find this a lot easier.
Code-3:
name = "Jiovanni"
age = 41
print("Hi, I am " + name + " and I am " + age + " years old")
Code-4
:
name = "Jiovanni"
age = 41
print("Hi, I am [name] and I am [age] years old")
Q-13: To name a variable called the first name, which method is correct? You can choose more than one answer to the following question.
- firstname
- FirstName
- first.name
- first_name
If you are surprised about the second entry here, remember that it is recommended not to use this format to name variables. While it is not recommended, it does not mean that it is wrong.
Q-14:
Choose one or more answers which apply. Clean-code practice is:
- To keep our workstations clean.
- To name our variables and functions appropriately
- To improve readability.
- To ensure the code is not breaking any laws.
Q-15:
Which of the following is the correct way to create a variable named ‘test’:
- def test():
- test.create
- test = “” – You can always create variables as blanks
- print(test)
Q-16:
What is a concatenation of strings?
- To merge two or more strings into a new string object
- To separate two strings
- To convert an integer into a string
- None of the above
Q-17: Choose the correct answer(s). Python is:
- The successor of ABC language – This was discussed in the previous book.
- Only operable through PyCharm IDE
- Used for automation and Machine Learning – These are two of the most in-demand fields of modern times.
- All of the above
Q-18:
What is OOP?
- Object-Oriented Python
- Object-Oriented PyCharm
- Object-Oriented Programming – Remember, everything in Python is considered an object.
- Only On Python
Q-19:
How can you acquire user input and store it in a variable called income, for calculation purposes?
- income = bool(“Enter your income:”)
- income = int(“Enter your income:”)
- income = input(“Enter your income:”)
- income = int(input(“Enter your income:”) – The user will input a value that will be then converted into an integer.
Q-20:
Which of these is/are true regarding Python?
- There are two data types
- Variables can be called, modified or removed.
- Python can work without PyCharm
- Python is a case-sensitive language
Yes! Python can work without PyCharm as PyCharm is just one of the many ways to operate Python and write codes.
Is This Correct? – Part 1 Solutions
This was indeed a section that caused quite a bit of confusion but provided the perfect opportunity to practice our coding skills and keep an eye out for errors. Let us look at the solutions to the questions posed within the first part of the “Is This Correct?” series.
Q-1: The program shown below was created to display a concatenated string. Do you think that the following will work? Will this deliver the required output of “This will be added With this!” or would it produce completely different output? If so, why?
string1 = "This will be added "
string2 = "With this!"
print("string1 + string2")
Ans:
The actual answer would be as shown below if you were to run this code as it is:
string1+string2
This happened because the print statement was given a string that contained the characters string1 and string2. Python took them quite literally as a string object. In order to make them work properly, you will need to use a formatted string. The solution would be as shown here:
string1 = "This will be added "
string2 = "With this!"
print(f"{string1}{string2}")
Output:
This will be added With this!
Q-2: Following is a program, written by a skilled programmer for a local business called “Pete’s Garage” which should provide the business with a more reliable way of dealing with things. The program is written as shown below:
print('Welcome to Pete's garage)
name = input('Please enter your name: ')
job_number = int(input('Please enter your job number: '))
repair_cost = 100
discount = 15
total = repair_cost - discount
print("{name}, the total for {job_number} is ${total}")
print('Thank you for your business')
Will this program work? If not, can you identify the error that might cause this program to crash or stop responding?
Ans:
To begin with, there are a few errors that need addressing. Beginning at the very top, the first print statement is not correctly written. The string ends at the apostrophe after Pete and hence the program will not function nor identify the rest.
Moving forward, the print statement declaring the total is not formatted. It is missing the ‘f’ key character. Once these two errors are sorted, the program should function rather well.
If you try the program now, it should display this:
Welcome to Pete's garage
Please enter your name: Emma
Please enter your job number: 91829
Emma, the total for 91829 is $85
Thank you for your business
Process finished with exit code 0
Q-3: A university student decided to piece together a program that will allow potential online students from abroad to fill out the form and seek out further information regarding courses they’re interested in. The form looks like this:
#Online Registration Form
print("Welcome to ABC Uni!")
print("Please enter the required information to begin.")
s_f_n = input("Enter your name: ")
phone = int(input("Enter your phone number: ")
em = "Enter your email: "
crs = "Choose your course:
The student has asked to review the program and find out if there are any issues that need addressing. Find out what is wrong with the code and correct the issues.
Ans:
Once again, we see that the phone variable has two opening parentheses but only one closing parenthesis. Fix that first to ensure that this line of code is functional. Next, the ‘em’ variable has a fixed string value. But we are trying to get an input from the user. Use the input function here. Lastly, the ‘crs’ has an opening quotation mark but no closing quotation mark. It is also missing the input function.
Lastly, if needed, a print statement can be added to confirm the selection. The overall program should look like this:
#Online Registration Form
print("Welcome to ABC Uni!")
print("Please enter the required information to begin.")
s_f_n = input("Enter your name: ")
phone = int(input("Enter your phone number: "))
em = input("Enter your email: ")
crs = input("Choose your course: ")
print(f"{s_f_n}, you have chosen {crs} as your course.")
print(f"Details of the {crs} course will be emailed to you at {em}")
print(f"We may also be in touch via a phone call at {phone}")
Output:
Welcome to ABC Uni!
Please enter the required information to begin.
Enter your name: Joel
Enter your phone number: 915789654
Enter your email: joel@abcxyz.com
Choose your course: Game Development
Joel, you have chosen Game Development as your course.
Details of the Game Development course will be emailed to you at joel@abcxyz.com
We may also be in touch via a phone call at 915789654
Q-4: A student has created a program for a login page at a library for the new batch of users that have just joined. After a brief introduction, all users are asked to create their username and password pairs. After the users have entered their passwords, each password is compared to ensure that it matches. The program looks like this:
username = input("Username: ")
password = input("Password: ")
print("You have entered the following:")
print(username.lower())
print({password.lower()})
print(password==password.lower)
What seems to be the problem here? Why do you think the code will not work? What can be done to ensure that the program starts functioning?
Ans:
The program would not have worked as it would have printed out a case-sensitive password in all lower-case. A comparison between the two would then obviously return ‘false’ as they would not be the same.
Remember, Python is a case-sensitive language. Password is not the same as PASSWORD or password. To make this a fully functioning program, you will need to do a little more than just tweak parentheses or fill out missing values.
Here is my take on the same program.
username = input("Username: ")
password = input("Password: ")
print("You have entered the following:")
print(username)
print(password)
login = False
login_id = input("Please enter your username: ")
login_pwd = input("Enter your password: ")
while not login:
if login_id == username and login_pwd == password:
print("You have logged in successfully")
login = True
elif login_id == username and login_pwd != password:
print("You have entered the wrong password")
break
elif login_id != username and login_pwd == password:
print("You have entered the wrong ID!")
break
else:
print("You have entered an invalid ID/Password")
break
Q-5: A programmer, with intermediate experience and knowledge, was asked to type out a program that would print out Boolean values for every grade a student acquires. For grades from A to B, the prompt was to print out True, while others would be considered False. Have a look at this code and see if this will work:
grades = ["A", "A", "B"", "U", "F", "E", "D"]
for x in grades:
if x == A or x == B:
x = True
if x == True:
print("Pass")
else:
x = False
print("Fail")
The student has claimed that the code worked exceptionally. It is now up to you to analyze the code without testing it first to deliver your first impressions.
Ans:
Once again, we see some misplaced quotation marks in the first line. The first order of the day is to correct those right away. Then we have our ‘if’ statements. See how the statement says if x == A. Here, we need to add quotation marks in order for A to be a string object instead of a separate variable. Here is the end result:
grades = ["A", "A", "B", "U", "F", "E", "D"]
for x in grades:
if x == 'A' or x == 'B':
x = True
if x == True:
print("Pass")
else:
x = False
print("Fail")
Output:
Pass
Pass
Pass
Fail
Fail
Fail
Fail
Q-6: A string named initial_message contains the following message:
“
Hi, I have just taken part in the course. I hope that I will be a programmer one day.
”
Excluding the quotation marks, a programmer was asked to find out the length of the string. She used the following method to do so:
String.length(initial_message)
Is this the correct method to check the length of a string? If not, what is the correct method applicable here?
Ans:
No. That is not the correct way to check the length of the string. The correct way to do so is using the len()
function, as shown here:
print(len(initial_message))
This will then count the characters and print out the value of characters in return.
Chapter 2 Solutions
Task-1: A YouTube streamer decided to conduct a survey where users were asked to provide feedback on what they would like to watch in the next stream. Your job is to create a program that uses the following information and prints out the result of what the user chose, along with a thank you message.
What shall I stream next?
a)
Days Gone
b)
Resident Evil 2
c)
Fortnite
d)
Apex Legends
e)
Death Stranding
f)
Surprise Us!
The ending message should be:
You have chosen (option). I appreciate your time and hope to see you in the next one!
Ans:
This is indeed quite an easy one to do. Here is the solution for the survey that this streamer is trying to create.
print("Welcome to my survey, where I ensure I deliver what you want!")
print("Please, take some time to fill this out and help me decide what to play next!")
a = "Days gone"
b = "Resident Evil 2"
c = "Fortnite"
d = "Apex Legends"
e = "Death Stranding"
f = "Surprise Us"
print(f"""Here are your options. Remember, select one:
a){a},
b){b},
c){c},
d){d},
e){e},
f){f}""")
selection = input("Please make a selection: ")
print(f"You have chosen {selection}. I appreciate your time and hope to see you in the next one!")
And the corresponding output would look like this:
Welcome to my survey, where I ensure I deliver what you want!
Please, take some time to fill this out and help me decide what to play next!
Here are your options. Remember, select one:
a)Days gone,
b)Resident Evil 2,
c)Fortnite,
d)Apex Legends,
e)Death Stranding,
f)Surprise Us
Please make a selection: b
You have chosen b. I appreciate your time and hope to see you in the next one!
And that would be as simple as that. If you were able to do this easily, well done. If not, now you have every idea of how it works. Do remember that this is a very basic level of programming. You can make this as interactive as you wish. Now, you can try using various methods to make it even better.
Task-2: A dentist wishes to have a program created for his website where the customers will be presented with multiple services. The customer will choose the option and will be presented with a total for the service that is payable by the customer. The services are given as shown below:
a)
Root Canal Therapy - $250
b)
Oral Hygiene Check - $50
c)
Emergency Injury Treatment - $100
d)
Post-Procedure Check-up - $150
e)
Routine Check-ups and Consultation - $75
For advanced payments, customers get a 50% discount.
Design a program that provides the customer with all the necessary information and gives a total according to what the customer chooses.
Ans:
I already gave you a hint, but now, let us see how this would work.
print("The Patient's Portal")
print("Please select the service you would like to come in for.")
a = "Root Canal Therapy"
print(f"A){a}")
b = "Oral Hygiene Check"
print(f"B){b}")
c = "Emergency Injury Treatment"
print(f"C){c}")
d = "Post-procedure checkup"
print(f"D){d}")
e = "Routine Checkups and consultation"
print(f"E){e}")
selection = input("Please choose one: ")
print(f"You chose {selection}")
total = 0
if selection.lower() == "a":
total = 250
print(f"Your total is ${total}")
elif selection.lower() == "b":
total = 50
print(f"Your total is ${total}")
elif selection.lower() == "c":
total = 100
print(f"Your total is ${total}")
elif selection.lower() == "d":
total = 150
print(f"Your total is ${total}")
else:
total = 75
print(f"Your total is ${total}")
print("Did you know? Book in advance and get 50% off!")
payment_time = input("Would you like to pay today? [y/n]: ")
if payment_time.lower() == "y":
total = total * 0.50
print(f"Your total payable is ${total}")
else:
print(f"You will need to pay ${total} at the counter.")
print("Have a smiling day!")
The output should show you the following:
The Patient's Portal
Please select the service you would like to come in for.
A)Root Canal Therapy
B)Oral Hygiene Check
C)Emergency Injury Treatment
D)Post-procedure checkup
E)Routine Checkups and consultation
Please choose one: a
You chose a
Your total is $250
Did you know? Book in advance and get 50% off!
Would you like to pay today? [y/n]: y
Your total payable is $125.0
Have a smiling day!
The program is a little long, but it does keep you engaged and keeps you on your toes to type in the correct code in order to make a successful program. If you were able to figure this one out on your own, brilliant. If not, it is perfectly okay. There is plenty of time to learn what you need to do in order to carry out various tasks to come up with your desired results.
Task-3: A college campus has decided to create a program that will determine the eligibility of an applicant based on a few questions and conditions. The college in question has asked you to create a program to record the following pieces of information:
a)
First name
b)
Last name
c)
Age
d)
Overall marks in their latest test result (out of 600)
e)
If seeking scholarship
Based on the following conditions, the eligibility for admission and for the scholarship will be decided:
For Admission:
●
The student should have achieved at least a 60% overall score or above for admission.
For Scholarship:
●
The student must have at least a test score of 80% in order to be eligible for the scholarship.
Create a program with data from three different students where they have acquired 471, 354 and 502 accordingly. Print out their results based on the above conditions.
Ans:
This program also required some critical thinking and posed a bit of a challenge with three different situations. To address these, we need our friendly ‘if’ statements to help us out and create an intelligent program.
print("Welcome to the Applicant’s eligibility checker")
first_name = input("Please enter your first name: ")
last_name = input("Please enter your last name: ")
age = input("Please enter your age: ")
marks = float(input("Please enter your overall marks (out of 600): "))
total_marks = 600.0
passing_marks = total_marks * 0.60
marks_for_scholarship = total_marks * 0.80
if marks >= passing_marks:
print(f"Congratulations {last_name}! You are eligible for admission to the college!")
scholarship = input("Are you seeking a scholarship? [Y/N]: ")
if scholarship.lower() == "y" and marks >= marks_for_scholarship:
print(f"Congratulations {last_name}! You are eligible for a scholarship!")
elif scholarship.lower() != "y":
pass
else:
print(f"{last_name}, you are not eligible for a scholarship at this time!")
else:
print(f"Unfortunately {last_name}, you are not eligible for admission.")
print("Thank you for your input and we wish you good luck!")
The output for the above would be as shown below:
Welcome to the Applicant’s eligibility checker
Please enter your first name: John
Please enter your last name: Doe
Please enter your age: 21
Please enter your overall marks (out of 600): 402
Congratulations Doe! You are eligible for admission to the college!
Are you seeking a scholarship? [Y/N]: y
Doe, you are not eligible for a scholarship at this time!
Thank you for your input and we wish you good luck!
Is This Correct? – Part 2 Solutions
Q-1: A programmer came up with a program that would find the highest number from a given set of numbers. The numbers provided were stored as a list in a list variable called ‘number_data’ and the program that he designed looked like this:
number_data = [323, 209, 5900, 31092, 3402, 39803, 78341, 79843740, 895, 6749, 2870984]
for number in number_data:
if num < number:
num = number
print(num)
Will the above code work? What’s wrong with the code?
Ans:
The above code will not work as the variable ‘num’ is not defined. While some may have been unnecessarily worried, the solution was rather simple. Just declare a variable called num with a starting value of zero.
number_data = [323, 209, 5900, 31092, 3402, 39803, 78341, 79843740, 895, 6749, 2870984]
num = 0
for number in number_data:
if num < number:
num = number
print(num)
Remember to declare variables before they are used as Python reads the program line by line.
Q-2: A freelance programmer was tasked with creating a simple program to determine the eligibility of a profile for an auto-loan. Based on some specific information and conditions, such as the candidate should be less than 45 years of age, must have a minimum of a certain amount as income and should not have any criminal records, the program was to determine if the same person was eligible for a loan or not. The programmer wrote the following program:
print("Your doorway to auto-loan eligibility check!")
print("Please provide complete information for best results")
name = input("Please enter your full name: ")
age = int(input("Enter your age: "))
income = int(input("Please enter your income per month: "))
nature_of_job = input("Do you work full-time, part-time or as a freelancer?: ")
has_license = input("Do you have a valid license? [y/n]: ")
if has_license.lower() == "y":
has_license = True
else:
has_license = False
has_criminal_record = input("In the last 5 years, do you have any criminal records? [y/n]: ")
if age > 45 and income >= 8000 and has_license == True and has_criminal_record == False:
print("You are eligible for a loan")
elif age < 45 and income >= 5000 and has_license == True and has_criminal_record == False:
print("You are eligible to apply for a loan")
elif has_criminal_record:
print("You are not eligible for a loan")
elif income < 5000:
print("You are not eligible at this time")
else:
print("Please be patient as one of our specialists will be in touch!")
Upon executing a sample, the result was as follows:
Your doorway to auto-loan eligibility check!
Please provide complete information for best results
Please enter your full name: John Smith
Enter your age: 38
Please enter your income per month: 8300
Do you work full-time, part-time or as a freelancer?: Full-time
Do you have a valid license? [y/n]: y
In the last 5 years, do you have any criminal records? [y/n]: n
You are not eligible for a loan
Process finished with exit code 0
Do you think the program executed correctly? If not, what do you think the issue is?
Ans:
The above program has one major issue which will cause the program to always push out not eligible as a result. The has_criminal_record has not yet been defined as True or False. For that, we need to create a separate condition. Here is the fully operable program with a sample test.
print("Your doorway to auto-loan eligibility check!")
print("Please provide complete information for best results")
name = input("Please enter your full name: ")
age = int(input("Enter your age: "))
income = int(input("Please enter your income per month: "))
nature_of_job = input("Do you work full-time, part-time or as a freelancer?: ")
has_license = input("Do you have a valid license? [y/n]: ")
if has_license.lower() == "y":
has_license = True
else:
has_license = False
has_criminal_record = input("In the last 5 years, do you have any criminal records? [y/n]: ")
if has_criminal_record.lower() != "y":
has_criminal_record = False
else:
has_criminal_record = True
if age > 45 and income >= 8000 and has_license == True and has_criminal_record == False:
print("You are eligible for a loan")
elif age < 45 and income >= 5000 and has_license == True and has_criminal_record == False:
print("You are eligible to apply for a loan")
elif has_criminal_record:
print("You are not eligible for a loan")
elif income < 5000:
print("You are not eligible at this time")
else:
print("Please be patient as one of our specialists will be in touch!")
Output:
Your doorway to auto-loan eligibility check!
Please provide complete information for best results
Please enter your full name: Elliot Charington
Enter your age: 41
Please enter your income per month: 6900
Do you work full-time, part-time or as a freelancer?: full
Do you have a valid license? [y/n]: y
In the last 5 years, do you have any criminal records? [y/n]: n
You are eligible to apply for a loan
Q-3: As a school project, every student was asked to come up with a program that is no longer than 10 lines and is able to do some basic mathematics to produce answers. The student came up with a simple program that asks the user to type in a number and will let them know if the number is even or odd. The program is as shown below:
print("Setting the ODDS, EVEN!")
num = input("Enter a number: ")
if (num % 2) = 0:
print("{0} is Even")
else:
print("{0} is Odd")
Do you think the program will work? What errors do you think, if any, would cause problems for the student?
Ans:
This program has a few issues. Firstly, notice that the print statements are not formatted. Secondly, the condition set is not using the right comparison operator. Instead of ‘=’ we need to use the ‘==’ operator to provide the condition with a comparison point.
Moreover, the input will initially be stored as a string. Be sure to use the int
converter. Lastly, replace the ‘0’ in the print statements with the variable ‘num’ and that should do it. If you run the program now, it should be fully functional and should return the correct results.
print("Setting the ODDS, EVEN!")
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd")
Q-4: As a side project, a programmer decided to create a simple program that can let users know if the year, mentioned by the user, is a leap year or not. The leap year is calculated by determining if the year is exactly divisible by the number ‘4’ and in the case of a century year, like the year 2000, it must be exactly divisible by 400.
Using the above concept, the programmer wrote this code:
print("My Brilliant Little Leap Year Calculator!")
year = int(input("Please enter the year: "))
if (year / 4) == 0:
if (year / 100) == 0:
if (year / 400) == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
When the code was run with the year 2020, the following was the response:
My Brilliant Little Leap Year Calculator!
Please enter the year: 2020
2020 is not a leap year
Process finished with exit code 0
Why do you think that is?
Ans:
This one involved a little more mathematics than actual programming. Using the ‘/’ operator, we would not have received the exact values. Instead, we will need to change all the ‘/’ operators to ‘%’ and run the program again. Now, the year 2020 will be shown as a leap year, and any other leap years will be correctly calculated as well.
print("My Brilliant Little Leap Year Calculator!")
year = int(input("Please enter the year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Output:
My Brilliant Little Leap Year Calculator!
Please enter the year: 2020
2020 is a leap year
Project – 1 Solution
(Exercise 118: Stephenson, B. (2014) The Python Workbook)
As promised, here is how I have created a simple game of “Rock, Paper, Scissor” using Python.
from random import randint
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0, 2)]
tries = 0
player = " "
while tries <= 9:
player = input("Rock, Paper, Scissors?")
tries += 1
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
else:
print("You win!", player, "smashes", computer)
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
else:
print("You win!", player, "covers", computer)
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
else:
print("You win!", player, "cut", computer)
else:
print("That's not a valid play. Check your spelling!")
computer = t[randint(0, 2)]
You may copy this and try it out yourself. Change the values where possible to see how it affects the program. This is one terrific way to spend some quality time with a game while learning the dynamics as well.
Chapter 3 Solutions
Task-1: A programmer has been asked to create a simple program where he is to map out digits from zero to nine in words. The program will ask a user to enter his/her number, and the program will print the same out in text instead. The desired result is as shown below:
Please, enter your number:
415602397
Output:
Four One Five Six Zero Two Three Nine Seven
How do you suppose this can be achieved? Would we need to use a loop here or a set of conditional statements?
Ans:
To achieve this simple goal, we will use a dictionary to create key-value pairs. Here is the solution, and honestly it is worth a try.
number = input("Phone number: ")
words = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine",
"0": "Zero"
}
output = ""
for char in number:
output += words.get(char) + " "
print(output)
This should now print out words instead of numbers.
Task-2: A student carried out a program that calculated the shipping cost for an online retailer for the customer. The program would base the shipping cost on the total of the cart and the country of residence of the customer in question.
What do you think the student did?
Ans:
Refer to the original chart in the question for reference purposes. A successful version of the program would be as shown here:
total = int(input("Please enter the total amount: "))
country = input("Country [US/AU/CA/UK]: ")
if country.upper() == "US":
if total <= 99 and not total <= 49:
print("Shipping Cost is $10")
elif total >= 100 and not total >= 250:
print("Shipping Cost is $25")
elif total >= 250:
print("Shipping Costs $50")
else:
print("FREE")
if country.upper() == "AU":
if total <= 99 and not total <= 49:
print("Shipping Cost is $20")
elif total >= 100 and not total >= 250:
print("Shipping Cost is $50")
elif total >= 250:
print("Shipping Costs $100")
else:
print("Shipping Cost is $10")
if country.upper() == "CA":
if total <= 99 and not total <= 49:
print("Shipping Cost is $15")
elif total >= 100 and not total >= 250:
print("Shipping Cost is $30")
elif total >= 250:
print("Shipping Costs $75")
else:
print("Shipping Cost is $5")
if country.upper() == "UK":
if total <= 99 and not total <= 49:
print("Shipping Cost is $25")
elif total >= 100 and not total >= 250:
print("Shipping Cost is $55")
elif total >= 250:
print("Shipping Costs $110")
else:
print("Shipping Cost is $20")
The output would provide you the correct answers according to the input.
Task-3: You are a programmer who has been tasked with creating a simple yet intelligent game that stores a name that the users will have to guess. Upon providing the wrong name, the program will provide hints. You have created the following program, however, there seems to be something wrong here.
name = 'James'
guess = input("I have a name. Can you try to guess it?: ")
guess_num = 0
max_guess = 5
while guess != name and guess_num == max_guess:
print(f"I am afraid, that's not quite right! Hint: letter {guess_num +1} ")
print(guess_num + 1, "is", name[guess_num] + ". ")
guess = input("Have another go: ")
guess_num = guess_num + 1
if guess_num == max_guess and name != guess:
print("Alas! You failed. The name was", name + ".")
else:
print("Great, you got it in", guess_num + 1, "guesses!")
Ans:
Believe it or not, there was only one slight error. The program worked, but the problem was that it would accept even an incorrect entry as correct. If you pay close attention to the ‘while’ condition, you will notice that guess_num == max_guess is never met, hence this block of code never gets executed. When that happens, there is nothing to add an increment to the number of guesses. The program would then move on to the ‘if’ statement, and hence choose the ‘else’ part as the output. To correct this, all you needed to do was to replace the ‘while’ condition to this:
while guess != name and guess_num != max_guess:
Now, the program should function properly and make this into an interactive little game.
Question and Answers
Q-1: What does the
==
operator do?
- It assigns a value
- It recalls and matches the value of variables before and after it
- It lets Python know not to equate variables
- None of the above
Q-2: What is wrong with the code below?
x = 20
y = 30
z = 40
if x > y:
print("Something's wrong here")
- Since x is less than y, the program will crash and return an error
- z is not called, hence the program will not function
- The condition is not followed by an indentation
- There is nothing wrong with the program
Q-3: What will the result of the following program be?
alpha = 'Bravo'
bravo = 'Charlie'
charlie = 'Alpha'
for char in alpha:
if char != 'a':
print(char)
- Bravo
- Charlie
- Alpha
- None of the above – The result would print “B r a v o”
Q-4: What is the difference between 100 / 30 and 100 // 30?
- It is just a typing mistake
- Both will deliver the same results
- The / will show a float figure while the // will show an integer remainder
- The / will show an integer remainder while the // a float remainder
Q-5: What will the code shown below print as a result if a car is traveling at 75 miles per hour?
car_speed = int(input("Enter Car's current speed: "))
acceleration = 20 #per second
top_speed = 100
time = 0 #in seconds
if car_speed == 0:
time = top_speed // acceleration
print(f"It should take {time} second(s) for the car to reach its top speed")
#For a stationary vehicle
else:
time = (top_speed - car_speed) // acceleration
print(f"it would take {time} second(s) to hit max speed.")
#For a vehicle in motion
- 5 second(s)
- 3 second(s)
- 1 second(s) – We are using the // operator, which will always return an integer value
- Program will return an error
Q-6: When should you use a ‘for’ loop?
- When we need one specific output
- When we need to iterate over a range of elements
- When we wish to set a certain condition to be either true or false
- None of the above
Q-7: What does the following error indicate?
Traceback (most recent call last):
File "C:/Users/Programmer/PycharmProjects/PFB/PFB-2/Project-2.py", line 1, in <module>
car_speed = int(input("Enter Car's current speed: "))
ValueError: invalid literal for int() with base 10: 'abc'
Process finished with exit code 1
- The program crashed due to an invalid value entry
- The program crashed as ‘abc’ was not entered as a string
- Used single quotes instead of double quotes
- None of the above
Q-8: The following program uses the log10 module from the ‘math’ package. The program was designed to carry out a few arithmetic operations to test the values and functionality of the program. What seems to be wrong here?
from math import log10
a = input("Enter 1st value: ")
b = input("Enter 2nd value: ")
print(a, "+", b, "is", a + b)
print(a, "-", b, "is", a - b)
print(a, "*", b, "is", a * b)
print(a, "/", b, "is", a / b)
print(a, "%", b, "is", a % b)
print(f"The base 10 logarithm of {a} is {log10(a)}")
print(a, "^", b, "is", a**b)
- The strings are not formatted properly
- The input values are stored as strings instead of integers
- The log10 function will not work within a formatted string
- All of the above
Q-9: What does an ‘elif’ statement do that ‘else’ can’t?
- Elif conditions are secondary conditions that are executed when the main condition is false.
- Elif statements do not require conditions whereas else statements do.
- Elif statements are exactly the same as else statements.
- None of the above.
Q-10: What does the following produce as a result?
def high_number(numbers):
max = numbers[0]
for number in numbers:
if number < max:
max = number
return max
list = [21, 200, 31, 1, 39]
print(high_number(list))
- 39
- 5
- 200
- 1 – If you chose 200 because I named the function high_number, you missed out on the fact that I used a < operator instead of >, hence the result would always be the smallest number in the list.
Q-11: It is necessary to use ‘if’ statements every time you use loops. Is this statement true or false?
Ans: False – There have been many cases where we did not use ‘if’ statements when we used a loop.
Is This Correct? – Part 3 Solutions
Q-1: A programmer decided to create a simple program, just to practice basic ‘if’ and ‘else’ conditions. He wrote the following program:
name = "John"
age = 33
is_married = True
is_happy = input("Are you happy?: ")
if is_happy.lower() == "yes":
print("Well done!")
else:
print('Sorry to hear that')
While the program runs fine, there is something that is wrong. Can you figure out what it is? You should be able to remove it and the program will still continue to function properly.
Ans:
The is_married condition is neither needed nor being used anywhere. This is only making the program a little more confusing. It is best to remove anything from the program will never be used. The program should still be able to run properly.
Q-2: A student defined a function as shown below:
def kms_to_miles(distance):
distance * 0.621
When trying to use it, the program returned a value of ‘None’ as a result. Why do you think that happened?
- The student must have not passed the appropriate parameter.
- The distance used would have been in miles, hence the error.
- The student forgot to use ‘return’ before the calculation while defining the function.
- I have no idea why this failed. It should have worked.
Q-3: Do you think the following program should work? If not, why?
prices = [5, 10, 15, 20, 25]
total = 0
for item in prices:
total += item
print(f"Your total price is: ${total}")
Ans:
The program is actually error-free. This program should run fine on its own.
Q-4: In our previous book, we went through an example program as shown:
for a in range(3):
for b in range(3):
for c in range(3):
print(f"({a}, {b}, {c})")
If you were to change the values of the ranges from top to bottom to 3, 2, 1, respectively, would the program work? What will the outcome be?
Ans:
The program should continue to work and the outcome will be the following:
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
Q-5: According to a student, the indentation is unnecessary and should not cause any problems when executing a program. The other student is of the idea that Python pays attention to whitespace and hence the indentation is quite important to maintain the code and arrange it accordingly. Which of the two do you think is right?
Ans:
The latter has the correct answer as Python pays significant attention to whitespaces. This is exactly why Python will fail to function if you forget to use an indentation where it is necessary.
Q-6: Look at the code snippet below. It was taken from a program that was designed to iterate over key pairs of a dictionary.
output = ""
for char in number:
output += words.get(char) + " "
print(output)
What does the += operator do here?
Ans:
Although the program written above will fail to work, owing to multiple issues, the actual question is highlighting what the += operator would do. This operator adds as an increment the value of words.get(char) to the output on every loop.
Q-7: A teenager wanted to print out a simple design on python as a result. The design shown below was the output:
*
**
***
****
*****
******
*******
********
*********
**********
I did this!
**********
*********
********
*******
******
*****
****
***
**
*
Do you think this can be done using loops? If so, can you code the program?
Ans:
There are two ways you can carry out this program. The first one involves a lot of lines, each using a print statement. That is far too basic and we will simply ignore that. The second one involves the use of loops, and that is where things get interesting. Here is how you can achieve this:
character = '*'
for char in range(0, 11):
output = character * char
print(output)
print("I did this!")
for char in range(10, 0, -1):
output = character * char
print(output)
You have first informed Python to iterate through the range in ascending order. In the second loop, you have used a -1 step in the end and reversed the order of the range. Now, it will start from 10 and end at the last number of the range.
Chapter 4 Solutions
Q-1: Taxi Fare Calculator
Ans:
This was actually a little tough. There were quite a few components which needed to be readdressed a few times before arriving at the final phase. Here is my defined function to carry out the taxi fare calculations.
def calculate_fare():
distance = float(input("Enter the distance in kms: "))
distance = distance * 1000 #Convert kms into meters
fare = 3.0 + ((distance / 100) * 0.1) # extra fare charged at every 100 meters
return fare
print(f"Your total taxi fare is ${calculate_fare()}")
Remember, you will need to use a float value to get the correct answers.
Q-2: Card Deck Shuffler
Ans:
This one was hard. I am sure you had to do a bit of research, and if you did, it is perfectly okay. I was not expecting you get this one right immediately. Using functions can sometimes be tricky, especially if it involves quite a few elements. Here is how this is done:
from random import randrange
def createDeck():
cards = []
for suit in ["s", "h", "d", "c"]:
for value in ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]:
cards.append(value + suit)
return cards
def shuffle(cards):
for i in range(0, len(cards)):
other_pos = randrange(0, len(cards))
temp = cards[i]
cards[i] = cards[other_pos]
cards[other_pos] = temp
def main():
cards = createDeck()
print("This is the original deck: ")
print(cards)
print()
shuffle(cards)
print("This is the shuffled version: ")
print(cards)
main()
Now, the result should show you both the original cards and the shuffled version as well.
Q-3: Random Password Generator
Ans:
The solution to this is as shown below. Most of it is pretty much self-explanatory.
from random import randint
shortest_pass = 6
max_pass = 8
min_ASCII = 33
max_ASCII = 126
def randomPass():
randomLength = randint(shortest_pass, max_pass)
result = ""
for i in range(randomLength):
randomChar = chr(randint(min_ASCII, max_ASCII))
result = result + randomChar
return result
def main():
print("Your randomly generated password: ", randomPass())
main()
I encourage you to try and change the values per your liking to change the outcome and see how the overall program is affected.
Is this correct? – Part 4 solutions
Q-1: Below is a user-made function that is designed to iterate through a given range and look for the highest number. Will the function work when it is called?
def high_number(numbers):
max = numbers[0]
for number in numbers:
if number < max:
max = number
return max
list = [21, 200, 31, 1, 39]
high_number(list)
Ans:
The above is actually a code you have already visited in this workbook. Currently, it will not print out anything as there is no print command used. In order to print the result, use the print function and place the function with the parameter within the parentheses of the print function. Before executing the code, be sure to change the < operator to > to view the highest number in the list.
Q-2: What seems to be the issue with the following?
def this_function():
print("Hello From This Function!")
this_function_with_args(name, greeting):
print(f"Hello {name}, From This Function!, I wish you {greeting}")
this_function()
this_function_with_args()
Ans:
In the above code, the function “this_function_with_args()” is not defined as the key element of ‘def’ is missing. Without it, Python will not be able to find anything called this_function_with_args() and hence the program will fail to execute.
Once that is sorted, you will need to pass two arguments for this function to work properly. Here is an example:
this_function_with_args("John", "Happy Birthday")
Now, the function will work as per the requirements.
Q-3: What would this function do?
def plus(a,b):
sum = a + b
(sum, a)
sum, a = plus(3,4)
print(sum)
Ans:
This function will not work as it is not defined properly and is honestly a mess. Remember, our aim is to write clean code so that everyone can understand what is going on. Here is the solution to make this function work properly:
def plus(a, b):
return a + b
sum = plus(3, 4)
print(sum)
Now, this function will calculate the two numbers that are passed as arguments.
Q-4: Can you place a loop within a function as shown below?
def plus(*args):
total = 0
for i in args:
total += i
return total
print(plus(20,30,40,50))
Ans:
Yes, the function should work perfectly fine. When defining a function, you can write hundreds of lines using ‘if’ and ‘else’ conditions as well as ‘for’ and ‘while’ loops. You can also use constructors, other predefined functions, methods and values to make the function more meaningful. There is no limitation to how much code a function can hold.
Where to Head Next
The world is now your digital playground. You have all the essentials you need to get started. You are already fluent with your basics and should have no problem tackling the bigger challenges that lay ahead of you.
To make the most of the journey, utilize great resources such as udemy, coursera, YouTube and many other major names that offer more advanced learning opportunities. There are countless books out there that offer the same learning experience with great detail. Be sure not to miss out on programming practice as the more you wait, the more you lose track of the concepts you worked so hard to learn.
Continue making great and simple programs to keep yourself in touch with the basics. Remember, the stronger the basics, the easier it is for you to advance.
Work on various projects which you can find on many websites and freelance platforms. For those willing to seek a career, consider the option of working in Artificial Intelligence, Deep Learning, Machine Learning and other related fields. These are advancing every day and require more talented programmers such as yourself to go out there and make a difference.