-7

why the assign() function does not change the string into integer? the assign function does not return the values i set in if statement!

p1 = raw_input("Player 1 ?")
p2 = raw_input("Player 2 ?")

def assign(n):

    if n == "r":
        return (1)
    elif n == "s":
        n = 2
    elif n == "p":
        n = 3
    else:
        print "Wrong input!"
    return n

assign(p1)
assign(p2)
print p1
print p2

if p1 - p2 == 0:
    print "Tie!"
elif (p1 - p2) / 2 != 0:
    print " Player 1 is winner!"
else:
    print" Player 2 is the winner!"
Sasan
  • 17
  • 8
  • What's the input and output you're getting, and what is the output you expect? – TheSoundDefense Jul 26 '14 at 20:49
  • 1
    Your `assign` function might be called `assign` but it does not `assign` a new value to the variable _outside_ of `assign`. – tobias_k Jul 26 '14 at 20:50
  • 1
    Python assignment does **not** work like that. See e.g. http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables – jonrsharpe Jul 26 '14 at 20:51
  • 2
    I always wonder why new users think that it is best to put the entire question in the title, then only put code in the question body. – SethMMorton Jul 26 '14 at 21:00
  • http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference is essentially what you're asking. – Wooble Jul 26 '14 at 22:50

1 Answers1

1

The variable n inside the function is distinct from the expression (or variable) supplied as an argument. As such, assigning to n inside the function will not affect any of the variables outside. (This is because Python is not Call By Reference.)

Instead, use the return value, eg.

def classifyInput(n):    
    if n == "r":
        return 1
    elif n == "s":
        return 2
    elif n == "p":
        return 3
    else:
        print "Wrong input!"
        # implicit: return None

p1_inp = raw_input("Player 1 ?")
p1 = classifyInput(p1_inp)
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • great! thanks a lot. i see your point. its working. sorry if my post is cluttered. i'm pretty new to coding and this website ! – Sasan Jul 26 '14 at 21:17
  • also i wrote this script to make rock scissor paper game. will be happy if you let me know i'm approaching this in a right way – Sasan Jul 26 '14 at 21:20
  • @user3880531 I would actually leave the original r/p/s values (there is no need to turn them into numbers). See http://stackoverflow.com/a/14892086/2864740, http://stackoverflow.com/questions/23585417/reducing-if-statements-in-a-pokemon-element-type-system/23585577#23585577 and similar questions for how an ordering can then be established (I think that a lookup does really well in this case, but it can also be done with if-else statements) – user2864740 Jul 26 '14 at 21:21
  • i see . yeah its smarter to do that! – Sasan Jul 26 '14 at 21:30