EmilianSpo - 1 year ago 65

Python Question

I've searched and this has been answered a lot already, but it mostly had to do with version errors. I checked my Python version (it's 3.4.2) but it still returns the error.

Code w/ error:

`import random`

def start():

rannum = random.randint(0, 20)

inpnum = int(input('Please enter a number between 0 and 20: '))

calc()

def loop():

inpnum = int(input('Please enter a number between 0 and 20: '))

calc()

def calc():

if inpnum > rannum:

print('The number you entered is too high.')

loop()

if inpnum < rannum:

print('The number you entered is too low.')

loop()

if inpnum == rannum:

print('Congratulations! You guessed the number!')

input('')

start()

This returns the error code:

`Traceback (most recent call last):`

File "guessthenumber.py", line 26, in <module>

start()

File "guessthenumber.py", line 6, in start

calc()

File "guessthenumber.py", line 14, in calc

if inpnum > rannum:

NameError: name 'inpnum' is not defined

I tried to fix it myself and changed it to look like this:

`import random`

def loop():

inpnum = int(input('Please enter a number between 0 and 20: '))

calc()

def calc():

rannum = random.randint(0, 20)

inpnum = int(input('Please enter a number between 0 and 20: '))

if inpnum > rannum:

print('The number you entered is too high.')

loop()

if inpnum < rannum:

print('The number you entered is too low.')

loop()

if inpnum == rannum:

print('Congratulations! You guessed the number!')

input('')

calc()

It does work but it keeps making a new number (I think I know why, the rannum = random.randint(0, 20) keeps making up a new number every time) and it asks you for an input number twice (because it already asks for one at loop() but does so again in calc(), I think) so you have to randomly guess until you have it right because it keeps changing every guess.

To me it looks like complete Python code. Does anyone else know what to do here?

Answer Source

One solution would be to change your calc function to accept an arguemnt:

```
def calc(num):
# do stuff with num
```

and pass `ipnum`

into it:

```
def loop():
inpnum = int(input('Please enter a number between 0 and 20: '))
calc(inpnum)
```

This is how you make use of local variables in one function in another function.