Hey everyone, I will be starting a mini blog series where I take on exercises from http://www.practicepython.org/. The first one will involve the character input function, which is simple.
Here’s the link to the challenge: Link
Here’s the challenge
Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
- Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
- Print out that many copies of the previous message on separate lines. (Hint: the string
"\nis the same as pressing the ENTER button)
Here is the solution to the main part of the exercise:
What did I do here?
- I defined the function and set three variables, name, age, and year. The name and age variables are self explanatory and they involve the user to input the information.
- The year will be used to determine when the user will turn 100. Thus, the formula is 2017 (the current year) plus the difference between 100 and their current age (which is how many years they have left before they turn 100)
- I didn’t realize that I actually didn’t have to print out what their name is nor their age but when I realized, I didn’t bother to remove it to show how to implement variables into the print function.
- I added conditional branches to check their age in which the shell would print the appropriate message. The user will get the year that they turn 100 if they are under 100. Otherwise, they will be told that they are already 100 if they entered ‘100’ or will be told that they are older than 100 if they entered an age that is higher than 100.
Not too bad, eh? Now, it’s time to add the extras. The challenge asks us to print the message that tells them when they’ll turn 100 the number of times that is inputted by the user.
I set up a new variable called repeat which will be a number that multiplies the string.
Now they want us to do the same thing but with the string printed on separate lines. You can use \n to do this but the while loop also does the trick.
And the challenge is complete!