monsterlou 发表于 2019-12-23 17:27:30

在学习while循环语句时为什么不能按照下列逻辑呢?

本帖最后由 monsterlou 于 2019-12-23 17:32 编辑

print('Hello World')
temp = input('can you input the right number i\'m thinking: ')
guess = int(temp)
if guess == 8:
      print('Yes you\'re right!')
      print('we have no gift for you')
else:
      while guess != 8:
            temp = input('Take one more try: ')
            guess = int(temp)
            if guess < 8:
                print('Nope guess bigger one')
            else:
                print('maybe little one!')
print('Game Over')

新入门菜鸟,有诸多不理解的地方,请大神赐教这段代码有什么问题?
为什么结果是这样?
Hello World
can you input the right number i'm thinking: 9
Take one more try: 12
maybe little one!
Take one more try: 13
maybe little one!
Take one more try: 5
Nope guess bigger one
Take one more try: 4
Nope guess bigger one
Take one more try: 3
Nope guess bigger one
Take one more try: 3
Nope guess bigger one
Take one more try: 8
maybe little one!
Game Over

请指导
多谢

sunrise085 发表于 2019-12-23 17:37:47

本帖最后由 sunrise085 于 2019-12-23 17:42 编辑

因为你的程序逻辑不对啊。if else中没有判断guess等于8的情况啊。
temp = input('can you input the right number i\'m thinking: ')
guess = int(temp)
if guess == 8:
      print('Yes you\'re right!')
      print('we have no gift for you')
else:
      while guess != 8:
            temp = input('Take one more try: ')
            guess = int(temp)
            if guess < 8:
                print('Nope guess bigger one')
            elif guess > 8:
                print('maybe little one!')
            else:
                print('Yes you\'re right!')
                print('we have no gift for you')
print('Game Over')

若你认为进入while循环后就不该在判断guess等于8的情况,那么程序应该这样修改:
temp = input('can you input the right number i\'m thinking: ')
guess = int(temp)
if guess == 8:
      print('Yes you\'re right!')
      print('we have no gift for you')
else:
      while guess != 8:
            if guess < 8:
                print('Nope guess bigger one')
            else:
                print('maybe little one!')
            temp = input('Take one more try: ')
            guess = int(temp)
print('Game Over')

jackz007 发表于 2019-12-23 18:05:01

      while 本该是总览全局的角色,而在楼主的代码中却只能偏居一隅,实在是“桌子底下放风筝”啊!
print('Hello World')
guess = 0
while guess != 8:
    guess = int(input('can you input the right number i\'m thinking: '))
    if guess == 8:
      print('Yes you\'re right!')
      print('we have no gift for you')
    else:
      print('Take one more try: ')
      if guess < 8:
            print('Nope guess bigger one')
      else:
            print('maybe little one!')
print('Game Over')
页: [1]
查看完整版本: 在学习while循环语句时为什么不能按照下列逻辑呢?