Tip calculator

Marco's Dino
Marco's Dino

Multiple choice

What term do we use for a common way of doing things?

Saving
A

A template

B

A pattern

C

A recipe

D

A trick

Not graded. So why do it?

Multiple choice

Comments can show you the ________________ of a program.

Saving
A

Cost

B

Variable

C

Structure

D

Happiness

Not graded. So why do it?

Let's make a simple calculator to work out restaurant tips. You'll learn about working backwards, and data types.

Specs

Let's start off with what we want the program to do, that is, the specifications. Here's what I/O (input/output) should look like.

Output

Hey, can you guys write this? Adela, can you take the lead?

Adela
Adela

OK, no problem.

It's an IPO program because you said that before. An input chunk, then a processing chunk, then an output chunk.

Umm, any hints on how to get started?

Aye. Work backwards. Write the output code first.

Georgina
Georgina

Oh, I get it! Write the output code, then you'll know what variables you need to make the output.

Right! Here's the I/O again:

Output

Ethan
Ethan

So the last line of code will be a print(). Maybe:

print('Total: ' + total)

We know we'll need a total.

Good! (That won't quite work, because computers are stupid. We'll get to the problem in a bit. You have the right idea, though.)

The line before the last line?

Ray
Ray

How about:

print('Tip: ' + tip)

Before that:

print('Meal cost: ' + meal_cost)

Not sure about the line before that, though, with all the dashes.

Adela
Adela

Hmm... maybe just...

print('----------------')

So we have:

  • # Output
  • print('-----------------')
  • print('Meal cost: ' + meal_cost)
  • print('Tip: ' + tip)
  • print('Total: ' + total)
  • ​​​​​​​

Cute mammal

Yay! You've got the output code. Now what?

Adela
Adela

Before the output, maybe we do the calculations. Like, you can't have this in the program...

print('Total: ' + total)

... without a value for total.

Ethan
Ethan

Good thinking, Adela! That makes sense.

The output code prints the variables meal_cost and tip. So, it looks like the total is the cost of the meal plus the tip amount.

total = meal_cost + tip

Ray
Ray

Ooo! I got the tip. The meal cost times 15%.

I don't know how to write multiply. Let me google it... OK, this:

tip = meal_cost * 0.15

Great!

Here's the code so far:

  • # Processing
  • tip = meal_cost * 0.15
  • total = meal_cost + tip
  •  
  • # Output
  • print('-----------------')
  • print('Meal cost: ' + meal_cost)
  • print('Tip: ' + tip)
  • print('Total: ' + total)
  • ​​​​​​​
Adela
Adela

In the output, we've got three variables: meal_cost, tip, and total. We've worked out how to compute tip and total. How do we work out meal_cost?

Reflect

How should they work out meal_cost?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Georgina
Georgina

Hey guys! We don't work it out. Here's the I/O we want:

Output

meal_cost is an input. The user has to tell us what it is.

Adela
Adela

Yeah, that makes sense. I'll add some comments at the top... The program is:

  1. # Compute a 15% tip for a meal.
  2. # Written by the Scoobies, June 12, Year of the Dragon
  3.  
  4. # Input
  5. meal_cost = input('Meal cost? ')
  6.  
  7. # Processing
  8. tip = meal_cost * 0.15
  9. total = meal_cost + tip
  10.  
  11. # Output
  12. print('-----------------')
  13. print('Meal cost: ' + meal_cost)
  14. print('Tip: ' + tip)
  15. print('Total: ' + total)
  16. ​​​​​​​

We're done!

Good!

Except for one thing we'll talk about later.

Structure diagrams

The Scoobies could have started with a structure diagram (you saw one earlier). Here's an MT (empty) structure diagram for the IPO pattern:

Starting structure diagram

Let's add variables that link processing and output.

Adding variables linking processing with output

Ray
Ray

So processing sends tip and total to output. OK, but output needs meal cost as well. Doesn't processing send that, too?

That comes from input.

All the variables

meal_cost, the variable that comes from input, is used in both processing and output.

Adela
Adela

That structure diagram looks like the one we had for the name tag program:

Name tag Tip

Structure diagram

All the variables

Reflect

Fill this in: Programs with similar structure diagrams probably use the same _________.

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Ray
Ray

Pattern, maybe?

Right! Look under the surface of the code, to find the patterns. Programmers who think in patterns are more valuable, since they use the patterns to do hundreds of similar tasks.

Try the program

Here's the code again.

  1. # Compute a 15% tip for a meal.
  2. # Written by the scoobies, June 12, Year of the Dragon
  3.  
  4. # Input
  5. meal_cost = input('Meal cost? ')
  6.  
  7. # Processing
  8. tip = meal_cost * 0.15
  9. total = meal_cost + tip
  10.  
  11. # Output
  12. print('-----------------')
  13. print('Meal cost: ' + meal_cost)
  14. print('Tip: ' + tip)
  15. print('Total: ' + total)
Reflect

Run the code. What happens?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.

Type error

Ray
Ray

What the hell?

Data types

The error report tells you there's a problem with the line: tip = meal_cost * 0.15

To see what's going on, start the program in debug mode, and run the first line. (You'll need to type the meal cost in the console.) Here's what I got:

Debugging

Check out meal_cost. Its value is 60; that's what I typed. The variable Explorer (VE) tells you its type is str. That's the problem.

Remind we what a variable is.

Reflect

What's a variable?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Ethan
Ethan

It's a piece of computer memory with a name.

Right. Each variable has a data type. It's, er, the type of data that can go into the variable. Python has a bunch of data types, but let's just talk about float and string.

A float is a number that can have a decimal part, like 6.11, 44, and -123.311. Note that 44 can be a float. The number can has a decimal part, but doesn't have to.

A string is text. Actually, anything you can type on the keyboard, like 'кози круті'.

Operators

Operators and types are related. An operator is something like + that combines values.

Check this out.

  1. person1 = 'Sheena'
  2. person2 = 'Trid'
  3. print(person1 + person2)
  4. price1 = 10
  5. price2 = 20
  6. print(price1 + price2)
Reflect

Lines 3 and 6 both have the + operator. Do they do the same thing? If not, what's the difference?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Adela
Adela

Well, they kinda do the same thing, but not really. They both add. The + in line 3 puts two things together, one after the other, getting SheenaTrid. The + in line 6 sums two numbers.

Right.

peson1 and person2 are strings. Python sees that, and interprets + as append (also called concatenate), so it jams the strings together.

price1 and price2 are floats. Python interprets their + as 'the sum of.'

Ethan
Ethan

Oh, I get it. Python uses a different version of +, depending on the types of the data it's dealing with.

Right.

Remember what the * operator does?

Reflect

What does the * operator do? BTW, geeks sometimes call * splat.

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Georgina
Georgina

Multiply, like 2*3 is 6.

Correct.

Try this:

  • person1 = 'Sheena'
  • person2 = 'Trid'
  • print(person1 * person2)
  • ​​​​​​​
Reflect

What happens?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Ethan
Ethan

I got a type error, can't multiply. Makes sense, too. 'Sheena' times 'Trid' means... well, nothing. It's nonsense.

One more:

  • adults = '4'
  • kids = '3'
  • people = adults * kids
  • ​​​​​​​
Reflect

Try the program. Why doesn't it work?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Georgina
Georgina

Oh wow, this sucks. '4' and '3' have quotes, so they're strings, not floats.

You can't multiply strings, so an error.

Aye, that's it. A string is made up of characters we can type, like...

  • 'Paul Smith'
  • '221b Baker Street'
  • 'Собаки – это самое лучшее, что есть на свете.'

We can type digits on the keyboard, so '322' is a string, though 322 is not.

Ray
Ray

Wait. When it gets to the *, couldn't Python look at the '4' and the '3', and convert them to floats?

Yes, it could, and some programming languages do. PHP and VBA, for example. Python doesn't.

Run this.

  1. number1 = input('Please enter a number: ')
  2. number2 = input('Please enter another number: ')
  3. product = number1 * number2
  4. print('Their product is ' + product)
Reflect

What happened?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Ray
Ray

Another error.

OK, run the program again, but in debug mode. Step over the first two lines (Ctrl+F10), and enter a number in the console for each one. I typed 3 and 4, but use any numbers. Don't run the third line yet. (If you did, stop the program, and debug again.)

Here's what I got:

Input gives strings

Reflect

What do you notice about the variables that would cause the error you got?

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Georgina
Georgina

Oh, maaaan! They've got the str thing. They're strings, even though we entered numbers!

Right! input() always returns a string, no matter what the user types.

Earlier, Ray asked why Python didn't convert the values from strings to floats automatically. He's on the right track. If Python doesn't convert from strings to floats automatically, what can we do?

Ethan
Ethan

Oh! Can we convert the strings to floats ourselves?

Aye, that's the solution. Some new code:

  • number1 = float(input('Please enter a number: '))
  • number2 = float(input('Please enter another number: '))
  • product = number1 * number2
  • print('Their product is ' + product)
  • ​​

float() is a built-in Python function, like input() and print(). It takes whatever you give it, and makes a float out of it.

Here's one of those lines, with extra space sauce:

  • number1 = float( input('Please enter a number: ') )
  • ​​​​​​​

We wrapped input() inside float(). You'll see that a lot in Python code. The inner function runs first, and sends its data to the outer function. input() always return a string, which float() converts to a float.

Adela
Adela

Could you split the functions up?

Aye. For example:

  • user_input = input('Please enter a number: ')
  • ​​​​​​​number1 = float(user_input)

The name user_input explains what's happening. What the user types isn't number1 yet. It has to be converted.

Still, I would go with...

  • number1 = float(input('Please enter a number: '))
  • ​​​​​​​

... for simplicity.

Try it. Add the float()s, and see if the program works.

Printing, too

We have the same problem with print. Run this:

  1. print('Doggos are great!')
  2. print(2 + 3)
  3. print('Doggos are great! ' + 'Cats are OK, too.')
  4. total = 2 + 3
  5. print('Total: ' + total)

Lines 1 to 4 work fine. Line 5 crashes the program. Here's what I got:

  • Doggos are great! From line 1
  • 5 From line 2
  • Doggos are great! Cats are OK, too. From line 3
  • Line 4 doesn't output anything, and doesn't have any errors.
  • Traceback (most recent call last): From line 5
  •  
  •   File d:\documentz\python course\lessons\6 useful-calculators\2 tip\basic-tip-program py\type-conversion.py:5
  •     print('Total: ' + total)
  •  
  • TypeError: can only concatenate str (not "int") to str

Let's compare the +s.

The + in line 2 (2 + 3) adds a number to a number. No trubba.

The + in line 3 ('Doggos are great! ' + 'Cats are OK, too.') adds a string to a string. No problem.

The + in line 4 (2 + 3 again) adds a number to a number. Orright!

The + in line 5 ('Total: ' + total) tries to add a string and a number. Crashy crash!

The solution's easy:

  • print('Total: ' + str(total))

This tells Python to make a stringy version of total before the squoosh. total stays a number, though.

Adela
Adela

So float and str are kinda the reverse of each other.

float takes a string, and returns a number, like float(user_input).

str takes a number, and returns a string, like str(total).

Aye, that's it!

Tippy tip

Here's the tip program so far, with some issues:

  1. # Compute a 15% tip for a meal.
  2. # Written by the scoobies, June 12, Year of the Dragon
  3.  
  4. # Input
  5. meal_cost = input('Meal cost? ')
  6.  
  7. # Processing
  8. tip = meal_cost * 0.15
  9. total = meal_cost + tip
  10.  
  11. # Output
  12. print('-----------------')
  13. print('Meal cost: ' + meal_cost)
  14. print('Tip: ' + tip)
  15. print('Total: ' + total)
Reflect

Get the program working.

If you were logged in as a student, the lesson would pause here, and you'd be asked to type in a response. If you want to try that out, ask for an account on this site.
Ray
Ray

Got it!

  • meal_cost = float(input('Meal cost?'))
  • ...
  • print('Meal cost: ' + str(meal_cost))
  • print('Tip: ' + str(tip))
  • print('Total: ' + str(total))

Yay!

Summary

Reading a summary helps anchor that you just read in your memory.

  • Working backwards is often a good way to go.
  • Think about the structure of a program, before you write it.
  • Every variable has a data type, like string or float.
  • Data types affect what operators you can use on variables. E.g., you can't multiply strings.
  • There are type conversion functions, like float() and str().

Exercises

Remember

Exercise

Aussie Rules

Australian Rules is a type of football. You score points by getting the ball between posts at either end of the field:

Goal posts

If the ball goes between the center two posts, that's a goal, and is worth six points. If the ball goes between one of the center and outside posts, that's a behind, and is worth one point.

Write a Python program for computing the score, given the number of goals and behinds. Here's sample I/O:

  • How many goals? 8
  • How many behinds? 2
  • Score: 50

Include comments for the IPO pattern.

Upload a zip file of the project folder. The usual coding standards apply.

Exercise

Circles

Write a Python program to compute the circumference and area of a circle, from a radius input by the user. Make your I/O look like this:

  • Radius? 2.3
  •  
  • Circle
  • ======
  •  
  • Radius: 2.3
  • Diameter: 4.6
  • Cirumference 14.451313999999998
  • Area 16.619011099999998

Match the format exactly.

Include comments showing the pieces of the IPO pattern.

Upload a zip of your project folder. The usual programming standards apply.