Yossi Gershon Yossi Gershon - 2 months ago 16
Python Question

How do I use raw input inside a function

I have scoured the forum trying to find a good way to make a function that takes raw input and uses it.
This is my code:
#Rolling for Agility

print "Roll for Agility"
def Rolling(a, b, value):
in1 = raw_input()
if in1 == 'roll':
irand = randrange(a, b)
elif in1 == 'Roll':
irand = randrange(a, b)
else:
print "Please Type <roll> in order to roll the dice."
Rolling ()
print "Your %d is %d" % (value, irand)


Rolling(1, 10, Agility)

It's supposed to take the numbers for the rolling range, and the number in the roll is inserted into a value (Agility in this case).

The code doesn't work because there's a problem with the raw input and the arguments put inside "Rolling function". I want the function not only to take raw input but also process it. I don't want to make raw input before the function and later add it manually into the function by putting the raw input into a string or int.

Thanks in advance!

Answer

The code has some typos. Error message NameError: name 'value' is not defined is generated because that statement has been mistakenly put outside the Rolling function body where value is not defined.

Corrected code should look like:

#Rolling for Agility
from random import randrange
print "Roll for Agility"
def Rolling(a, b, value):
    in1 = raw_input()
    if in1 == 'roll' or in1 == 'Roll':
        irand = randrange(a, b)
        print "Your %s is %d" % (value, irand) 
    else: 
        print "Please Type <roll> in order to roll the dice."
        Rolling(a,b,value) # using recursion to call again incase of erroneous input 


Rolling(1, 10, "Agility")
Comments