Python 我的代码有问题一个变量不能与
当我尝试运行代码的这一部分时,它会不断显示一条错误消息,如下所示:while puissance>100或puissance<0: TypeError:“str”和“int”实例之间不支持“>”输入函数返回字符串str。要将其转换为int,需要使用int函数:Python 我的代码有问题一个变量不能与,python,string,variables,while-loop,typeerror,Python,String,Variables,While Loop,Typeerror,当我尝试运行代码的这一部分时,它会不断显示一条错误消息,如下所示:while puissance>100或puissance”输入函数返回字符串str。要将其转换为int,需要使用int函数: power=input("How much power would you like to have?(power goes from 1 to a 100)") while power > 100 or power < 0: if power < 100 or power &g
power=input("How much power would you like to have?(power goes from 1 to a 100)")
while power > 100 or power < 0:
if power < 100 or power > 0:
break
else:
power=input("How much power would you like to have?")
请注意,如果用户输入的字符串不是可以解释为整数的字符串,int将引发ValueError
如果要重复提示用户直到用户提供有效值,请使用带有try/except的循环:
input返回一个字符串,因此需要power=intinputblah
power = int(input("How much power would you like to have?(power goes from 1 to a 100)"))
while True:
try:
power = int(input(
"How much power would you like to have? (power goes from 1 to 100)"
)) # raises ValueError if not an int
assert 1 <= power <= 100 # raises AssertionError if not in range
except (AssertionError, ValueError):
continue # prompt again
else:
break # continue on with this power value