请仔细阅读我的示例Python程序

我仍然在学习Python,因为我想向十一岁的孩子(我作为一名教师工作)教授这门语言的基本概念。 我们在基础方面做了一些工作,以便他们理解编程的基本要点,并将任务分解为块等。 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")

你似乎不需要变量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

既然你想教好风格:

  • 除非你创建一个图,否则不要使用像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? 你的学生可能会练习吗?


    你必须打破循环

    你的时间应该是

    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")
    
    链接地址: http://www.djcxy.com/p/54305.html

    上一篇: Please code review my sample Python program

    下一篇: Whether this Python Book can be Learned with version 2.6? instead of 2.5