pythondice

Python dice roll game


I'm making a dice game on python and I'm having an issue. "/roll1" and "/roll2" works perfectly but when I try "/score" it outputs nothing. How can I fix this?

#Autharisation
# password is any integer
while True:
    try:
        pass_word = int(input("Please enter the password: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
    else:
        break

#Game

import random
def rolldie():
    
    inputChoice = input("Enter Choice: ")
    
    roll1 = ""
    if(inputChoice == "/roll1"):
      roll1  = random.randint(1,6)
      print("Nice roll! You rolled a {}!".format(roll1) )
      
        
    roll2 = ""
    if(inputChoice == "/roll2"):
      roll_2 = random.randint(1,6)
      print("Nice roll! You rolled a {}!".format(roll_2) )

    elif(inputChoice == "/score"):
      print(roll1 + roll2 ) 


    rolldie()
rolldie()

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ


Solution

  • If you want to keep your function recursive, you have to pass your results from an execution to the next one, thanks to function parameters, for example:

    import random
    def rolldie(roll1=0, roll2=0):
        
        inputChoice = input("Enter Choice: ")
        
        if(inputChoice == "/roll1"):
          roll1  = random.randint(1,6)
          print("Nice roll! You rolled a {}!".format(roll1) )
          
        if(inputChoice == "/roll2"):
          roll2 = random.randint(1,6)
          print("Nice roll! You rolled a {}!".format(roll2) )
    
        if(inputChoice == "/score"):
          print(roll1 + roll2) 
    
        rolldie(roll1, roll2)
        
    rolldie()
    

    You could also use a loop instead of the recursive way or use global variables but that is generally not the best option