[Tutor] how come this doesnt work

Dave Angel davea at ieee.org
Sat Jan 15 05:39:35 CET 2011


On 01/-10/-28163 02:59 PM, walter weston wrote:
>
> I generate a random number(supposedly a password, in my case its just a long floating point lol),I want the user to reinput that number and I want to print a string if the number entered is correct. so if m==num(num is the number generated and m is the variable which stores the input ) then I want to print 'you entered correctly, proceed'.
>
> here is my code..
>
> import random
> for x in range(0,1):
>      num = random.random()
>      print (num)
>      m=input('input pass:')
>      if m==num:
>          print('you entered correctly, proceed')
>
> It's very noobish dont give me complex replys, and dont be to rude or laugh at me, as I am a beginner In the programming domain.
>   		 	   		

You left out a few details, like what version of Python you're using. 
However, i suspect you're using version 3.x, and will respond accordingly.

input() returns a string, while random.random() returns a float.  So 
they'll never be equal.

Because floats are stored in binary floating point, you run a risk in 
comparing them in any case.  So rather than converting the user's input 
to float, I'd suggest converting the random value to a string.  And if 
you do it before printing it, your user should be able to get an exact 
match every time.

Just change the num assignment to:

     num = str(random.random())

DaveA


More information about the Tutor mailing list