我对编程逻辑太陌生了,我不确定我是否能恰当地表达这一点。我正在使用Python2.7,并尝试编写一个脚本,该脚本将一直重复,直到输入0为止。我尝试了if、else和while语句,得出的结论是我对逻辑的了解不够,无法了解Python。例如…我太新了,所以初始化对我来说毫无意义。我几乎在收到的每个搜索结果中都看到过这个短语,但我不知道它是什么意思。我所在的类是逻辑类而不是Python类。我可以用伪代码写,但我真的很想看到一个工作模型。请帮忙。此脚本将运行并在输入零时退出,但不会再次提示行驶里程。你知道吗
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
getMiles = float(input ('Enter Miles: '))
while getMiles == 0:
print "END OF PROGRAM"
exit
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
while costOfTrip == float:
getMiles
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
我忘了提的是强制性的“项目结束”声明。我把你的答案和这个结合起来了。再次感谢大家。我可以不再把头撞在墙上了。你知道吗
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or enter zero to quit"
getMiles = float(raw_input ('Enter Miles: '))
while getMiles >= 0:
if getMiles == 0:
print "END OF PROGRAM"
exit()
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
getMiles = float(raw_input ('Enter Miles: '))
你很接近,这是固定版本:
我在整个代码块周围添加了一个
while True
,这将导致问题被反复询问(永远),直到用户输入0英里。你知道吗唯一需要修正的是
exit
是一个函数调用,所以它应该是exit()
。你知道吗我只是想说,作为一个风格的问题,即使你的新循环条件/逻辑可以很快整理起来阅读
Python实际上离伪代码不远,实际上这里的问题不是代码而是逻辑。你知道吗
要获得基本的“循环直到进入零”,可以使用以下逻辑:
至于你自己的代码,你似乎在用while,而你的意思是if 在第二种情况下,实际上只是命名一个变量(getMiles),它什么也不做
整个代码可以如下所示:
**不需要像其他人建议的那样使用“while true”,这从来都不是一件好事。你知道吗
更高级的版本是提取逻辑中可重复且独立于函数的部分
至于init是什么,这是一个更高级的面向对象的主题,您可能还不需要担心
相关问题 更多 >
编程相关推荐