如何创建一个随机的 4 位数字并将其存储为变量

Tec*_*eck 0 python windows random

我正在使用 python 2.7.10 进行猜 4 位数字游戏。但是我找不到如何随机生成一个 4 位数字并将其存储为变量。数字必须介于 1111 和 9999 之间。困难的部分是,我想将其存储为变量,而不是将其打印出来供玩家查看。

如果你愿意,我会在完成后发布代码。

代码终于来了!

import random
number = random.randint(1111,9999)
tryagain = 'yes'
print ('hello! ')
print ('------------------------------------------------------------- ')
print ('Try and guess the 4 digit number in the least number of tries ')
print ('------------------------------------------------------------- ')
while tryagain == 'yes':
    lowoutput = None
    highoutput = None
    guess = None
    guess = input('Guess: ')
    if guess == number:
        print ('Correct! ')
        correctoutput str(raw_input(Enter 'exit' to exit: "))
        If correctoutput == 'exit':
            print 'Goodbye'
            exit()
        else:
            print 'invalid input'
    elif guess > number:
        print 'Your answer is too high'
        highoutput = str(raw_input("Try again? 'Y'/'N'))
        if highoutput == 'n':
            tryagain = 'n'
        elif highoutput == 'y'
            try again = 'yes'
        else:
            print 'invalid input'
    else:
        print 'Your answer is too low' 
        lowoutput = str(raw_input("Try again 'y'/'n'"))
        if lowoutput == 'n':
            try again = 'n'
        elif lowoutput == 'y'
            tryagain = 'yes'
        else:
            print 'invalid input'
print 'too bad, the right answer was: '
print (number)
exit()
Run Code Online (Sandbox Code Playgroud)

这应该有效。可能有一些错误,因为我在平板电脑上写了这个。所有改进都将被接受

Pyn*_*hia 5

尝试

import random
r = random.randint(1111,9999)
print "%04d" % r
Run Code Online (Sandbox Code Playgroud)

或者

print '{0:04d}'.format(r)
Run Code Online (Sandbox Code Playgroud)