请审查我的示例Python程序代码
我正在学习Python,因为我想把这门语言的基本概念教给11岁的孩子们(我是一名老师)。我们已经做了一些基础的工作,让他们理解编程的基本要素,以及如何把任务拆分成小块等等。Python是英国新课程中将要教授的语言,我不想让孩子们养成坏习惯。下面是我写的一个小程序,没错,我知道它写得不好,但如果能给我一些改进的建议,我会非常感激。
我还在努力学习这门语言的教程,所以请多多包涵!:o)
# This sets the condition of x for later use
x=0
# This is the main part of the program
def numtest():
print ("I am the multiplication machine")
print ("I can do amazing things!")
c = input ("Give me a number, a really big number!")
c=float(c)
print ("The number", int(c), "multiplied by itself equals",(int(c*c)))
print("I am Python 3. I am really cool at maths!")
if (c*c)>10000:
print ("Wow, you really did give me a big number!")
else:
print ("The number you gave me was a bit small though. I like bigger stuff than that!")
# This is the part of the program that causes it to run over and over again.
while x==0:
numtest()
again=input("Run again? y/n >>>")
if x=="y":
print("")
numtest()
else:
print("Goodbye")
4 个回答
2
你需要结束这个循环。
你的 while 循环应该是:
while again == 'y':
这样的话,
again = 'y'
def numtest():
print ("I am the multiplication machine")
print ("I can do amazing things!")
c = input("Give me a number, a really big number!")
c = float(c)
print ("The number", int(c), "multiplied by itself equals", (int(c * c)))
print("I am Python 3. I am really cool at maths!")
if (c * c) > 10000:
print ("Wow, you really did give me a big number!")
else:
print ("The number you gave me was a bit small though. I like bigger stuff than that!")
# This is the part of the program that causes it to run over and over again.
while again == 'y':
numtest()
again = input("Run again? y/n >>>")
if again != "y":
print("Goodbye")
4
既然你想教大家好的编程风格:
不要用像
x
这样的变量名,除非你是在画图。可以参考 PEP008 来了解命名规则和风格。保持空格的一致性:
c = input ("Give me a number, a really big number!") c=float(c)
这样是不一致的。哪种写法更好呢?
如果你真的想要一个无限循环的话:
while True: numtest() again = input("Run again? y/n >>>") if again.lower().startswith("n"): print("Goodbye") break
不过,有些人认为使用 break
是不好的风格,你同意吗?你会怎么重写这个循环,让它不使用 break 呢?这或许可以作为你学生的一个练习?
11
你似乎不需要这个变量 x
while True:
numtest()
again = input("Run again? y/n >>>")
if again == "y": # test "again", not "x"
print("")
else:
print("Goodbye")
break # This will exit the while loop