【问题标题】:Python3 if Statement in a LoopPython3 if 循环语句
【发布时间】:2013-10-10 04:35:15
【问题描述】:

当我的输出应该是“住宅、商业、城市和教区”时,我得到的是“R、B、C 和 P”

我的总数也得到 0.00,如果是企业、城市或教区(它们都不同),我需要总数……它不是计算。

我从 .data 文件中获取输入,它们是正确的

print("=========================================================")
print(format("Name", '<12s'),format("Type", '<15s'),format("Location", '<10s'),format("KwH", '>6s'),format("Total", '>10s'))
print("=========================================================")
total = 0
for i in range(10):
    custName = input()
    custType = input()
    custLoc = input()
    custKwh = eval(input())
    if (custType == "R"):
        custType = "Residential"
    if (custType == "B"):
        custType = "Business"
        total = (custKwh * 0.05710) + 10
    if (custLoc == "C"):
        custLoc = "City"
        total = (custKwh * 0.0401) + 6
    if (custLoc == "P"):
        custLoc = "Parish"
        total = (custKwh * 0.04411) + 6.60
    print(format(custName, '<12s'),format(custType, '<15s'),format(custLoc, '<10s'),format(custKwh, '>6d'),format(total, '>10.2f'))

输入是:

Smith R P 4500 Taylor R C 6000 Williams B C 10500 Johnson R C 7500 Davis R P 3000 Woods B P 25300 Morgan R C 5800 Landry R C 3900 Young B P 18500 Wilson R P 7000

【问题讨论】:

  • 首先,我看不出你是如何得到任何输出的,因为你没有输出任何东西。其次,也许您应该在更新代码以显示输出方式后给出输入示例。
  • 代码已更新,这是我的全部代码..
  • 看起来您的输入需要您在每个值之后按回车键,这一切都被放入 custName 变量中。您可以通过使用 .split(' ') 将一个输入输入所有差异变量来修复它
  • 我在数据文件中的每个值之后都输入了它...我不想占用太多空间所以我只是在这里输入它们
  • 您需要做的另一件事是在 custLoc 的 if 语句中设置 custLoc 而不是 custType

标签: python loops if-statement


【解决方案1】:

我会改写成这样:

print("=========================================================")
print(
    format("Name", '<12s'),
    format("Type", '<15s'),
    format("Location", '<10s'),
    format("KwH", '>6s'),
    format("Total", '>10s')
)
print("=========================================================")
total = 0
for i in range(10):
    custName, custType, custLoc, custKwh = input().split(' ')
    custKwh = int(custKwh)
    if (custType == "R"):
        custType = "Residential"
    if (custType == "B"):
        custType = "Business"
        total = (custKwh * 0.05710) + 10
    if (custLoc == "C"):
        custLoc = "City"
        total = (custKwh * 0.0401) + 6
    if (custLoc == "P"):
        custLoc = "Parish"
        total = (custKwh * 0.04411) + 6.60
    print(
        format(custName, '<12s'),
        format(custType, '<15s'),
        format(custLoc, '<10s'),
        format(custKwh, '>6d'),
        format(total, '>10.2f')
    )

这里的关键错误是您在检查 custLoc 时再次设置了 custType(复制粘贴错误?)

【讨论】:

  • 这仍然没有解决我的问题,仍然得到 R、B、C 和 P ......并且总值仍然是 0.00。我应该将 total = 设置为其他内容吗?为什么不计算
  • @user2865217 我不是在和你聊天。只需发布您的命令或自己学习 python —— 很抱歉,我们这样做是免费的。
  • 你是如何运行脚本的?您用来启动它的确切命令是什么。您是如何获取数据的?
  • python pa3.py
  • 你看到的和我看到的有什么不同? gist.github.com/ranman/6913539
猜你喜欢
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
相关资源
最近更新 更多