0

okay so I am trying to see if a number is greater than 1 less than 0 or equal to nothing then to exit. here is what I have so far.

def main():
    print("This program illustrates a chaotic function")
    x = raw_input("Enter a number between 0 and 1: ")
    if x == "" or x < 0 or x > 1:
        print("bad person")
        exit()
    else:
        x = eval(x)
        for i in range(10):
            x = 3.9 * x * (1-x)
            print(x)
main()
raw_input()

my code keeps printing bad person when I type in 0.5 even though that is greater that 0 and less than 1. I feel like this is some stupid error but i dont know. Any help would be great. Thanks

MathMXC
  • 319
  • 1
  • 3
  • 14

2 Answers2

1

Probably the cause of the error is that you cannot compare strings (as returned by raw_input) with numbers in a meaningful way. So you should convert the input to a number - in this case you want a float:

x = float(raw_input("Enter a number between 0 and 1: "))

and then you don't need that line anymore:

x = eval(x)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1
val = None
while val is None or val < 0 or val > 1:
    try:
        val = float(raw_input("Enter a number between 0 and 1: \n"))
    except ValueError:
        print("You must enter a number between 0 and 1.")

for i in range(10):
    val = 3.9 * val * (1 - val)
    print(val)

This way you don't have to use exit(), it won't break the while loop until it gets a number between 0 and 1. It will also keep going incase the user enters a char or anything else.

lciamp
  • 675
  • 1
  • 9
  • 19