Skip to content

Choice Function: Replaced sample with choice for selecting a single code #154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Refactor temperature conversion program for improved user experience …
…and code readability
  • Loading branch information
Soyvor committed Apr 11, 2024
commit 6bb24af9b22112d05b833561ce6b341b7934833c
53 changes: 27 additions & 26 deletions TempConversion.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
# Temperature Conversion Program

def menu():
print("\n1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")
choice = int(input("Enter a choice: "))
return choice

def toCelsius(f):
return int((f - 32) / 1.8)
print("\n1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")
choice = input("Enter a choice: ").strip() # Added .strip() to remove leading/trailing whitespace
return choice

def to_celsius(f):
return (f - 32) / 1.8 # Removed unnecessary conversion to int

def to_fahrenheit(c):
return c * 1.8 + 32 # Removed unnecessary conversion to int

def toFahrenheit(c):
return int(c * 1.8 + 32)

def main():
choice = menu()
while choice != 3:
if choice == 1:
c = eval(input("Enter degrees Celsius: "))
print(str(c) + "C = " + str(toFahrenheit(c)) + "F")
elif choice == 2:
f = eval(input("Enter degrees Fahrenheit: "))
print(str(f) + "F = " + str(toCelsius(f)) + "C")
else:
print("Invalid choice.")
choice = menu()

main()
choice = menu()
while choice != '3': # Changed 3 to '3' to compare with string
if choice == '1':
c = float(input("Enter degrees Celsius: ")) # Changed eval to float for safer input parsing
fahrenheit = to_fahrenheit(c)
print(f"{c}C = {fahrenheit}F") # Using f-strings for cleaner output formatting
elif choice == '2':
f = float(input("Enter degrees Fahrenheit: ")) # Changed eval to float for safer input parsing
celsius = to_celsius(f)
print(f"{f}F = {celsius}C") # Using f-strings for cleaner output formatting
else:
print("Invalid choice.")
choice = menu()

if __name__ == "__main__": # Added guard to ensure main() runs only if the script is executed directly
main()