希望能对此进行回顾。这个程序确实能按计划工作。但是,我不确定是否有一种更优雅或更好的方法来使用更少的代码来执行这个过程。
def main():
print ('This program takes two numbers and multiplies them.')
print ('the result is multiplied by a third number')
print ('entered by the user too')
procedure()
def procedure():
n = float(input('Enter a number: '))
n2 = float (input('Enter a number: '))
value = n * n2
y = value
print value
n3 = float(input('Multiply by: '))
while n3 != '0':
op = n3 * y
y = op
print y
n3 = float(input('Multiply by: '))
main()发布于 2015-01-08 07:30:41
您的程序是一个无限循环,因为浮点数永远不等于字符串。
既然您声称这个程序按预期工作,那么我就会相信您的话,并说循环应该使用while True: …编写。
有太多的变量被使用没有好的理由。特别是y和value是多余的。
变量名没有意义,您的函数名也没有意义。
习惯上使用样板if __name__ == '__main__': …介绍您的主要代码。
你做了多次float(input(…))。将其提取到函数中是值得的。
要打印多行字符串,请编写一个"""multiline string"""。在这种情况下,字符串可以作为程序的docstring执行双重任务,所以我将这样编写它。
"""This program takes two numbers and multiplies them.
the result is multiplied by a third number
entered by the user too"""
def prompt_float(prompt):
return float(input(prompt))
def repeated_multiply():
product = prompt_float('Enter a number: ') * \
prompt_float('Enter a number: ')
while True:
print(product)
product *= prompt_float('Multiply by: ')
if __name__ == '__main__':
print(__doc__)
repeated_multiply()发布于 2015-01-08 06:30:24
变量名称:
n、n3等。相反,product、multiplier等就更好了。其他:
y = 0来自n * n2,那么它就是一个徒劳无益的乘法循环。value、y、op。https://codereview.stackexchange.com/questions/76940
复制相似问题