【问题标题】:Python variable increment while-loopPython变量递增while循环
【发布时间】:2012-12-23 13:00:28
【问题描述】:

如果用户猜对了数字,我正在尝试使变量number 增加!如果被其他用户猜到,则继续增加增加的值。但似乎我的syntax 是错误的。所以我真的需要你的帮助。下面是我的代码:

#!/usr/bin/python
# Filename: while.py
number = 23
running = True

while running:
    guess = int(raw_input('Enter an integer : '))

    if guess == number:
        print 'Congratulations, you guessed it. The number is now increase'
        number += 1 # Increase this so the next user won't know it!
        running = False # this causes the while loop to stop
    elif guess < number:
        print 'No, it is a little higher than that.'
    else:
        print 'No, it is a little lower than that.'
else:
    print 'The while loop is over.'
    # Do anything else you want to do here
print 'Done'

【问题讨论】:

  • syntax error 你的意思是semantic error 这里?
  • 我看不出你的语法有什么问题......也许你想在猜到数字后继续循环?

标签: python variables loops numbers while-loop


【解决方案1】:

你可以在没有“运行”变量的情况下做到这一点,它不是必需的

#!/usr/bin/python
# Filename: while.py
number = 23
import sys

try:
    while True:
        guess = int(raw_input('Enter an integer : '))
        if guess == number:
            print('Congratulations, you guessed it. The number is now increase')
            number += 1 # Increase this so the next user won't know it!
        elif guess < number:
            print('No, it is a little higher than that.')
        else:
            print('No, it is a little lower than that.')
except ValueError:
    print('Please write number')
except KeyboardInterrupt:
    sys.exit("Ok, you're finished with your game")

【讨论】:

    【解决方案2】:
    #!/usr/bin/python
    # Filename: while.py
    number = 23
    running = True
    
    while running:
        guess = int(raw_input('Enter an integer : '))
    
        if guess == number:
            print 'Congratulations, you guessed it. The number is now increase'
            number += 1 # Increase this so the next user won't know it!
            running = False # this causes the while loop to stop
        elif guess < number:
            print 'No, it is a little higher than that.'
        else:
            print 'No, it is a little lower than that.'
    
    # Do anything else you want to do here
    print 'Done'
    

    【讨论】:

    • 在python中没有else if这样的东西;两个else都不是顺序
    猜你喜欢
    • 2015-10-10
    • 2020-01-21
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多