exercises

adder

Make a program that adds two numbers together:

Enter a number: 665
Enter another number: 1
665 plus 1 is 666

Show solution

a = input('Enter a number: ')
b = input('Enter another number: ')
print(a, 'plus', b, 'is', a + b)


tip calculator

Make a tip calculator:

>>> %Run tip.py
Enter the cost of your meal: 10
Enter the tip percentage: 15
The tip amount is 1.5
The total cost is 11.5
>>> %Run tip.py
Enter the cost of your meal: 6.66
Enter the tip percentage: 42
The tip amount is 2.7972
The total cost is 9.4572

For the first line of your program, use this:

cost = float('Enter the cost of your meal: ')

float is like int, but it will allow you to type decimal numbers instead of just integers. If you used int instead of float, the program would crash in the second example.

Show solution

cost = float(input('Enter the cost of your meal: '))
tip = int(input('Enter the tip percentage: '))
tip_percent = tip / 100
tip_amount = cost * tip_percent
total_cost = cost + tip_amount
print("The tip amount is", tip_amount)
print("The total cost is", total_cost)


what if

Pretend you’re taking CS 101 at Wossamotta University. During the semester there are two midterm exams and a final exam. Your grade breakdown is:

  • 25% – midterm 1 score
  • 25% – midterm 2 score
  • 50% – final exam score

You got 85% and 95% on the two midterms, respectively. So if you got 75% on the final, your grade would be 0.25 * 85 + 0.25 * 95 + 0.5 * 75 = 82.5%.

Now write the following program:

Enter a final exam score: 87
If you get 87 percent on the final exam, your grade will be 88.5 percent.

Show solution

final = int(input("Enter a final exam score: "))
midterm1 = 85
midterm2 = 95
grade = 0.25 * midterm1 + 0.25 * midterm2 + 0.5 * final
print("If you get", final,
      "percent on the final exam, your grade will be",
      grade, "percent.")


previous: number input next: booleans