Python Example A

Python Example A#

Let’s look at a Python example. In a previous lab, we wrote a program that took a temperature in Fahrenheit and converted it to Celsius.

What that program might have looked like:

# input temp
f = float(input("Enter a temperature in Fahrenheit: "))

# convert to celsius
c = (f -32) * 5/9

# show output
print(f"{f} degrees Fahrenheit is equal to {c} degrees celsius")
For more on f strings in Python: https://realpython.com/python-f-strings/

This isn’t a terribly long program to write out, but if we need to perform this conversion regularly, we might want to just write it out once and be able use that working code elsewhere in our program.

We can rewrite this program as a function that we can access elsewhere in our program.

# define function
def tempConvert():
  fahrenheit = float(input("Enter a temperature in Fahrenheit: ")) # get temperature
  celsius = (fahrenheit -32) * 5/9 # convert to celsius
  print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius} degrees celsius") # show output

Then, elsewhere in our program, we could call that function using its name.

# sample function call
tempConvert(32)

In this example, we passed the value 32 to the tempConvert function we created.