如何使代码更有效(For loop?)

时间:2015-08-04 09:35:24

标签: python

我想让我的代码更高效,而不是再次重复我的代码用于第二级,随着随机数从1-10变为1-100的唯一变化我可以使这些变量使max_number = 10 for对于第二级,级别1和max_number = 100,并使用相同的代码,将此代码中的行数减半。但是我不确定,因为我不是非常经验,关于如何做到这一点,我已经获得了使用for循环的提示,我想知道是否有人可以帮助我:

这是我效率低下的代码:

#The two imports, import modules. They allow me to use functions defined elsewhere such as when I import a random number or
#use sys.exit() to terminate the game
import random
import sys 

#Ask the user for name, use in opening comments

user_name=str(input("Please type in your name: "))
#print instructions
print('''Hello {}! Welcome!
This game is going to develop your number skills! 

So here is how to play:
Firstly, {}, we are going to give you two numbers.
Then you must choose which of these numbers you think is bigger or which number is smaller.
Type this number in and if you are right you will get a point.
Get enough points and you can progress to level two!
''' .format(user_name, user_name))

#Set the scores of both user and computer to 0
user_score = 0
comp_score = 0
level = 1


#Only use the loop when the user score is below three
#Then randomly select to either have type_question to be bigger or smaller and this will define which path the program will take
while user_score < 3:
    bigorsmall = ['bigger', 'smaller']
    type_question = random.choice(bigorsmall)

#Import two random integers, then make sure these integers are not the same
    a1 = random.randint(1, 10)
    a2 = random.randint(1, 10)
    while a1 == a2:
        a2 = random.randint(1, 10)

    print("\nThe two random values are {} and {}. \n " .format(a1, a2))

#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#If the type of question is bigger than the loop to ask for the bigger number is used
    if type_question == 'bigger':
        bigger = max(a1, a2)

#Ask the user to type in which they think is the bigger number
#The while strand means that no other integers then the integers given are allowed
#The except strand of the loop means that only integers can be entered

        while True:
            try:
                user_num = int(input("Which number is bigger:"))
                while user_num != a1 and user_num != a2:
                    user_num = int(input("Please pick either {} or {}:" .format(a1, a2)))
                break
            except ValueError:
                print("That is not an integer, please try again.")

#If users number is correct then give the user one point, if not give computer a point.             
        if user_num == bigger:
            print("\nCorrect, you get one point, keep playing you are doing great!")
            user_score+=1
        else:
            print('\nSadly that is wrong, keep trying! The bigger number was {}, the computer gets one point.'.format(bigger))
            comp_score+=1

        print("Your score is: {} \nThe computers score: {}" .format(user_score, comp_score))

#-----------------------------------------------------------------------------------------------------------------------
#This is the same loop as previously however the purpose is for the user to find the SMALLER number
#This loop is used if type_question was computer generated randomly as smaller        
    elif type_question == 'smaller':
        smaller = min(a1, a2)

        while True:
            try:
                user_num = int(input("Which number is smaller:"))
                while user_num != a1 and user_num != a2:
                    user_num = int(input("Please pick either {} or {}:" .format(a1, a2)))
                break
            except ValueError:
                print("That is not an integer, please try again.")


        if user_num == smaller:
            print('\nCorrect, you get one point, keep playing you are doing great!')
            user_score+=1
        else:
            print('\nSadly that is wrong, keep trying! The smaller number was {}, the computer gets one point.'.format(smaller))
            comp_score+=1

        print("Your score is: {} \nThe computers score: {}".format(user_score, comp_score))       

#-----------------------------------------------------------------------------------------------------------------------
#encourage the user to keep playing + allow an option to quit the game

cont_game = input("\n{} you are doing great! If you would like to keep playing type 'yes' \nIf you would like to quit press any key and then enter:" .format(user_name))

if cont_game == "yes":
    print("\nYAY!")
else:
    print("Hope you had fun!")
    sys.exit() 

#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------   
#Start of a level two
#Same rules apply so no need for new information
#This loop is the same as previous loops, so comments are only placed where changes have been made

user_score = 0
comp_score = 0
level = 2

print("YOU HAVE GOT TO LEVEL {}! \nThe numbers now could be between 1 and 100! \nSame rules apply.".format(level))

print("Your score has reset to 0 and you must get 5 points to win at this game.")

while user_score < 5:
    bigorsmall= ['bigger', 'smaller']
    type_question = random.choice(bigorsmall)

#In level two the integers could be from 1 to 100   
    a1 = random.randint(1, 100)
    a2 = random.randint(1, 100)
    while a1 == a2:
        a2 = random.randint(1, 100)

    print("\nThe two random values are {} and {}. \n " .format(a1, a2))

#-----------------------------------------------------------------------------------------------------------------------
    if type_question == 'bigger':
        bigger = max(a1, a2)

        while True:
            try:
                user_num = int(input("Which number is bigger:"))
                while user_num != a1 and user_num != a2:
                    user_num = int(input("Please pick either {} or {}:" .format(a1, a2)))
                break
            except ValueError:
                print("That is not an integer, please try again.")

        if user_num == bigger:
            print("\nCorrect, you get one point, keep playing you are doing great!")
            user_score+=1
        else:
            print('\nSadly that is wrong, keep trying! The bigger number was {}, the computer gets one point.'.format(bigger))
            comp_score+=1

        print("Your score is: {} \nThe computers score: {}" .format(user_score, comp_score))

#-----------------------------------------------------------------------------------------------------------------------
    elif type_question == 'smaller':
        smaller = min(a1, a2)

        while True:
            try:
                user_num = int(input("Which number is smaller:"))
                while user_num != a1 and user_num != a2:
                    user_num = int(input("Please pick either {} or {}:" .format(a1, a2)))
                break
            except ValueError:
                print("That is not an integer, please try again")

        if user_num == smaller:
            print('\nCorrect, you get one point, keep playing you are doing great!')
            user_score+=1
        else:
            print('\nSadly that is wrong, keep trying! The smaller number was {), the computer gets one point.'.format(smaller))
            comp_score+=1

        print("Your score is: {} \nThe computers score: {}".format(user_score, comp_score))       

#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#End of game, automatically terminate the program
print("You have won the game, I hope you had fun!")
sys.exit()

1 个答案:

答案 0 :(得分:0)

好的第一步是集中精力将代码分解为函数。您需要考虑您保留的代码重复以及如何将其移动到函数中。目的是将可能不同的东西作为参数传递。

考虑接受用户输入的代码。你在四个地方有几乎相同的代码。您希望验证输入并仅接受两个值中的一个。这可以移动到如下函数:

def get_input(prompt, a1, a2):
    while True:
        try:
            user_num = int(input(prompt))
            while user_num != a1 and user_num != a2:
                user_num = int(input("Please pick either {} or {}:" .format(a1, a2)))
            break
        except ValueError:
            print("That is not an integer, please try again.")

    return user_num

该功能会获取您希望为用户提供的提示,以及您将接受的两个可能答案。然后,您可以使用以下代码替换代码的四个部分:

user_num = get_input("Which number is bigger? ", a1, a2)

user_num = get_input("Which number is smaller? ", a1, a2)

接下来,您可以考虑编写一个函数来提问。这可以将范围作为参数。因此,第一次使用10调用函数调用1级问题时,可以使用100调用相同的函数来处理2级问题。

通过像这样拆分代码,可以更容易地找到可以添加循环的位置。

希望这会给你一些想法。