mardi 4 août 2015

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. 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:

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

Aucun commentaire:

Enregistrer un commentaire