-3

I have trouble understanding these lines of codes:

return (0, user, computer)        
return (-1, user, computer)

My question: what does 0, -1, and 1 mean? How can () have three items inside?

Thanks very very much!I'm a beginner. Much help is needed and appreciated.

the original code is below:

def play():
    user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors\n")
    user = user.lower()

    computer = random.choice(['r', 'p', 's'])

    if user == computer:
        return (0, user, computer)         #?????????????????

    # r > s, s > p, p > r
    if is_win(user, computer):
        return (1, user, computer)

    return (-1, user, computer)
jss367
  • 2,887
  • 4
  • 40
  • 62
  • 3
    This is a [tuple](https://docs.python.org/3/library/stdtypes.html#typesseq). These questions and answers might help: https://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python https://stackoverflow.com/questions/354883/how-do-i-return-multiple-values-from-a-function – Stuart Jul 29 '20 at 02:34
  • The function is returning a data structure known as a "tuple". Here's an example of what it can do: https://www.programiz.com/python-programming/tuple – jss367 Jul 29 '20 at 02:34
  • 1
    As for what do the numbers mean, that's a program logic thing (they have no intrinsic meaning), but I'm assuming it's indicating tie, user lost or user won for 0, -1 and 1 respectively. – ShadowRanger Jul 29 '20 at 02:38
  • worth noting that this is really strange code. You shouldn't expect to write things that look like this. – Adam Smith Jul 29 '20 at 02:41
  • Use of this tuple to represent the end state is something I'd expect to be a stand-in for a real solution that involves a custom `Result` object or etc – Adam Smith Jul 29 '20 at 02:43
  • 1
    @AdamSmith: A `collections.namedtuple` would be the usual approach (as code that relied on the `tuple` would still work, and new code could access named attributes if it preferred). – ShadowRanger Jul 29 '20 at 23:33
  • @ShadowRanger yup, or a new-fangled dataclass – Adam Smith Jul 30 '20 at 00:32

2 Answers2

1

To answer your questions first:

what does 0, -1, and 1 mean?

0 : draw; 1 : user wins; -1: user loses (computer wins)

How can () have three items inside?

in python, when you put the things you return between parenthesis, you are returning a tuple.

To sum up, this code asks the user to choose (rock, paper, scissors) then the computer randomly chooses one too. The two choices are then sent to is_win which decides the game outcome.

m_martini
  • 29
  • 5
0

Here, -1 means the user lost, 0 means it's a draw, and 1 means the user won. () stands for a tuple, a type of data structure that's a iterable. The return statement can return any type of object in Python.

See: Python docs on tuples

David
  • 638
  • 2
  • 14