Data Types: int and float (Level 3)

Remember that the input command reads strings. You have to convert strings to integers (whole numbers) or floats (decimals) if you want to use them to perform calculations.

Examples

1) Write a program that prompts the user to enter the length and width of a rectangle. Output the area of the rectangle

length = int(input("Enter the length of the rectangle"))
width = int(input("Enter the width of the rectangle"))
area = length*width
print("The rectangle has an area of " + str(area))

2) To convert miles to kilometers, you multiply the number of miles by 1.609. Write a program that prompts the user to enter the number of miles, and then output the answer converted to kilometers

Note the use of float as a user may input 12.5 miles, for example.

miles = float(input("Enter the number of miles"))
kilometers = miles * 1.609
print(str(miles) + " miles = " + str(kilometers) + " kilometers")

Exercise

  1. Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
  2. At the time of writing, the exchange rate for pounds to euros is 1 GBP = 1.19984 Euros. Write a program that will convert pounds to euros. Test it using the data GBP4.50 (Don’t forget to convert the input to a float!)
  3. Now write a program to convert euros to pounds. Test it using the data Euro 7.40
  4. Prompt the user to input a number. Output the square of that number.
  5. Prompt the user to input two numbers. Output the average of those two numbers.
  6. Prompt the user to input three numbers. Output the sum and the average of those three numbers.
  7. Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle

Extension: Fahrenheit to Celsius

Here are the formulas to convert from Fahrenheit to Celsius and back again.

°F to °C Deduct 32, then multiply by 5, then divide by 9 °C to °F Multiply by 9, then divide by 5, then add 32

  1. Now write a program to convert Celsius to Fahrenheit. Use the test data to check your program.
  2. Write a program to convert Fahrenheit to Celsius. Again, use the test data below to check your program.

Test data

C F
0 32
12 54
100 212
-3 27
-18 0
-23 -10

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.