2016-11-26 95 views
0

我正在处理Python脚本,用户必须猜测脚本选择的随机数。这是我的代码:在Python脚本中更改随机数

import random 
while True: 
    number = random.randint(1, 3) 
    print("Can you guess the right number?") 
    antwoord = input("Enter a number between 1 and 3: ") 
    if antwoord == number: 
     print ("Dang, that's the correct number!") 
     print (" ") 
    else: 
     print ("Not the same!") 
     print ("The correct answer is:") 
     print (number) 

    while True: 
     answer = input('Try again? (y/n): ') 
     print (" ") 
     if answer in ('y', 'n'): 
      break 
     print("You can only answer with y or n!") 
    if answer == 'y': 
     continue 
    else: 
     print("Better next time!") 
     break 

它的工作原理...排序的...我想它和整个这个传来: User enters 2, it says it's incorrect, but then displays the same number!

我有,我每次打电话变量“的感觉号码“,它会再次更改随机数。我该如何强制脚本保存在开始时选取的随机数字,而不是在脚本中不断更改它?

+0

为什么不在外面指定随机数呢? –

+0

这是Python 2还是3?如果是python 3,则需要评估输入(使用''''eval(input())''') - '''“2”'''与'''2'''不一样 – Lolgast

+0

如果是这种情况@AhsanulHaque,你怎么解释它说这是错误的号码,但后来显示相同​​的号码,并说这是正确的号码被选中? – ErikB26

回答

0

据我所知,你想在每个循环步骤中选择一个新的随机整数。 我猜你正在使用python 3,所以input返回一个字符串。既然你不能在一个字符串和一个int之间进行比较,你需要首先将输入字符串转换为一个int。

import random 
while True: 
    number = random.randint(1, 3) 
    print("Can you guess the right number?") 
    antwoord = input("Enter a number between 1 and 3: ") 
    try: 
     antwoord = int(antwoord) 
    except: 
     print ("You need to type in a number") 
    if antwoord == number: 
     print ("Dang, that's the correct number!") 
     print (" ") 
    else: 
     print ("Not the same!") 
     print ("The correct answer is:") 
     print (number) 

    while True: 
     answer = input('Try again? (y/n): ') 
     print (" ") 
     if answer in ('y', 'n'): 
      break 
     print("You can only answer with y or n!") 
    if answer == 'y': 
     continue 
    else: 
     print("Better next time!") 
     break 
+0

谢谢!这是解决方案! – ErikB26