这是my other thread on 10 Green Bottles的后续行动。我现在想知道如何让我的输入只接受一些单词/数字。如果写入了错误的单词/数字,则会提示您再次键入。如果输入的单词匹配一个被接受的单词,它将传递并运行其余的代码。 代码:
def main():
num1=int(input('Pick a number between 10 and 30: '))
hue=str(input('Pick a colour; Red, Green, Blue: '))
numbers =[ 'no', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty', 'Twentyone', 'Twentytwo', 'Twentythree', 'Twentyfour', 'Twentyfive', 'Twentysix', 'Twentyseven', 'Twentyeight', 'Twentynine', 'Thirty' ]
text_one = hue +' bottle%s\nHanging on the wall'
text_two = "And if one " + hue + " bottle\nShould accidentally fall\nThere'll be"
text_three =' \n'
with open(numbers[num1] + ' ' + hue + ' Bottles.txt', 'w') as a:
for l in range(num1, 0, -1): #
a.write(numbers[l]+ ' ')
if l == 1:
a.write(text_one % '' +'\n')
else:
a.write(text_one % 's' +'\n')
a.write(numbers[l] + ' ')
if l == 1:
a.write(text_one % '' + '\n')
else:
a.write(text_one % 's' + '\n')
a.write(text_two + ' ')
a.write(numbers[l-1] + ' ')
if (l - 1) ==1 :
a.write(text_one % ''+'\n')
else:
a.write(text_one % 's'+'\n')
a.write('\n' + '\n')
if __name__ == '__main__':
main()
答案 0 :(得分:0)
简单while
:
while True:
try:
msg = int(input("Enter: "))
except ValueError:
print("Not Valid!")
continue
# do some validation like if msg.endswith('hi') and stuff like that ex:
if msg > 40 or msg < 10: # fail if greater than 40 and smaller than 10
print("Not Valid!")
continue
break