gpt4 book ai didi

python - 使用基于计数的迭代结构的初学者 Python 程序

转载 作者:行者123 更新时间:2023-12-03 20:47:34 25 4
gpt4 key购买 nike

我正在学习 Python 编程初学者类(class),我们要编写一个程序来生成项目描述、价格和总数。我最初编写的程序使用了 LISTS,这让我在作业中得到了一个胖 0,因为显然我们不会在这个作业中使用列表。幸运的是,我可以重写它。所以,我应该使用基于计数的迭代结构,我可以使用“for”语句,或者同时使用“for”和“while”语句。但不仅仅是“while”语句(基于计数而不是基于事件)。我不知道哪种组合最有效。我附上了我的程序,但我认为它根本不是很好,结构对我来说似乎很糟糕。如果有人能给我一些关于如何使它看起来更好的指导,或者我如何改进它,我将不胜感激。我已经搜索了一个不包含列表或一些疯狂内容的示例(我是初学者,所以我们使用初学者的东西),但根本没有运气。
最后,我想再说一遍,我不能使用 LISTS,提前谢谢大家。
问题:
利用基于计数的迭代结构,该结构将接受下面列出的数据并生成总购买量。您的最终报告应该类似于下面的一个节目。
输入数据:

Item Description    Item Price
Salomon Fish $ 26.97
Ribeye Steak $ 12.98
Sweet Corn $ 4.96
Asparagus $ 5.92
输出:
Item Description       Item Price

=================================

Salomon Fish $ 26.97

Ribeye Steak $ 12.98

Sweet Corn $ 4.96

Asparagus $ 5.92

Your total purchase: $ xx.xx

我的代码: (对不起,如果格式错误,我从未在这里发布过)
fish=int(input("enter fish price ===> "))
corn=int(input("enter corn price ===> "))
steak=int(input("enter steak price ===> "))
asparagus=int(input("enter asparagus price ===> "))
for x in range (1,fish+1,1):
total=x
for y in range(1,corn+1,1):
total=x+y
for z in range(1,steak+1,1):
total=x+y+z
for i in range(1,asparagus+1,1):
total=x+y+z+i
print("Item Description Item Price")
print("==============================")
print("Fish $",fish)
print("Corn $",corn)
print("Steak $",steak)
print("Asparagus $",asparagus)
print("Your Total Purchase:", total)
输出是:
enter fish price ===> 5
enter corn price ===> 5
enter steak price ===> 5
enter asparagus price ===> 5
Item Description Item Price
==============================
Fish $ 5
Corn $ 5
Steak $ 5
Asparagus $ 5
Your Total Purchase: 20

最佳答案

我同意 Mark Meyer : 分配没有指定输入。你的编程风格已经做得很好了。鉴于这些限制,我只建议进行一些改进:

  • 对总和使用运行总计变量。
  • 给它一个有意义的名字。 x, y, z 没有意义。

  • 在这里,运行记录看起来像这样:
    total = 0
    total += fish
    total += corn
    ...

    关于python - 使用基于计数的迭代结构的初学者 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64830081/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com