简体   繁体   中英

Python, Calling a function again based on input from user

I'm trying to get back to the roll_die function within take_turn function after the user enters "y", then continue adding value to turn_score variable. Can anyone see what I'm doing wrong? Thanks in advance, here's my code so far:

import random
def roll_die():
    roll_value = random.randint(1,6)
    return roll_value

def take_turn(is_human_turn):
    roll_die()
    roll = roll_die()
    turn_score = 0
    turn_score = turn_score + roll

    if is_human_turn:
        print("total so far:",turn_score)
        input("roll again? y/n ")
        if input == "y":
            roll_die()
        # Trying to get back to the roll_die func w/in take_turn func
        #  and continue adding value to turn_score

    return turn_score

take_turn(True)

I suggest you to:

  1. Gather the 3 first lines of take_turn() function into turn_score = roll_die()
  2. Use while loop to roll again until user enters something different from "y"
  3. Add the value returned by roll_die() to turn_score
  4. Do something with the value returned by take_turn() (otherwise do not return anything)

Here is my full code solution:

import random

def roll_die():
    roll_value = random.randint(1,6)
    return roll_value

def take_turn(is_human_turn):
    turn_score = roll_die()
    while is_human_turn:
        print("total so far:", turn_score)
        if input("roll again? y/n ") == "y":
            turn_score += roll_die()
        else:
            is_human_turn = False
    return turn_score

result = take_turn(True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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