Reputation: 19
Here is my code. I am just starting to learn Python. I am trying to generate a random number and guess it. If the answer is 7, then my program will print "lucky". If not, then "unlucky". I try to run my simple code many times. Every time I get "unlucky". Is there anybody who knows whether the problem is in my algorithm or somewhere else. BTW, I really want to know how could I know specifically know what is the number randomly generated in python? I just wonder if the same number, that is being generated every time, is the same one or not.
from random import randint
z = input("What's the max number you want me to guess?")
choice = f"randint(1,{z})"
if choice == 7:
print("lucky")
else:
print("unlucky")
Upvotes: 0
Views: 1970
Reputation: 1972
If you want to check whether the same number is being guessed by random, just use print
, to check it. Here:
from random import *
z = int(input("What's the max number you want me to guess?"))
choice = randint(1,z)
print("The number that I guessed:",choice)
if choice == z:
print("I gussed it! I got lucky.")
else:
print("I couldn't guess it, I got unlucky.")
Upvotes: 0
Reputation: 365807
The reason you're getting unlucky every time has nothing to do with randomness.
Try running your code in the debugger, or adding a print(choice)
, to what what you're getting.
If you enter, say, 10
, then choice
is the string "randint(1,'10')"
. That string is never going to be equal to the number 7
.
To make this work, you need to change two things:
randint
, instead of making a string that looks like the source code to call it.10
, not a string, like '10'
.So:
choice = randint(1, int(z))
Once you fix this, the random numbers will be random. Technically, they're created by a PRNG (pseudo random number generator), a fancy algorithm that takes a bunch of state information and spits out a sequence of numbers that look random, but are actually predictable from that state. But, as explained under seed
, by default, Python seeds that generator with os.urrandom
(which, on most platforms, is another PRNG, but is itself seeded by whatever actual random data is available).
If you want the sequence to be repeatable, for testing, you can call the seed
function manually. For example, this program:
from random import randint, seed
seed(42)
z = input("What's the max number you want me to guess?")
choice = randint(1, int(z))
print(choice)
… will give you 2
every time you ask for a random number between 1 and 10.
Upvotes: 1