0
#1
def hit_stay():
    hit_stay = ''
    while True:
        hit_stay = input('Would you like to Hit or Stay?')
        if hit_stay in ['hit','Hit','stay','Stay']:
            hit_stay = hit_stay.capitalize()
            return hit_stay
        else:
            print('Please enter a valid word)

#2
When I use the code and call the function it works the first time 
hit_stay = hit_stay()

#3
Then I print the choice
print(hit_stay)

However if I try and call number 2 again to get a different choice it says 'str' not callable Im trying to ask the user for a choice in order to use that choice later in my code. I found of that if run number 1 again then number 2 everything works ok but I need to be able to call this function later and get a new answer.

  • 1
    You can't call the function again after you assigned something else [in this particular case - the returning value] to the variable which has the same name, eg I have a function named XYZ, I did XYZ = XYZ(); now XYZ will not contain the function anymore but the value that returned from XYZ, you got to rename the line `hit_stay = hit_stay()` to something else, anything but `hit_stay`. – Jonathan1609 Jun 30 '21 at 21:46
  • @Jonathan1609 You should post this as an answer. The existing answer doesn’t actually answer the question. – itroulli Jul 01 '21 at 01:28

2 Answers2

0

Functions in python are "first-class" objects. You can think of a function as if it were any other variable.

So, when you say hit_stay = hit_stay(), the variable hit_stay no longer points to a function (because you called it the same name as the function). It points to the result of hit_stay(), which is a string (either "HIT" or "STAY").

The second time you try to call it, it's as if you were trying to "call" a string (hence the error).

Also, as a suggestion, it looks likely that you're returning "HIT" or "STAY" so that somewhere else in you code you will have something like:

if ... == "HIT":
    # Do 'hit' stuff

You might find it useful looking into something like enum. IMO makes it cleaner and more maintainable. That would look like:

from enum import Enum


class Action(str, Enum):
    HIT = "HIT"
    STAY = "STAY"


def hit_stay() -> Action:
    while True:
        action = input("Would you like to Hit or Stay?")
        try:
            return Action(action.upper())
        except ValueError:
            print("Please enter a valid word")

action = hit_stay()
if action == Action.HIT:
    # do 'hit' stuff ... 
NikT
  • 1,590
  • 2
  • 16
  • 29
0

You can't call the function again after you assigned something else [in this particular case - the returning value] to the variable which has the same name, eg I have a function named XYZ, I did XYZ = XYZ()

now XYZ will not contain the function anymore but the value that returned from XYZ, you got to rename the line hit_stay = hit_stay() to something else, anything but hit_stay

Jonathan1609
  • 1,809
  • 1
  • 5
  • 22