FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

feat: add input validation to temperature conversion exercise by harininr · Pull Request #90 · realpython/python-basics-exercises · GitHub

Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (1) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,40 @@
# Solution to challenge


def get_numeric_input(prompt):
"""Prompt the user until a valid numeric input is entered."""
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a numeric value.")


def convert_cel_to_far(temp_cel):
"""Return the Celsius temperature temp_cel converted to Fahrenheit."""
temp_far = temp_cel * (9 / 5) + 32
return temp_far
return temp_cel * (9 / 5) + 32


def convert_far_to_cel(temp_far):
"""Return the Fahrenheit temperature temp_far converted to Celsius."""
temp_cel = (temp_far - 32) * (5 / 9)
return temp_cel
return (temp_far - 32) * (5 / 9)



# Prompt the user to input a Fahrenheit temperature.
temp_far = input("Enter a temperature in degrees F: ")
temp_far = get_numeric_input("Enter a temperature in degrees F: ")

# Convert the temperature to Celsius.
# Note that `temp_far` must be converted to a `float`
# since `input()` returns a string.
temp_cel = convert_far_to_cel(float(temp_far))
temp_cel = convert_far_to_cel(temp_far)

# Display the converted temperature
print(f"{temp_far} degrees F = {temp_cel:.2f} degrees C")

# You could also use `round()` instead of the formatting mini-language:
# print(f"{temp_far} degrees F = {round(temp_cel, 2)} degrees C"")

# Prompt the user to input a Celsius temperature.
temp_cel = input("\nEnter a temperature in degrees C: ")
temp_cel = get_numeric_input("\nEnter a temperature in degrees C: ")

# Convert the temperature to Fahrenheit.
temp_far = convert_cel_to_far(float(temp_cel))
temp_far = convert_cel_to_far(temp_cel)

# Display the converted temperature
print(f"{temp_cel} degrees C = {temp_far:.2f} degrees F")

Back | FazBrowse Home | New Git URL