我该如何改善呢?

时间:2018-11-14 14:25:55

标签: python

我目前正在自学Python,这是我的第一个程序。我正在做一些简单的项目,所以我可以改善。想听听对此的反馈。

import random

print("There is a number between 1 and 100 guess it and you will win a price : ")


def guess():
    # A simple guess game.
    random_number = random.randint(1, 5)
    flag = True
    user_guess = []

    while flag:

        user_number = input("Enter the number : ")

        user_guess.append(user_number)

        if int(user_number) < random_number:
            print("You have to go higher")

        elif int(user_number) > random_number:
            print("You have to go lower ")

        else:
            flag = False
            print("Congrats you win !!! \nThe numbers of guesses before you won : ")
            print(len(user_guess))


guess()

while True:
    play_again = input("Do you like to play again ? : (y/n): ")
    if play_again == 'y':
        guess()
    else:
        print("Thank you for playing have a nice day!!! ")
        break

1 个答案:

答案 0 :(得分:2)

  1. 如果用户输入无效(非数字)字符,您的程序将引发异常。使用isdigit可以避免这种情况。
  2. 每次要将user_number与其他整数进行比较时,都将user_number转换为整数是昂贵且琐碎的。转换一次,然后将其重新分配给flag
  3. while True是不必要的。使用list,并在需要时中断。
  4. 仅保留整个count对象来计数用户输入的内容有点过头。使用一个整数(在我的示例中为print("There is a number between 1 and 100 guess it and you will win a price : "))并使用它。
  5. 您打印“介于1到100之间” ,但是您的程序会创建一个介于1到5之间的随机整数。我不确定这样做的意图(也许是调试辅助工具),但是我认为这是一个小错误。
  6. 一个较小的建议,将guess移至guess函数,因为该函数声明自己的目的更有意义。

以下是我对def guess(): print("There is a number between 1 and 100 guess it and you will win a price : ") # A simple guess game. random_number = random.randint(1, 100) # flag = True obsolete count = 0 while True: user_number = input("Enter the number : ") if (user_number.isdigit()): user_number = int(user_number) else: print("Invalid:") continue count += 1 if user_number < random_number: print("You have to go higher") elif user_number > random_number: print("You have to go lower ") else: print("Congrats you win !!! \nThe numbers of guesses before you won : ") print(count) break 函数进行的更改:

 proc sql;
 connect to Hadoop <connection info>;
  exec( create external table hadoop1( x double, y string, z double) row format
 delimited fields terminated by ‘\001’ stored as textfile location
 '/tmp/hadoop1_hdfs_file') by hadoop;
 quit;