Collection
Question 1
Write a Python program that converts miles to kilometers. The conversion formula is: 1 mile = 1.60934 kilometers. Use the following information to create your program:
- Initialize a variable
miles
with a value representing the number of miles to convert. - Create a variable
kilometers
and calculate its value by multiplyingmiles
with the conversion factor. - Print the original number of miles and the equivalent distance in kilometers using a formatted output.
- Write the code for the program that performs the miles to kilometers conversion using Python.
Sample Code
# Miles to Kilometers Converter
kilometers = 12.25
miles = 7.38
miles_to_kilometers = ###
kilometers_to_miles = ###
print(miles, "miles is", round(miles_to_kilometers, 2), "kilometers")
print(kilometers, "kilometers is", round(kilometers_to_miles, 2), "miles")
Question 2
Convert the following equation into code that calculates the straight line given the slope (m) and y-intercept (b):
- y = mx + b
Sample Code
# Calculate the straight line given the slope (m) and y-intercept (b)
m = 2.5
b = 1.8
x = 3.2
y = m * x + b
print("The value of y for x =",x,"is", y, ".")
Question 3
Write a Python program that calculates the area of a rectangle using the given length and width values. Print the calculated area using a formatted output.
Sample Code
# Calculate the area of a rectangle
length = 5.2
width = 3.7
area = length * width
print("The area of the rectangle is", area, ".")
Question 4
Create a Python function that calculates the square of a given number. Write the code to call the function with a specific number and print the result using a formatted output.
Sample Code
# Calculate the square of a number
x = 7
result = x**2
print("The square of",x,"is",result,".")
Question 5
Given the quadratic function $$y = ax^2 + bx + c$$ write a Python program that calculates the value of y for a given x. Use the provided values of a, b, c, and x. Print the calculated value of y using a formatted output.
Sample Code
# Calculate the value of y for a given quadratic function
a = 2
b = -5
c = 3
x = 4
y = a * x**2 + b * x + c
print("The value of y for x =", x, "is", y, ".")
Question 6
Write a Python program that calculates the circumference and area of a circle using the given radius. Print both the circumference and area using formatted output. $$\text{Circumference} = 2 \pi \times \text{radius}$$ $$ \text{Area} = \pi \times \text{radius}^2 $$
Note that you should use import math since we will use the value of $\pi$ in the code.
Sample Code
import math
# Calculate the circumference and area of a circle
radius = 2.5
circumference = 2 * math.pi * radius
area = math.pi * radius**2
print("The circumference of the circle is", circumference, ".")
print("The area of the circle is", area, ".")