我正在创建一个简单的计算器程序,并希望缩短在检查输入变量时我必须做的输入量。 有没有办法分配我的IF / ELSE语句并调用它们以节省时间和打字?我必须写出很多变量。 我还没有很多关于python的知识,所以请尽量使它变得简单易懂。
loop = 1
while loop == 1:
a1 = input("Add this number of apples: ")
if a1.isdigit():
a1 = int(a1)
else:
print("You cannot add a letter, changed to 0.")
a1 = 0
loop = 1
if a1 < 0:
print(user_name + ", You cannot choose a negative number!")
loop = 1
else:
print("")
print(a1, "apples +", a2, "apples =", a1 + a2, "total apples.")
print("")
loop = 1
a2 = input("to this number of apples: ")
if a2.isdigit():
a2 = int(a2)
else:
print("You cannot add a letter, changed to 0.")
a2 = 0
loop = 1
if a2 < 0:
print(user_name + ", You cannot choose a negative number!")
loop = 1
else:
print("")
print(a1, "apples +", a2, "apples =", a1 + a2, "total apples.")
print("")
loop = 1
答案 0 :(得分:0)
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
print "Please Enter An Integer"
def get_conditional_int(prompt,condition,error):
while True:
a = get_int(prompt)
if condition(a):
return a
print error
a = get_conditional_int("Enter The Number Of Apples:",lambda x:x>0,"Enter A Positive Value!")
print a + 54
作为您现有代码的旁白,您永远不会得到负面的
print "-5".isdigit()