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

2024-10-05 13:17:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Python2.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()

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


Tags: thenonenumberinputifexitelseyes

热门问题