python - 在嵌套循环中返回 2 步
问题描述
def get_user_choice():
global user_choice
''' 3users give their numbers to be validated'''
for i in range(1, 4):
choices = []
** choices = input("User {}, please enter 5 numbers separated by ',' :".format(i))
nums = choices.split(',')
while True:
if len(nums) != 5:
print(" Wrong choice,You have to enter 5 numbers separated by ','")
break
for nr in nums:
if nr.isdigit():
if int(nr) < 1 or int(nr) > 25:
print(" Wrong! Enter 5 Numbers between 1 and 25")
continue
else:
print(nr + " is not a number, try again")
continue
# How can i go back to ** from here????
解决方案
此代码更正了请求号码的逻辑并返回所选号码。
def get_user_choice():
''' 3users give their numbers to be validated'''
#global user_choice--didn't understand why you needed a global user_choice so commented out for now
user_choices = []
for i in range(1, 4):
while True:
choices = input("User {}, please enter 5 numbers separated by ',' :".format(i))
nums = choices.split(',')
if len(nums) != 5:
print(" Wrong choice,You have to enter 5 numbers separated by ','")
else:
for nr in nums:
if nr.isdigit():
if int(nr) < 1 or int(nr) > 25:
print(" Wrong! Enter 5 Numbers between 1 and 25")
break
else:
print(nr + " is not a number, try again")
break
else:
user_choices.append(nums)
break
return user_choices
# Get user choices
choices = get_user_choice()
上述代码的更简洁版本
def get_user_choice():
''' 3users give their numbers to be validated'''
invalid_numbers = lambda numbers: list(filter(lambda y: not y.isdigit(), numbers))
invalid_range = lambda numbers: list(filter(lambda y: not (1 <= int(y) <= 25), numbers))
user_choices = []
for i in range(1, 4):
while True:
choices = input("User {}, please enter 5 numbers separated by ',' :".format(i))
nums = choices.split(',')
if len(nums) != 5:
print(" Wrong choice, You have to enter 5 numbers separated by ','")
continue
p = invalid_numbers(nums)
if p:
print(*p,' are not numbers. Enter 5 numbers separaterd by "," ')
continue
p = invalid_range(nums)
if p:
print(*p, ' are out of range. Enter 5 numbers between 1 and 25')
continue
## uncomment if you wanted the number rather than strings
# nums = list(map(int, nums))
user_choices.append(nums)
break
return user_choices
choices = get_user_choice()
推荐阅读
- java - 我的 MacOS 应用程序弹出一个 java 图标
- asp.net-mvc - Kendo DateTimePicker 未将更改的值传递给控制器 ASP MVC
- sublimetext3 - 如何在片段中使用崇高的文本变量?
- c# - 调试模式错误
- kendo-grid - Kendo Grid - 根据列单元格数据值呈现自定义 HTML
- spring - Thymeleaf 安全方言 - hasPermission()
- c++ - Eigen 中的断言失败,C++
- javascript - JavaScript postMessage 和多个可传输对象
- c++ - 带有类型参数的模板模板参数?
- build - Flatpak - 打包二进制文件