Python Forum
Creating a variable that displays time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a variable that displays time
#1
Hi all,

I am doing a year 8 digital media assignment. We are allowed to get help from anywhere and are allowed to get the code as complex as we like. My teacher has taught her self some basic python, as she transferred from art, but has not been able to help me. I am creating a simple 10 question maths game, that you can choose what operation to use, and what the minimum and maximum numbers will be.

My teacher suggested that I post on a community forum to try to get some help. I have been trying to time how long it takes the player to answer 10 questions.

Sorry about this mass of code but...

Here is my code:
def main():
    from random import randint
    
    #Defines what the title will look like. Prints all visuals. (When called)
    def dis_intro():
        title = "**A Simple, 10 question Maths Quiz**"
        author = "_____________ By Elijah ____________"
        print("*" * len(title))
        print(title)
        print("*" * len(title))
        print(author)
    
    #Defines the user options. Prints all visuals. (When called)
    def dis_menu():
        title = "**A Simple, 10 question Maths Quiz**"
        men_list = ["1. Addition", "2. Subtraction", "3. Multiplication", "4. Division", "5. Random 1-10"]
       
    #Loops for the length of the list
        for i in range(0, len(men_list)):
            print(men_list[i]) #Prints
            
        print("-" * len(title))
        
    #Calls on the menu display (display_intro, and display_menu)
    dis_intro()
    dis_menu()
    
        #Asks what operation the user wants to use.
    choose = int(input("Enter your choice: "))
    print("")
    
    #Assigns a piece of either positive or critical feedback to a list, with a number to call apon.
    p_feedback = ["Correct, great job!", "Amazing, keep it up!", "Perfect!", "Good job!", "Keep it up!"]
    c_feedback = ["Wrong, nice try...", "Nearly...", "Not quite...", "Try again!", "Don't give up!"]
    
    #Runs code for addition questions.
    def addition():
            print("Great, addition!")
            import time
            question = int(0) #Sets the question number to 0.
            score = int(0) #Sets the player score to 0.
            min_num = input("What will the minimum number be? ") #Asks for minimum number, and assigns it to a variable.
            max_num = input("What will the maximum number be? ") #Asks for the maximum number, and assigns it to a variable.
            
            #loops until the player has answered 10 questions.
            while question != int(10):
                num_1 = randint(int(min_num), int(max_num)) #Imports a random interger between the player specified range, and assigns it to a variable to use for the question generation.
                num_2 = randint(int(min_num), int(max_num)) #Imports a random interger between the player specified range, and assigns it to a variable to use for the question generation.
                answer = num_1 + num_2 #Sets a question to ask the player.
                guess = input("Answer: " + str(num_1) + " + " + str(num_2) + " = ") #Displays the generated question to the player, and allows an input.
            
                #Determines if the answer the players inputed answer matches the computer generated answer.
                if int(answer) == int(guess):
                    rand_f = randint(0, 4) #Generates a random interger to use to call up a peice of feedback from the list.
                    print(p_feedback[rand_f]) #Uses the randomly generated Interger to print the feedback from the list.
                    question = question + 1 #Adds one to the question number.
                    score = score + 1 #Adds on to the score of the player.
                    print("You are on question: " + str(question) + "/10") #Prints question number.
                
                #Determines it the player answer is not equal to the computer generated answer.
                else:
                    rand_f = randint(0, 4) #Generates a random interger to use to call up a peice of feedback from the list.
                    print(c_feedback[rand_f]) #Uses the randomly generated Interger to print the feedback from the list.
                    question = question + 1 #Adds one to the question number.
                    
                #Determines if the player has answered 10 questions yet.
                if question == int(10):
                    print("")
                    print("Well done, you completed the quiz!") #Affirms player.
                    time.sleep(1)
                    print("You got " + str(score) + "/10 corect!") #Prints score.
                    print("")
                    time.sleep(1)
                    
                    #Defines what the title for playing agian will look like.
                    title_2 = "**Do you want to play again?**" #Defines the title.
                    print("*" * len(title_2)) #Prints * the length of the title.
                    print(title_2) #Prints the title.
                    print("*" * len(title_2)) #Prints * the length of the title.
                    
                    #Defines what the menu for playing again looks like.
                    title_2 = "**Do you want to play again?**" #Defines the title.
                    men_list_2 = ["1. Play again", "2. Exit"] #Defines the options the user has.
                    
                    #Loops for the length of the list.
                    for i in range(0, len(men_list_2)):
                        print(men_list_2[i]) #Prints.
        
                    print("-" * len(title_2)) #Prints _ the length of the title.
                    print("")
                    
                    choose_2 = int(input("What is your choice? ")) #Asks for player input.
                    
                    #Defines what will happen if the player chooses option 1.
                    if choose_2 == 1:
                        import time
                        print("")
                        print("Restarting Game")
                        print("Redirecting to menu.")
                        time.sleep(1)
                        print("...")
                        print("Loading Code.")
                        time.sleep(1)
                        print("...")
                        print("Reseting Variables.")
                        time.sleep(1)
                        print("...")
                        print("Wasting some time.")
                        time.sleep(1)
                        print("...")
                        print("Running Functions.")
                        time.sleep(2)
                        print("...")
                        print("")
                        time.sleep(1)
                        main() #Starts the main program again.
                        
                    #Defines what will happen if the player chooses option 2.
                    if choose_2 == 2:
                        print("")
                        print("Ok!")
                        print("Thanks for playing!")
                        print("")
                        print("Please come back soon!")

    #Calls on the code for each operation, depending on user input.
    if choose == 1:
        addition()
main()
That is the code that runs addition...

I was thinking about setting the current time at the start of the code to a variable, and then setting it to another variable at the end; Then working out the difference.
Reply
#2
Ok first of all restructure your code. How? Well you have functions inside a function, which is not a good idea because a function is meant for one process. So my suggestion is to make the code like this
from random import randint
def main():
    #Calls on the menu display (display_intro, and display_menu)
    dis_intro()
    dis_menu()

#Defines what the title will look like. Prints all visuals. (When called)
def dis_intro():
    title = "**A Simple, 10 question Maths Quiz**"
    author = "_____________ By Elijah ____________"
    print("*" * len(title))
    print(title)
    print("*" * len(title))
    print(author)
    
#Defines the user options. Prints all visuals. (When called)
def dis_menu():
    title = "**A Simple, 10 question Maths Quiz**"
    men_list = ["1. Addition", "2. Subtraction", "3. Multiplication", "4. Division", "5. Random 1-10"]
    
#Loops for the length of the list
    for i in range(0, len(men_list)):
        print(men_list[i]) #Prints
            
    print("-" * len(title))
        
    #Assigns a piece of either positive or critical feedback to a list, with a number to call apon.
    p_feedback = ["Correct, great job!", "Amazing, keep it up!", "Perfect!", "Good job!", "Keep it up!"]
    c_feedback = ["Wrong, nice try...", "Nearly...", "Not quite...", "Try again!", "Don't give up!"]
    
    #Asks what operation the user wants to use.
    choose = int(input("Enter your choice: "))
    print("")
    if choose == 1:
        addition()
      
    #Runs code for addition questions.
    def addition():
            print("Great, addition!")
            import time
            question = int(0) #Sets the question number to 0.
            score = int(0) #Sets the player score to 0.
            min_num = input("What will the minimum number be? ") #Asks for minimum number, and assigns it to a variable.
            max_num = input("What will the maximum number be? ") #Asks for the maximum number, and assigns it to a variable.
             
            #loops until the player has answered 10 questions.
            while question != int(10):
                num_1 = randint(int(min_num), int(max_num)) #Imports a random interger between the player specified range, and assigns it to a variable to use for the question generation.
                num_2 = randint(int(min_num), int(max_num)) #Imports a random interger between the player specified range, and assigns it to a variable to use for the question generation.
                answer = num_1 + num_2 #Sets a question to ask the player.
                guess = input("Answer: " + str(num_1) + " + " + str(num_2) + " = ") #Displays the generated question to the player, and allows an input.
             
                #Determines if the answer the players inputed answer matches the computer generated answer.
                if int(answer) == int(guess):
                    rand_f = randint(0, 4) #Generates a random interger to use to call up a peice of feedback from the list.
                    print(p_feedback[rand_f]) #Uses the randomly generated Interger to print the feedback from the list.
                    question = question + 1 #Adds one to the question number.
                    score = score + 1 #Adds on to the score of the player.
                    print("You are on question: " + str(question) + "/10") #Prints question number.
                 
                #Determines it the player answer is not equal to the computer generated answer.
                else:
                    rand_f = randint(0, 4) #Generates a random interger to use to call up a peice of feedback from the list.
                    print(c_feedback[rand_f]) #Uses the randomly generated Interger to print the feedback from the list.
                    question = question + 1 #Adds one to the question number.
                     
                #Determines if the player has answered 10 questions yet.
                if question == int(10):
                    print("")
                    print("Well done, you completed the quiz!") #Affirms player.
                    time.sleep(1)
                    print("You got " + str(score) + "/10 corect!") #Prints score.
                    print("")
                    time.sleep(1)
                     
                    #Defines what the title for playing agian will look like.
                    title_2 = "**Do you want to play again?**" #Defines the title.
                    print("*" * len(title_2)) #Prints * the length of the title.
                    print(title_2) #Prints the title.
                    print("*" * len(title_2)) #Prints * the length of the title.
                     
                    #Defines what the menu for playing again looks like.
                    title_2 = "**Do you want to play again?**" #Defines the title.
                    men_list_2 = ["1. Play again", "2. Exit"] #Defines the options the user has.
                     
                    #Loops for the length of the list.
                    for i in range(0, len(men_list_2)):
                        print(men_list_2[i]) #Prints.
         
                    print("-" * len(title_2)) #Prints _ the length of the title.
                    print("")
                     
                    choose_2 = int(input("What is your choice? ")) #Asks for player input.
                     
                    #Defines what will happen if the player chooses option 1.
                    if choose_2 == 1:
                        import time
                        print("")
                        print("Restarting Game")
                        print("Redirecting to menu.")
                        time.sleep(1)
                        print("...")
                        print("Loading Code.")
                        time.sleep(1)
                        print("...")
                        print("Reseting Variables.")
                        time.sleep(1)
                        print("...")
                        print("Wasting some time.")
                        time.sleep(1)
                        print("...")
                        print("Running Functions.")
                        time.sleep(2)
                        print("...")
                        print("")
                        time.sleep(1)
                        dis_menu() #Starts the menu again. #THIS HAS BEEN CHANGED
                         
                    #Defines what will happen if the player chooses option 2.
                    if choose_2 == 2:
                        print("")
                        print("Ok!")
                        print("Thanks for playing!")
                        print("")
                        print("Please come back soon!")
 
    #Calls on the code for each operation, depending on user input.
main()
Now for calculating the amount of time taken

from datetime import datetime
start = datetime.now()

#The addition quiz loop

end = datetime.now()

time_taken = (end-start).total_seconds()
that will give you the time taken for that function. you can put that when you start the function or when you start the loop.

Just saying, your structure is very illegibal. I would recommend you restructure the whole thing. Ask me for assistance if you need it. :)
Don't doubt always question. There's a difference.
Reply
#3
Thank you very much! I was aware that this is not the umm... recommended way of programming... But this was the way I was taught... I started python about a week and a half ago, so any help is much appreciated! What you are saying to do is restructure it so that it has many functions that call on each other. Is the aim to try and reduce the number of functions in each other?

Also... What IDE would you recommend using?
I am currently using anaoconda spyder...

I will post again when I get some more done, and if I have any troubles.
Reply
#4
(Mar-28-2018, 02:20 AM)groovydingo Wrote: Thank you very much! I was aware that this is not the umm... recommended way of programming... But this was the way I was taught... I started python about a week and a half ago, so any help is much appreciated! What you are saying to do is restructure it so that it has many functions that call on each other. Is the aim to try and reduce the number of functions in each other? Also... What IDE would you recommend using? I am currently using anaoconda spyder... I will post again when I get some more done, and if I have any troubles.

Hey sorry for the really late reply. But do you use discord or something? I can help you out more if we can chat live. I use Visual Studio Code its a great text editor and I use the powershell to execute the script (In windows).
Don't doubt always question. There's a difference.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python variable and function usage at a time prasanthbab1234 14 5,105 Sep-24-2020, 01:48 PM
Last Post: prasanthbab1234
  traverses directory recursively and displays files Prani05 7 3,338 Apr-30-2020, 10:25 AM
Last Post: snippsat
  Program that displays the number with the greatest amount of factors ilusmd 3 2,810 Nov-01-2018, 08:28 PM
Last Post: ichabod801
  creating date/time stamp from dataframe values kiki1113 1 2,502 Dec-06-2017, 05:43 PM
Last Post: gruntfutuk
  Creating a file with variable name but distinct extension Moeniac 1 2,247 Nov-27-2017, 05:47 PM
Last Post: DeaD_EyE
  Homework that displays different weights Schmitlab 4 3,311 Oct-21-2017, 10:39 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020