Chapter 3
Running Around in Circles - Literally!
The world of loops and conditional statements is one that involves quite a lot of thinking. These will test your analytical and critical thinking, your problem-solving ability and will put you in rather uneasy spots. The trick behind each one of these is to carefully understand how they work.
As always, I would personally recommend using a pen and a paper, or your choice of text editor on your computer, to first draw out the scenario using flow charts and diagrams. To give you an idea, here is one:
Table showing a simple ‘if’ conditional statement flow of a process.
Using tables or flow charts greatly helps us ease matters and develop a better understanding of the nature of the task at hand. Many great programmers first jot their ideas down into smaller parts to ensure that these are looked upon individually, where possible. By doing so, they can then focus on such charts to fully understand how the program needs to function and what the outcomes will be based on the path the user takes.
Similarly, it is highly recommended that you use such tables or charts to help you fully develop a command of ‘if’ and ‘else’ statements and ultimately master them. There is no other way to say this so I will just say it: If you wish to create intelligent programs, you can never do so without developing a thorough understanding of these conditional statements and loops.
With that said, let us continue our quest to perfect our understanding of conditional statements and loops.
To ‘if’ or ‘for’ - That Is the Question!
Quite a lot of times, even I would spend days trying to figure out if we need to use the ‘if’ and ‘else’ conditions or opt to settle for a ‘for’ and ‘while’ combination. This is one of the trickiest aspects of programming, but it is one that can certainly deliver the program much-needed quality.
I will be posing you with various questions and scenarios. Where possible, I will also let you know of the desired outcome that you should achieve. Your job, as a programmer, is to figure out whether you need to use conditional statements, loops or a combination of both to achieve said outcome.
This will be tricky, which is why it is essential that you use your favorite IDE and have a go at these. Come up with your possible solutions and match those with the ones provided at the end of the book to see if you were successfully able to crack these open.
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?
Not as easy as it sounds, is it? I can start you off with a hint; use a dictionary to create key-value pairs for numbers and words.
What you need to do next is absolutely your call. Take your time as there is no time limit imposed on you. Right now, you are practicing and learning how to be a better programmer. You can utilize your time well and without any deadlines to meet. In real-world scenarios, you may need to know all this beforehand so that you do not end up wasting time. If you are not able to do this, someone else will.
Here is our second task to think about and solve.
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.
The chart below shows the shipping cost details:
Country
Total
Shipping cost
US
<$50
$50 - $99
$100 - $249
>$250
Free
$10
$25
$50
AU
<$50
$50 - $99
$100 - $249
>$250
$10
$20
$50
$100
CA
<$50
$50 - $99
$100 - $249
>$250
$5
$15
$30
$75
UK
<$50
$50 - $99
$100 - $249
>$250
$20
$25
$55
$110
Using the information above, the student was successfully able to create the program.
What do you think the student did?
This might actually be simple, but think this through and try to make this one as pleasing as possible. If you wish to take on a bit of a challenge, add lists and tuples to the mix to further test yourself.
Every program that you come across here can be done in hundreds of ways, if not thousands. To me, the glass may seem half empty and to you, it may seem half full. It is completely based on how we analyze things and look at them.
Put your thinking cap on and for the next one, do not copy and paste the code onto your PyCharm just yet. See if you can spot the issue with this one.
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!")
Try not to jump to your IDE to figure this one out. First, take a moment or two and analyze what is causing this program to end almost immediately upon providing an incorrect name. Surely, there must be something that is not right.
Read carefully between the code lines and you should soon be able to figure the matter out. Try and resolve the issue and then try the possible solution on your IDE to see if it works.
Once again, I do encourage you to make things better by modifying the code to your liking. There are hundreds of games you can come up with which are simple yet purely entertaining for others. As programmers, we take pride in knowing that we were able to execute codes with efficiency and ease. Programs will get more complex in nature as you progress along in your programming journey. For those interested in deep learning and machine learning, expect hundreds of lines of code to train the machine. To do that, you will need to be well-versed with almost every method in existence, all the functions and modules that are available across the internet to make the most out of the experience.
Project - 2
Time for yet another project. Since we are discussing games, create a Python program that lets the user know their astrological sign from the given date of birth. The program may seem rather easy, but once you look into the smaller details, you will soon realize that this will require you to think a little out of the box.
For this project, I will not be providing hints nor a model to follow. You already have the knowledge, and you should be able to execute this one with ease and a bit of finesse as well. You do not need any special modules or packages to get this project done. All you need is a quick search on the internet to see which star sign starts when to get you going.
Through trial and error, you should be able to create a program that is able to work easily and exceptionally. Should you encounter issues, try and resolve them on your own instead of looking for a solution on the internet.
If such projects interest you, you can find many more by searching for “Python projects for beginners” and get started. The more projects you work on, the better you will learn. Keep an eye out for what is in demand these days and set your target to one day be able to carry out programming of a level that will get you paid handsomely.
Questions and Answers
I wish this was a game where we could see who leads with how many points and know who answered the questions correctly. However, we will not let that get in the way of learning.
Answer as many questions as you can. To make this interesting, time yourself and try to answer all the questions within 10 minutes. At the end of the 10-minute mark, stop and review your answers to see where you stand.
Q-1: What does the == operator do?
  1. It assigns a value
  2. It recalls and matches the value of variables before and after it
  3. It lets Python know not to equate variables
  4. 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")
  1. Since x is less than y, the program will crash and return an error
  2. z is not called, hence the program will not function
  3. The condition is not followed by an indentation
  4. 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)
  1. Bravo
  2. Charlie
  3. Alpha
  4. None of the above
Q-4: What is the difference between 100 / 30 and 100 // 30?
  1. It is just a typing mistake.
  2. Both will deliver the same results.
  3. The / will show a float figure while the // will show an integer remainder.
  4. 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
  1. 5 second(s)
  2. 3 second(s)
  3. 1 second(s)
  4. The program will return an error
Q-6: When should you use a ‘for’ loop?
  1. When we need one specific output
  2. When we need to iterate over a range of elements
  3. When we wish to set a certain condition to be either true or false
  4. 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
  1. The program crashed due to an invalid value entry
  2. The program crashed as ‘abc’ was not entered as a string
  3. Used single quotes instead of double quotes
  4. 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)
  1. The strings are not formatted properly
  2. The input values are stored as strings instead of integers
  3. The log10 function will not work within a formatted string
  4. All of the above
Q-9: What does an ‘elif’ statement do that ‘else’ can’t?
  1. Elif conditions are secondary conditions that are executed when the main condition is false
  2. Elif statements do not require conditions whereas else statements do
  3. Elif statements are exactly the same as else statements
  4. 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))
  1. 39
  2. 5
  3. 200
  4. 1
Q-11: It is necessary to use ‘if’ statements every time you use loops. Is this statement true or false?
And stop! Hopefully, you were able to do all of these within the time limit of 10 minutes. I do not expect that this was an easy task as 10 minutes is not exactly much, but then again, it was a challenge.
Well done for scoring as many as you did. The challenge wasn’t to see who could get the most answers correct. It was actually designed to ensure you continue practicing. Even if you were able to get one of these correct, using your knowledge and not just a wild guess, it shows that you were paying attention and trying to understand the problem to come up with a solution. That is exactly the kind of attitude and commitment which will take us closer to success.
Take a break, if you have been practicing for a while. It is said that a human mind needs a quick minute or two to relax after every 45 minutes. You have earned it. Once you are back, let us move ahead and try to analyze more programs and see where people have gone wrong.
Is This Correct? - Part 3
This is honestly becoming my favorite section already. We get to see many programs and get to point the errors out, and in the process, we get to learn so much more. In fact, we were even inspired by some of these programs to do something similar. Keep an eye out for programs that may seem interesting as you can always modify the way they work. However, this isn’t always allowed by the law.
It is best to ensure you first know your rights regarding copying or editing said code. For this book, you do not have to worry about it much.
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.
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?
  1. The student must have not passed the appropriate parameter.
  2. The distance used would have been in miles, hence the error.
  3. The student forgot to use ‘return’ before the calculation while defining the function.
  4. 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}")
Do not try and copy the code to your IDE. Try and analyze the situation first to see if you can spot an error.
Q-4: In our previous book, we went through an example program as shown:
for an 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?
Q-5: According to a student, 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?
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?
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?
For those who may remember the days when DOS was considered a new thing, we surely created a lot of these patterns and designs. Now, Python can carry that out but instead of just relying on print statements, we use loops to do extensive work for us instead.
There are more modules and packages such as turtle, which helps you create some incredible designs. Turtle is a built-in, pre-installed package, and you should be able to import it easily. You can easily find tutorials online to see what the entire thing is all about, and possibly use the same to see just how effortlessly Python can do our work for us.
Python is far more than just a coding language. You can get so much done by just typing a few lines. With the help of your favorite IDE, things are sure to enhance the experience and keep the learning curve high. With python, you always get to learn something new.
Speaking of new, it is time for us to look into our next chapter and come across another aspect of programming which we covered in the last book: Functions!