我正在尝试完成我的任务,一直在挣扎。想法是选择报告类型A或T。从那里输入,一直输入整数,直到退出。退出后,它应打印出报告“ T”加在一起的整数总数;或对于报告“ A”,它应打印总数,以及输入的整数列表。
此刻我遇到的问题是报告“ T”,一旦我输入整数,什么也不会使其出错或退出。它一直不断地要求我输入另一个整数。然后从报告“ A”开始,我输入的每个整数都会出现“无效输入”。我敢肯定我的代码可能还有更多的问题,但目前无法解决。任何指针将不胜感激。谢谢
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an ingteger to add to the total or \"Q\" to quit: ")
if report.upper == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
while True:
if report.upper() in "A T":
adding_report(report)
else:
print ("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")
答案 0 :(得分:1)
in
运算符需要一个可能值的集合。使用
if report.upper() in ("A", "T")
或(更接近您的财产)
if report.upper() in "A T".split()
答案 1 :(得分:1)
您的第一个问题在这一行:
if report.upper == "A":
这总是计算为False
,因为report.upper
是一个函数对象,而不是一个值。您需要
if report.upper() == "A":
返回值。您也可以很好地重命名输入变量并将其值替换为所需的内部变量:
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
report = report.upper()
这样可以节省您每次访问该字母时打给upper
的麻烦和时间。
请仔细阅读您的代码以查找重复的项目和错别字;从长远来看,您会省去头痛-我从个人经验中知道。
答案 2 :(得分:0)
尝试一下
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an integer to add to the total or \"Q\" to quit: ")
#You used "report.upper" instead of "report.upper()"
if report.upper() == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
#You forgot ot add this : "items.append(user_number)"
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
break
#Add this for loop termination: "or 0 to quit: "
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\" Or 0 to quit: ")
while True:
#it should be this ""if report.upper() in "A" or "T":"" not this ""if report.upper() in "A T":""
if report.upper() in "A" or "T":
adding_report(report)
#The condition below terminates the program
elif report == '0':
break
else:
print("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")