pythonrandomnonetypedice

Python Random Int Generation returning 'None' instead of a integer


I have a very simple dice rolling program, with the main body of the program here.

import random
from time import sleep

rounds = 5
delay = 1

playerTwoScore = 30
playerOneScore = 20

def roll():
 rollOne = random.randint(1,6)
 rollTwo = random.randrange(1,6)
 if rollOne == rollTwo:
   score = (rollOne + rollTwo) * 2
 else:
   score = rollOne + rollTwo
   return score


for i in range(rounds):
 playerOneRoll = roll()
 print("Player 1 rolled a",playerOneRoll)
 playerOneScore = int(playerOneScore) + int(playerOneRoll)
 print("Player 1's total score is",playerOneScore)
 print("----------------------------")
 sleep(delay)
 roll()
 playerTwoRoll = roll()
 print("Player 2 rolled a",playerTwoRoll)
 playerTwoScore = int(playerTwoScore) + int(playerTwoRoll)
 print("Player 2's total score is",playerTwoScore)
 print("----------------------------")
 sleep(delay)

It works fine for a couple rounds but then sometimes the player one roll will return as None and the program will end due to an error. Can't figure out why. The image of the output:

output

Any comments or ideas about this would help a lot - many thanks.


Solution

  • You need to return something for the "equal" possibility

    Otherwise, on the 1/6 of occasions with equal rollOne and rollTwo, the function will return without a value, i.e. None.

    Also there is no need to do the extra roll

    You aren't storing the result.

    Fixed code:

    
    rounds = 10
    delay = 1
    import random
    from time import sleep
    playerOneScore = 0
    playerTwoScore = 0
    
    def roll():
     rollOne = random.randint(1,6)
     rollTwo = random.randrange(1,6)
     if rollOne == rollTwo:
       return (rollOne + rollTwo) * 2  # <---- Need to return this
     else:
       return rollOne + rollTwo
    
    
    for i in range(rounds):
     playerOneRoll = roll()
     print("Player 1 rolled a",playerOneRoll)
     playerOneScore = int(playerOneScore) + int(playerOneRoll)
     print("Player 1's total score is",playerOneScore)
     print("----------------------------")
     sleep(delay)
     roll()           #     <---- not needed
     playerTwoRoll = roll()
     print("Player 2 rolled a",playerTwoRoll)
     playerTwoScore = int(playerTwoScore) + int(playerTwoRoll)
     print("Player 2's total score is",playerTwoScore)
     print("----------------------------")
     sleep(delay)