Follow my 11-year-old adventures with my Raspberry Pi
My dad gave me a project to challenge me today. He told me to write a program that would ask how many quarters, dimes, nickels, and pennies a person has and then tells them how many dollars that is. The first part was easy, I just used four input lines. As part of an input line, you can put text. So, if I want to ask “How many quarters do you have” and make the answer be variable q, then I just write “q = input(“How many quarters do you have?”).”
Another thing I learned is the difference between a float variable, an integer variable, and a string variable. A float is a number with decimals. An integer is a number with no decimals. A string is either a word or a number treated like a word. Since my answer for how many dollars is going to be something like X.XX then I need a float.
When I did it this way, I thought I had been successful, but there was one thing wrong. If no pennies were entered, then the answer came out like $4.6 instead of $4.60. I got lucky and Google took me to a book that had the info that I needed. I needed what is called a” string formatting operator” and a “formatting specifier”. I learned about them on page 103 in the preview of a book called Python Programming: An Introduction to Computer Science.
The string formatting operator let me put a variable inside of a print statement by adding a “%” inside of it. If the variable is a string, I put %s to insert it. So, I could put “print (“My name is %s”) %name” and it would put the variable “name” at the end of the sentence “My name is”.
The formatting specifier lets me set how the number is displayed. It looks like %0.2f. The first number tells how wide to make the number. If it was always going to be less than $10.00, then I could have put 3. Putting 0 (zero) lets it make the number as wide as it needs to be. The number after the decimal tells how many digits to put after the decimal of the variable. That’s exactly what I need! So, I put 2. The f is to tell it to be a float decimal.
Try the code below to do the same thing for you.
q = input(“How many quarters do you have?”)
d = input(“How many dimes do you have?”)
n = input(“How many nickels do you have?”)
p = input(“How many pennies do you have?”)
total =float (25 * q + 10 * d + 5 * n + p)
totaldollar = float(total/100)
print “You have a total of $%0.2f” %totaldollar
Here’s a video about variables in Python