创建一个python程序,猜测用户的密码"?

时间:2018-01-31 20:59:04

标签: python python-3.x

我正在创建一个程序,要求您考虑来自0 to 100的数字。然后它会猜测它是否是50, lower than 50, or higher than 50。该程序将继续猜测不同的数字,直到它猜出正确的数字。

如果用户没有输入yeslowerhigher,那么输出应该是"我不明白&#34 ; 。我的代码的问题是它获得了无限循环。我假设有一个循环,我需要在用户说出“#34;是"

这是我到目前为止所做的事情(我是一名新手程序员,所以我很抱歉,如果这没有意义,或者我的代码真的很糟糕!):

print('Hello.')
print('Pick a secret number between 0 and 100.')
print('Is your secret number 50')
low = 0
high = 101
guess = 50
a = input('Enter yes/higher/lower:\n')
while True:
    if a == 'yes':
        print('Great!')
        break
    elif a == 'lower':
        high = guess
        guess1 = (guess-low)//2+low
        print('Next is', guess1)
        print('Is your secret number', guess1)
    elif a == 'higher':
        low = guess
        guess1 = (high-guess)//2+guess
        print('Next is', guess1)
        print('Is your secret number', guess1)
    elif a != 'yes' or 'higher' or 'lower':
        print('I did not understand')

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,看看这是否是您程序的预期行为。

print('Hello.')
print('Pick a secret number between 0 and 100.')
print('Is your secret number 50')
low = 0
high = 100

while True:
    guess = int((low+high)/2)
    print('Is your secret number', guess)
    a = input('Enter yes/higher/lower:\n')
    if a == 'yes':
      print('Great!')
      break
    elif a == 'lower':
      high = guess-1
    elif a == 'higher':
      low = guess+1
    else:
        print('I did not understand')

算法如下:

  1. 您可以通过获取middlelow值的high来猜测。所以你用guess = int((high+low)/2)
  2. 做到了
  3. 如果用户的号码大于guess,则您将low值更改为guess+1。如果用户的号码低于guess,则您将high值更改为guess-1
  4. 重复此过程,直到最终获得用户的号码。