验证输入和使用条件似乎继续循环

时间:2017-10-25 17:39:43

标签: python python-2.7 if-statement while-loop break

如下图所示,我为用户提供了一个消费积分的选项,我确保输入包含'是是否'。如果用户想要花点数,则提示他选择与<= 8的分配不同的数字,我确保输入是使用v的数字。如果用户不想花点.isdigit(),则只需将其分配到v

0.0

然而,虽然代码工作正常,但在while True: choice = raw_input('\nSpend points?') if choice.lower().strip() in "y yes n no".split(): while True: if choice.lower().strip() in "y yes".split(): c = raw_input('Enter Value 1-6: ') if c.isdigit() and int(c) <= 6: if choice.lower().strip() in "y yes".split(): if c == '1': v = 0.3 if c == '2': v = 0.25 if c == '3': v = 0.2 if c == '4': v = 0.1 if c == '5': v = 0.05 if c == '6': v = 0.75 break if choice.lower().strip() in "n no".split(): v = 0.0 break else: continue else: continue print v 似乎成功打印后,代码将继续循环回到“你想花点数吗?”

我认为问题在于我的v声明,但我不确定它应该去哪里。

2 个答案:

答案 0 :(得分:1)

value_map = {
    1: 0.3,
    2: 0.25,
    3: 0.2,
    4: 0.1,
    5: 0.05,
    6: 0.75,
}

# Prompt user to spend points until they quit
while True:
    answer = raw_input('Spend points? y(es) n(o) q(uit) ')
    answer = answer.strip().lower()
    if not answer:
        continue
    if answer in ('q', 'quit'):
        print('Quit')
        # Break out of outer loop
        break
    elif answer in ('y', 'yes'):
        # Prompt until a valid selection is made
        while True:
            selection = raw_input('Value in 1-6 ')
            if not selection.isdigit():
                print 'Please select a number in 1-6'
                continue
            selection = int(selection)
            if selection < 1:
                print 'Selection out of range (too low)'
                continue
            if selection > 6:
                print 'Selection out of range (too high)'
                continue
            # Break out of inner loop
            break
        value = value_map[selection]
    elif answer in ('n', 'no'):
        value = 0.0
    else:
        print 'Please select one of y, n, or q'
        continue
    print value

答案 1 :(得分:0)

你可以通过这样做来重写这个想法,并且当@Wyatt使用地图时,使用它也是一个好主意:

choice = raw_input('\nSpend points?')
v = 0.0
value_map = {
    1: 0.3,
    2: 0.25,
    3: 0.2,
    4: 0.1,
    5: 0.05,
    6: 0.75,
}
while not (choice.lower() in "y yes n no".split()):
  print("invalid input, valid input are 'y, yes, n, no'")
  choice = raw_input('\nSpend points?')

if choice.lower().strip() in "y yes".split():
    c = raw_input('Enter Value 1-6: ')
    while not(c.isdigit() and int(c) <= 6):
      print("please, enter a digit between 1 and 6")
      c = raw_input('Enter Value 1-6: ')

    v = value_map[int(c)]


print v