Increasing the Complexity of Basic Python Functions - Conditional Statements and GUI

First off, I finally included some very needed graphical changes. My previous posts had the code included as either a JPG or PNG, with no feature to make it interactive. This left a less than diserable result. Now the code should be shown neatly, and color coded by syntax. The code is embedded and useable by converting python to HTML. 

Temperature Evaluation Programs

Temperature Evaluation Programs

/\_/\ >^,^< _ / \ / (___)/

Step 1: Simple Conditional Statement Practice


'''
step 1, simple conditional statement practice
includes user input and variance in output based on inputs
'''

# define variable temp and range
def eval_temp(temp):
    message = "Normal"
    if temp > 99.8:
        message = "Fever"
    elif temp < 95.4:
        message = "Hypothermia"
    return message
    
# prompt user input, use float to allow decimal 
user_temp = float(input("Enter your temperature: "))

# pass user_temp to eval_temp to classify it
your_temp = eval_temp(user_temp)

# output based on temp range
if your_temp == "Normal":
    print("Your temperature is normal")
elif your_temp == "Fever":
    print("You have a Fever")
else: #if not fever or normal, then hypothermia when < 95.4
    print("You have Hypothermia")
    
Temperature Evaluation

This program demonstrates basic conditional statements with user input.It simply outputs one of three defined variable parameters based on user input. The python code above does not account for unexpected inputs such as letters, however I felt as though it would be important to include in the background as to not cause errors within Blogger.

The purpose of this first program, is to introduce conditional statements of 'if', 'elif', and 'else' for the logical categorization of 'Normal', 'Fever", and 'Hypothermia' based on predefined temperature ranges.

Result:

Step 2: More Complex Conditional Statements


'''
step 2, more complex conditional statement practice,
increasing complexity by including quit check functionality, normalized unit input, variable units,
temperature conversion logic, dynamic output based on unit and user input, error handling for units,
delays, and better input handling for common misspelling. 
'''
import time  # time module for intentional delay between outputs

# define variable temp and range
def eval_temp(temp, unit="F"):
    if unit == "C":
        temp = temp * 9/5 + 32  # Convert Celsius to Fahrenheit for evaluation
    message = "Normal"
    if temp > 99.8:
        message = "Fever"
    elif temp < 95.4:
        message = "Hypothermia"
    return message, temp

# define advice based on variables
def get_temp_advice(classification):
    advice = {
        "Normal": "Your temperature is normal.",
        "Fever": "You have a fever. Rest, stay hydrated, and consult a doctor if it is at or above 103\u00B0F or 40\u00B0C.",
        "Hypothermia": "If your temperature reaches below 95\u00B0F or 35\u00B0C, consult a doctor immediately."
    }
    return advice[classification]  # Use square brackets to access dictionary values

# function to convert Fahrenheit back to Celsius for display if needed
def convert_to_celsius(temp_f):
    return (temp_f - 32) * 5/9

# function to check if the user wants to quit
def check_quit(input_value):
    if input_value.strip().lower() == "quit":
        print("Goodbye.")
        exit()

# prompt user input, use float to allow decimal
def main():
    """main loop program"""
    print("Temperature evaluation program.")
    time.sleep(2)

    while True:
        try:
            # input temperature with quit check
            user_input = input("Enter your temperature (or type 'quit' to exit): ").strip()
            check_quit(user_input)
            user_temp = float(user_input)

            # input unit
            unit_input = input("Is this in Fahrenheit (F) or Celsius (C)? ").strip()
            check_quit(unit_input)
            unit = unit_input.lower()

            # normalize unit input to a single format
            if unit in ("f", "fahrenheit", "farenheit", "fahrenheight", "farenheight"):  # handle common misspellings
                unit = "F"
            elif unit in ("c", "celsius", "celcius", "celsuis"):
                unit = "C"
            else:
                print("Invalid unit. Please enter 'F' for Fahrenheit or 'C' for Celsius.")
                continue

            # pass user_temp to eval_temp to classify it
            classification, temp_f = eval_temp(user_temp, unit)

            # output based on temp range
            if unit == "C":
                temp_c = user_temp
                print(f"Your normalized temperature is {temp_c:.1f}\u00B0C.")
            else:
                temp_c = convert_to_celsius(temp_f)
                print(f"Your normalized temperature is {temp_f:.1f}\u00B0F ({temp_c:.1f}\u00B0C).")

            time.sleep(1)
            print(f"Classification: {classification}")
            time.sleep(1)
            print(get_temp_advice(classification))
            time.sleep(1)

            # continue/quit check
            again = input("Do you want to evaluate another temperature? (yes/no): ").strip().lower()
            check_quit(again)
            if again != "yes":
                print("Goodbye.")
                break

        except ValueError:
            print("Invalid input. Please enter a valid number for the temperature.")

if __name__ == "__main__":
    main()
    

This program evaluates your temperature with added complexity by including unit handling, conversion logic, and dynamic outputs. Disclaimer: handling unexpected errors for spelling, or foreseeable inputs such as including spaces before typing 'C' or 'F' allow for a more user-friendly program. This is a crucial step in creating good programs.

Rather than just entering 'C', or 'F', try spelling out Celsius or Fahrenheit or common misspellings of these words






Result:



  
  

  
  
  


	

Step 3: Applications and GUI


'''
step 3, incorporate a GUI as a desktop application. 
This step can not be run through blogger as 
it requires the user to have a python environment installed and 
running on the user's system and will not function in a browser.
'''

import tkinter as tk
from tkinter import messagebox

# func eval temp
def eval_temp(temp, unit="F"):
    if unit == "C":
        temp = temp * 9 / 5 + 32  # F to C conversion
    message = "Normal"
    if temp > 99.8:
        message = "Fever"
    elif temp < 95.4:
        message = "Hypothermia"
    return message, temp

# func F to C
def convert_to_celsius(temp_f):
    return (temp_f - 32) * 5 / 9

# func advice
def get_temp_advice(classification):
    advice = {
        "Normal": "Your temperature is normal.",
        "Fever": "You have a fever. Rest, stay hydrated, and consult a doctor if it is at or above 104\u00B0F or 40\u00B0C.",
        "Hypothermia": "If your temperature reaches below 95\u00B0F or 35\u00B0C, consult a doctor immediately."
    }
    return advice[classification]

# func handle temp eval
def evaluate_temperature(event=None):
    try:
        user_temp = float(entry_temp.get())  # temp input
        unit = unit_var.get()  # unit input
        
        # eval temp
        classification, temp_f = eval_temp(user_temp, unit)
        if unit == "C":
            temp_c = user_temp
            result = f"Your temperature is {temp_c:.1f}\u00B0C."
        else:
            temp_c = convert_to_celsius(temp_f)
            result = f"Your temperature is {temp_f:.1f}\u00B0F ({temp_c:.1f}\u00B0C)."
        
        # output label update
        result_label.config(text=result)
        classification_label.config(text=f"Classification: {classification}")
        advice_label.config(text=get_temp_advice(classification))

    except ValueError:
        messagebox.showerror("Invalid Input", "Did your cat walk on your keyboard?")

# main window
root = tk.Tk()
root.title("Cat's Temperature Evaluation")

"""
Section and button creation
"""

# input 
tk.Label(root, text="Enter your temperature:").grid(row=0, column=0, padx=10, pady=10)
entry_temp = tk.Entry(root)
entry_temp.grid(row=0, column=1, padx=10, pady=10)
entry_temp.bind("", evaluate_temperature)  # Bind the Enter key to the evaluate function

# unit 
tk.Label(root, text="Select unit:").grid(row=1, column=0, padx=10, pady=10)
unit_var = tk.StringVar(value="F")
tk.Radiobutton(root, text="Fahrenheit (F)", variable=unit_var, value="F").grid(row=1, column=1, sticky="w", padx=10, pady=5)
tk.Radiobutton(root, text="Celsius (C)", variable=unit_var, value="C").grid(row=2, column=1, sticky="w", padx=10, pady=5)

# enter 
enter_button = tk.Button(root, text="Enter", command=evaluate_temperature)
enter_button.grid(row=3, column=0, columnspan=2, pady=10)

# output
result_label = tk.Label(root, text="", wraplength=400, justify="center", fg="blue")
result_label.grid(row=4, column=0, columnspan=2, pady=10)

classification_label = tk.Label(root, text="", wraplength=400, justify="center", fg="green")
classification_label.grid(row=5, column=0, columnspan=2, pady=10)

advice_label = tk.Label(root, text="", wraplength=400, justify="center", fg="black")
advice_label.grid(row=6, column=0, columnspan=2, pady=10)

# GUI main loop
root.mainloop()

    
Temperature Evaluation

The final step includes more than what I can demonstrate through blogger. The GUI in blogger is pulled from the tkinter library, which requires the user to have an installed and running instance of python. The only visual change between this program and the last one is the <return> button and the addition of a selection box for Fahrenheit and Celsius which elminates one source of potential user error as compared to allowing the user to write in the box.

what started as a simple example in conditional statements, has now been expanded upon, becoming continuously more complex to teach systematic software development while introducing myself and the reader (you) to progressibely more advanced programming concepts. The GUI demonstrates event-driven programming that links user actions to specific functions. In terms of user compatibility, this is superior for ease of use. To compare the ease of use, in the previous examples I wrote the script in Jupyter, and then ran the program in anaconda_powershell which gave back a text-only output. The GUI removes this word-noise and uneccesary step by providing easy to use buttons and simple directions before providing the output in the same instance.





Result:


Click Here to download the script from GitHub. Here is an example of what the GUI looks like when run as a desktop application:

Comments

Popular Posts