一个简单的程序来帮助我计算一些新地板的成本,但我的最终产出不是我所期望的。 特别是,当underlay为“No”时,underlayrea的变量仍在提取值并在末尾打印。 如果不是很明显,这是我第一次尝试。永远不会
我原以为,虽然“edging”和“underlay”的变量保持为“No”,但while循环中不会存储任何值
underlay='No'
edging=input('Are you ordering Edging?').title()
underlay=input('Are you ordering underlay?').title()
roomsize=input('How many square meters is the room?')
roomflt=float(roomsize)
while edging =='Yes':
#ask for user inputs
edgeprice=input("How much is the edging per meter?")
edgeperim=input('What is the perimeter of the room?')
#convert to float for calculation
one=float(edgeperim)
two=float(edgeprice)
#calculate
edgearea=one*two
#reset flag
edging='No'
while underlay=='Yes':
#ask for user input
underlayprice=input('How much per square meter for the Underlay?')
#convert to float for calculation
three=float(underlayprice)
four=float(roomflt)
#calculate
underlayarea=three*four
#reset flag
underlay='No'
#set the floor price
floorprice=input("How much is the floor per square meter?")
#convert to float for calculation
five=float(floorprice)
six=float(roomflt)
#calculate
area=five*six
#get the cost
addemup=(edgearea+underlayarea+area)
print("\n----------------------------------------------\nThe total is £{0:.2f} to purchase the flooring.".format(addemup))
print("This is made up of £{0:.2f} for the floor itself,".format(area))
print("This is made up of £{0:.2f} for the edging,".format(edgearea))
print("and £{0:.2f} for the underlay".format(underlayarea))
应该使用简单的
if
-语句,而不是使用while
-循环和循环底部的“重置标志”。我还通过给变量命名来提高代码的可读性(从不给变量命名,比如one
、two
等等)。您还必须定义edgearea
和underlayarea
,因为如果用户在至少一个输入中输入"No"
,则会引发NameError
我还想建议大家看看干法原理,也就是“不要重复你自己”。这三种计算形式基本相同。这就是为什么更好的代码风格是为这些计算定义一个函数,该函数采用必要的参数。干溶液可能类似于以下内容:
相关问题 更多 >
编程相关推荐