[英]Why does my recursive function with if-elif statements return None?
[英]Does not execute if and elif statement in a recursive function that appends
我不明白为什么不执行带有append
的if
和elif
语句。 我将hht
和hat
变量转换为可以进行比较的变量。
a = {0: {'halbzeit_h_tore': '1', 'halbzeit_a_tore': '1'},
1: {'halbzeit_h_tore': '0', 'halbzeit_a_tore': '0'},
2: {'halbzeit_h_tore': '1', 'halbzeit_a_tore': '0'},
3: {}
}
played_games_of_the_day =[]
def check_1(**kwargs):
hht = kwargs['halbzeit_h_tore']
hat = kwargs["halbzeit_a_tore"]
c = 0
if hht == "-" and hat == "-":
played_games_of_the_day.append(0)
c += 1
check_1(a[c])
elif int(hht) == int and int(hat) == int :
c += 1
played_games_of_the_day.append(1)
check_1(a[c])
#if dict empty pass#
elif not bool(a[c]):
pass
if all(x==0 for x in played_games_of_the_day):
print("all zero")
elif all(x==1 for x in played_games_of_the_day):
print("all one")
check_1(**a[0])
print(played_games_of_the_day)
永远不要输入 if if hht == "-" and hat == "-":
因为正如您在字典中看到的那样,其中没有类似的值,并且它永远不会输入这个 elif elif int(hht) == int and int(hat) == int:
因为您正在将 integer 与变量类型进行比较,这将始终返回 False
为了正确处理这些值,我们需要考虑场景。
首先,在给定的代码中,字典中的值是str
类型。 一般来说,您可以使用isinstance
function 检查变量的类型。 让我们从一些例子开始:
my_dict = {'str_type': '1', 'int_type': 1, 'bad_str_type': 'I am not a number'}
def get_int_value(my_input):
if isinstance(my_input, int):
# It is already an integer
return my_input
elif isinstance(my_input, str):
# Needs to be converted
return int(my_input) # Crashes for bad strings
get_int_value(my_dict['str_type']) # returns int 1
get_int_value(my_dict['int_type']) # returns int 1
get_int_value(my_dict['bad_str_type']) # Raises ValueError
那么我们该如何处理崩溃。 我们可以在尝试输入数字之前检查输入值(Look Before You Leap,LBYL)或检测它何时失败并从中恢复(Easier to Ask Forgiveness than Permission,EAFP)。 选择取决于开发人员的偏好。
检查字符串中是否有数字的一种方法是使用my_input.isnumeric()
。 对于更复杂的要求,还有其他选项,例如正则表达式,但我离题了,因为它对于这种情况来说太多了。
使用 LBYL:
def get_int_value(my_input):
if isinstance(my_input, int):
# It is already an integer
return my_input
elif isinstance(my_input, str):
# Needs to be converted
# Negative numbers start with a '-'. isnumeric does not like it
if (my_input.startswith('-') and my_input[1:].isnumeric())
or my_input.isnumeric():
return int(my_input)
else:
return None # Or anything else that is appropriate.
get_int_value(my_dict['str_type']) # returns int 1
get_int_value(my_dict['int_type']) # returns int 1
get_int_value(my_dict['bad_str_type']) # returns None
使用 EAFP:
def get_int_value(my_input):
if isinstance(my_input, int):
# It is already an integer
return my_input
elif isinstance(my_input, str):
# Needs to be converted
try:
return int(my_input) # If it is int like there's no problem
except ValueError:
# It wasn't int like
return None # Or anything else that is appropriate.
get_int_value(my_dict['str_type']) # returns int 1
get_int_value(my_dict['int_type']) # returns int 1
get_int_value(my_dict['bad_str_type']) # returns None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.