所以我必须像这样进行输出:
Enter number of eggs: 19
1 dozen and 7 excess
相反,它显示如下:
Enter number of eggs: 19
1 dozen
它没有显示多余的
我尝试了以下代码:
eggs = int(input("Enter amount of eggs: "))
if eggs >= 1:
dozens = eggs // 12
excess = eggs % 12
print ("dozens eggs {0}".format(dozens))
print ("excess eggs {0}".format(excess))
else:
print('Invalid Input')
但是我的教授要求我提供准确的输出
eggs = int(input("Enter amount of eggs: "))
if eggs >= 1:
dozens = eggs // 12
excess = eggs % 12
print ("dozens eggs {0} ".format(dozens))
elif eggs >= 1 == 0:
print("{0} dozen and {1} excess".format(dozens, excess))
else:
eggs = 0
print("{0} excess".format(excess))
这是当前代码
我希望输出显示为:1 dozen and 7 excess
。但只显示一打
答案 0 :(得分:1)
您是否尝试过运行第二段代码?它应该告诉您语法错误。第9行:“ elif”必须跟在“ if”之后。不能在代码块的开头。
并且,“鸡蛋> = 1 == 0”将始终为False。为了使它为真,它必须满足“蛋> = 1和1 == 0”。 (我建议在代码中使用“和”,这会更清楚,尤其是对于初学者。)
我似乎不太明白“ elif”中的要点。 “ if”和“ else”似乎说明了所有可能的情况。鸡蛋将大于0或为0。0是一种特殊情况,因为它不允许除法。 (假设输入为负,则使用“小蛋<0”)。
我认为以下代码应该有效(对您的代码进行最少的更改)。 eggs = int(input(“输入鸡蛋数量:”))
if eggs >= 1:
dozens = eggs // 12
excess = eggs % 12
print ("{0} dozen eggs and {1} excess".format(dozens, excess))
else:
excess = 0
print("{0} excess".format(excess))
以下是我要写的,供您考虑(我有点完美主义者):
eggs = int(input("Enter amount of eggs: "))
if eggs > 0:
dozens = eggs // 12
excess = eggs % 12
if dozens == 0:
print(excess, "excess")
elif excess == 0:
print(dozens, "dozen eggs")
else:
print ("{} dozen eggs and {} excess".format(dozens, excess))
elif eggs < 0:
print("Amount can't be negative.")
else:
print("0 excess")