新手:对于范围内的 i 不递增

我正在尝试为课堂做作业,但它比需要的要困难得多,但我这样做是为了学习。

任何人都可以看到我的代码有问题吗?

我做了一些简单的搜索并尝试了一些修复,但我一定错过了一些基本的东西。

另外,我似乎无法将我的“新”列表中的所有项目相加。环顾四周后我仍然无法弄清楚这一点。正如主题所说,我对此很陌生,因此非常感谢任何帮助。

# define variables

new = []

items = float()

tax = float()

final = float()

subtotal = float()


# welcome and set rules of entering numbers

print("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")


# gathering input for items

for _ in range(5):

    _ += 1

    # define condition to continue gathering input

    test = True

    while test:  # test1 will verify integer or float entered for item1

        items = input("Enter the price of item without the $: ")

        try:

            val = float(items)

            print("Input amount is :", "$"+"{0:.2f}".format(val))

            test1 = False

        except ValueError:

            try:

                val = float(items)

                print("Input amount is :", "$"+"{0:.2f}".format(val))

                test = False

            except ValueError:

                print("That is not a number")

    new.append(items)



# define calculations

subtotal = sum(new)

tax = subtotal * .07

final = subtotal + tax


# tax & subtotal

print("Subtotal: ", "$"+"{0:.2f}".format(subtotal))

print("Tax: ", "$"+"{0:.2f}".format(tax))

print("Tare: ", "$"+"{0:.2f}".format(final))


慕虎7371278
浏览 110回答 4
4回答

侃侃无极

我清理了输出并利用反馈使其工作得更好。现在,如果人们有关于简化代码的建议,那就太好了。我想确保我以 Python 的方式编写东西,并且从内存使用和代码空间的角度来看也是高效的。感谢大家迄今为止提供的所有帮助!# define variablesnew = []items = float()subtotal = float()tax = float()final = float()    # welcome and set rules of entering numbersprint("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")# gathering input for itemsfor _ in range(5):    # define condition to continue gathering input    test = True    while test:  # test1 will verify integer or float entered for item1        items = input("\nEnter the price of item without the $: ")        try:            val = float(items)            print("Input amount is :", "$"+"{0:.2f}".format(val))            test = False        except ValueError:            try:                val = float(items)                print("Input amount is :", "$"+"{0:.2f}".format(val))                test = False            except ValueError:                print("That is not a number")    # append items to the list defined as new    new.append(items)    # define calculations    subtotal += float(items)    tax = subtotal * .07    print("Cost Subtotal: ", "$" + "{0:.2f}".format(subtotal), " & Tax Subtotal: ", "$" + "{0:.2f}".format(tax))    _ += 1    # define calculationsfinal = subtotal + tax# items tax & subtotalprint("\n Final list of item cost:")new_list = [float(item) for item in new] # fixed this toofor i in new_list:    print("- $"+"{0:.2f}".format(i))print("\n Final Pretax Total: ", "$"+"{0:.2f}".format(subtotal))print(" Final Tax: ", "$"+"{0:.2f}".format(tax))print("\n Tare: ", "$"+"{0:.2f}".format(final)) 

万千封印

所以问题出在你的while循环上。在伪装中,您的while循环while True:永远保持这种状态,直到用户输入一些分支到 的文本或字符串except,但之后又会这样吗?我很确定它except会工作,因为你的代码正在执行except两次,即使它分支try:&nbsp; &nbsp; val = float(items)&nbsp; &nbsp; print("Input amount is :", "$"+"{0:.2f}".format(val))&nbsp; &nbsp; test1 = Falseexcept ValueError:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; val = float(items)&nbsp; &nbsp; &nbsp; &nbsp; print("Input amount is :", "$"+"{0:.2f}".format(val))&nbsp; &nbsp; &nbsp; &nbsp; test = False您可能不需要整个第二个 try 语句并将其替换为print("That is not a number")andtest = False您控制 ( _) 没有在代码中的任何地方使用,所以我只需删除_ += 1我的理解现在我认为你想要做的是从用户那里获取 5 个项目,如果用户的输入不是正确的浮点数,它会再次询问,直到用户有 5 个输入正确为止。您的for循环可以替换为:首先确保您有一个计数器变量,例如vorc并将其分配给0。我们希望从用户那里获得while计数器变量小于 5(范围为0,1,2,3,4(5 倍))的输入。如果用户输入正确,您可以将计数器加 1,但如果不正确,您不执行任何操作,我们continue在try语句中,第一行可以是您想要测试的任何内容,在这种情况下,float(input("............."))如果输入正确并且没有错误被抛出,那么在这些行下方您可以添加您想要做的事情,在我们的例子中,它将增加计数器加一 ( v += 1) 并将其附加到new. 现在,如果用户输入不正确并抛出一个在我们的例子中是 to 的情况,except我们要做的就是。当抛出错误时,直接跳转到,不执行下一行。ValueErrorcontinueexcept这是获取用户输入的最终循环:v = 0while v < 5:&nbsp; &nbsp; items = input("...........")&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; float(items)&nbsp; &nbsp; &nbsp; &nbsp; v += 1&nbsp; &nbsp; &nbsp; &nbsp; new.append(items)&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; continue其余的代码可以是相同的!#defining variablesv = 0new = []items = float()tax = float()final = float()subtotal = float()#gathering input from itemswhile v < 5:&nbsp; &nbsp; items = input("Enter the price of item without the $: ")&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; float(items)&nbsp; &nbsp; &nbsp; &nbsp; v += 1&nbsp; &nbsp; &nbsp; &nbsp; print("Input amount is :", "$"+"{0:.2f}".format(float(items)))&nbsp; &nbsp; &nbsp; &nbsp; new.append(float(items))&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; continue# define calculationssubtotal = sum(new)tax = subtotal * .07final = subtotal + tax# tax & subtotalprint("Subtotal: ", "$"+"{0:.2f}".format(subtotal))print("Tax: ", "$"+"{0:.2f}".format(tax))print("Tare: ", "$"+"{0:.2f}".format(final))就这样!希望你明白为什么...

梵蒂冈之花

您无法在结束时获得最终计算的原因是循环实际上并未终止。此外,您的列表中还填充了 的字符串new.append(items)。你会想要new.append(val)这样它会添加这些值。这是一个使用 @Green Cloak Guy 的 while 循环建议来解决这个问题的版本。我这样做是为了它会添加任意数量的值,并具有明确的“END”条件,用户输入“end”即可退出并获得总计。 items.upper()将所有字母变为大写,因此您可以与“END”进行比较,并且仍然捕获“end”、“End”或“eNd”。#!/usr/bin/python3# define variables# you do not have to declare variables in python, but we do have to&nbsp;# state that new is an empty list for new.append() to work laternew = []# welcome and set rules of entering numbersprint("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")print('Type "end" to stop and total items')# gathering input for itemswhile True:&nbsp; &nbsp; items = input("Enter the price of item without the $: ")&nbsp; &nbsp; if items.upper() == 'END':&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; val = float(items)&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("Not a valid number.&nbsp; Try again, or 'end' to stop")&nbsp; &nbsp; new.append(val)# define calculationssubtotal = sum(new)tax = subtotal * .07final = subtotal + tax# tax & subtotalprint("Subtotal: ", "$"+"{0:.2f}".format(subtotal))print("Tax: ", "$"+"{0:.2f}".format(tax))print("Tare: ", "$"+"{0:.2f}".format(final))

MMTTMM

试试这个方法:new = []items = float()tax = float()final = float()subtotal = float()# welcome and set rules of entering numbersprint("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")try:&nbsp; &nbsp; new = list(map(lambda x: float(x), list(map(input, range(5)))))except:&nbsp; &nbsp; print("Some values are not a number")# define calculationssubtotal = sum(new)tax = subtotal * .07final = subtotal + tax# tax & subtotalprint("Subtotal: ", "$"+"{0:.2f}".format(subtotal))print("Tax: ", "$"+"{0:.2f}".format(tax))print("Tare: ", "$"+"{0:.2f}".format(final))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python