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

时间:2015-07-23 14:09:35

标签: 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()

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

1 个答案:

答案 0 :(得分:4)

尝试

import random
r = random.randint(1111,9999)
print "%04d" % r

print '{0:04d}'.format(r)