简体   繁体   English

如何提高代码效率(For循环?)

[英]How to make code more efficient (For loop?)

I want to make my code more efficient by instead of repeating my code again for level two, having the only change as the random numbers change from 1-10 to 1-100 I can make these a variable making max_number = 10 for level one and max_number = 100 for level two and use the same code, halfing the amount of lines I have in this code. 我想提高代码效率,而不是在第二级重复执行我的代码,唯一的变化是随机数从1-10变为1-100,我可以使它们成为变量,从而使max_number = 10成为第一级,对于第二级,max_number = 100,并使用相同的代码,将这段代码中的行数减半。 However I am unsure as I am not extremely experience, on how to do this, I have gotten tips to use a for loop, and I was wondering if anyone could help me with this: 但是,由于我不是很经验,所以我不确定如何执行此操作,我已经获得了使用for循环的技巧,并且我想知道是否有人可以帮助我:

Here is my inefficient code: 这是我效率低下的代码:

#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()

A good first step would be to concentrate on splitting your code into functions. 最好的第一步是集中精力将代码拆分为功能。 You need to consider what code you keep duplicating and how it could be moved into a function. 您需要考虑不断复制哪些代码,以及如何将其移动到函数中。 The aim is to pass as a parameter the things which might be different. 目的是将可能不同的事物作为参数传递。

Consider your code for accepting input from the user. 考虑您的代码以接受用户输入。 You have almost identical code in four places. 您在四个地方有几乎相同的代码。 You wish to validate the input and only accept one of two values. 您希望验证输入,并且仅接受两个值之一。 This could be moved to a function as follows: 可以将其移至以下函数:

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

The function takes the prompt you wish to give the user, and the two possible answers that you will accept. 该功能会提示您希望给用户的提示,以及您将接受的两个可能的答案。 You could then replace four parts of your code with the following: 然后,您可以将代码的四个部分替换为以下内容:

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

or 要么

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

Next you could think about writing a function to ask a question. 接下来,您可以考虑编写一个函数来提问。 This could take the range as a parameter. 这可以将范围作为参数。 So the first time you could call the function with 10 for your level 1 questions, and then the same function could be called with 100 for your level 2 questions. 因此,您第一次可以为级别1的问题调用带有10的函数,然后可以为级别2的问题调用带有100的相同函数。

By splitting the code up like this, it should then become a little easier to spot where you could add loops. 通过这样分割代码,发现应该在何处添加循环的代码应该会更容易一些。

Hopefully this gives you a few ideas. 希望这会给您一些想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM