mardi 7 juin 2016

While loop / if statement combined with user input PYTHON

The user should be able to choose between having a random (between 0.2 and 0.5) disease factor, and inputting their own. I tried to use a while loop to set it off, and then have an if statement for the Y or N choice. However once the disease value has been set, it doesn't appeal to the original Y or N disease factor criteria, so loops back again and asks whether the user wants to input their own disease factor or not. I can see why it is going wrong, but I'm not sure what to put instead.

Additionally when the user selects "N", there is an error saying

while random_disease < 0.2 or random_disease > 0.5 :
TypeError: unorderable types: str() < float()

I don't understand why this is coming up, as I set random_disease originally as a number, and it's inside the loop regarding numbers, not Y or N.

Sorry about the pre-set indentation, it's taken straight from my current code which has lots of loops, functions etc in it. Any help?

# Random disease factor #
        random_disease = 12
        while random_disease != "Y" or random_disease != "N":
            random_disease = input("Do you want a random disease factor? Enter Y if you do, or N if you want to select it yourself. Remember this will be between 0.2 and 0.5")
            if random_disease == "Y":
                random_disease = random.uniform(0.2, 0.5)
            elif random_disease == "N":
                while random_disease < 0.2 or random_disease > 0.5 :
                    try:
                        random_disease = float(input("What is your selected disease factor? Remember this should be between 0.2 and 0.5 : "))
                    except ValueError as ex:
                        print(ex)
            print("Your disease is ", random_disease)

Aucun commentaire:

Enregistrer un commentaire