How do I fix this boolean expression?

enter image description here

Im told that I need to define my h variable but I am not sure how to do that.

1 answer

  • answered 2019-09-15 00:51 gelonida

    I assume above code is python3 code.

    The result of input() is a string and if the user followed the instructions it will be "True" or "False", though it could be any other string if the user made a typo.

    So you have to decide how to handle any invalid answer like "Tru" or "Fasle" or even just nonsense text.

    Would you like to prompt until the user enters a valid text or treat anything except "True" as False?

    Line 11 determins the boolean value of the input string and will be True for any text, that is not an empty string. Then as the result is not assigned to anything the calculated value will be discarded.

    Effectively line 11 is not changing the value of h from str to a bool.

    If you assume, the user who entered the input text will not make an error, then you could just write following:

        h = h == "True"  # determine the boolean expression h == "True" ans save the result in h
    

    Which is a shorter form of

        if h == "True":
            h = True
        else:
            h = False
    

    Also instead of writing if h == True it is more common to just see if h though both will be working

    Instead of if h == False you will see mostly if not h

    If you give more details about how you want to handle invalid input, then I might advise of how to handle this.