为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕虎7371278 2023-08-08 15:02:27
我正在尝试为课堂做作业,但它比需要的要困难得多,但我这样做是为了学习。任何人都可以看到我的代码有问题吗?我做了一些简单的搜索并尝试了一些修复,但我一定错过了一些基本的东西。另外,我似乎无法将我的“新”列表中的所有项目相加。环顾四周后我仍然无法弄清楚这一点。正如主题所说,我对此很陌生,因此非常感谢任何帮助。# define variablesnew = []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.")# gathering input for itemsfor _ 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 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))
查看完整描述

4 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

我清理了输出并利用反馈使其工作得更好。现在,如果人们有关于简化代码的建议,那就太好了。我想确保我以 Python 的方式编写东西,并且从内存使用和代码空间的角度来看也是高效的。


感谢大家迄今为止提供的所有帮助!


# define variables

new = []

items = float()

subtotal = float()

tax = float()

final = 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):

    # 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 calculations

final = subtotal + tax


# items tax & subtotal

print("\n Final list of item cost:")

new_list = [float(item) for item in new] # fixed this too

for 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)) 


查看完整回答
反对 回复 2023-08-08
?
万千封印

TA贡献1891条经验 获得超3个赞

所以问题出在你的while循环上。


在伪装中,您的while循环while True:永远保持这种状态,直到用户输入一些分支到 的文本或字符串except,但之后又会这样吗?我很确定它except会工作,因为你的代码正在执行except两次,即使它分支


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

您可能不需要整个第二个 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 = 0


while v < 5:

    items = input("...........")

    try:

        float(items)

        v += 1

        new.append(items)

    except ValueError:

        continue

其余的代码可以是相同的!


#defining variables

v = 0

new = []

items = float()

tax = float()

final = float()

subtotal = float()


#gathering input from items

while v < 5:

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

    try:

        float(items)

        v += 1

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

        new.append(float(items))

    except ValueError:

        continue



# 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))

就这样!希望你明白为什么...


查看完整回答
反对 回复 2023-08-08
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

您无法在结束时获得最终计算的原因是循环实际上并未终止。此外,您的列表中还填充了 的字符串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 

# state that new is an empty list for new.append() to work later

new = []


# welcome and set rules of entering numbers

print("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 items

while True:

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

    if items.upper() == 'END':

        break

    try:

        val = float(items)

    except ValueError:

        print("Not a valid number.  Try again, or 'end' to stop")

    new.append(val)


# 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))


查看完整回答
反对 回复 2023-08-08
?
MMTTMM

TA贡献1869条经验 获得超4个赞

试试这个方法:


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.")


try:

    new = list(map(lambda x: float(x), list(map(input, range(5)))))

except:

    print("Some values are not a number")


# 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))


查看完整回答
反对 回复 2023-08-08
  • 4 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信