0

Can someone please explain what I'm doing wrong?

My code come's up as x not defined. What i'm trying to do is get the result of x in add1 and pass it to the doub function. I have searched and read up on this as much as possible, I know I am missing something simply so please point me in the right direction.

def main():
    value = (int)(input('Enter a number '))
    add1(value)
    doub(x)

def add1(value):
    x = value + 1
    return x


def doub (x):
    return x*2

main()
4
  • also, (int)(input('Enter a number ')) looks too much like c. int(input('Enter a number ')) is much more normal in python code. Commented Mar 16, 2016 at 16:14
  • Why not just return value + 1? Commented Mar 16, 2016 at 16:15
  • x only exists as a name for an object in the scope of add1. You return the object, and would need to assign another name for it outside of add1 if you ever want to talk about its value again. Commented Mar 16, 2016 at 16:16
  • 1
    in main() x is not defined. You need something like this: x = add1(value) Commented Mar 16, 2016 at 16:18

2 Answers 2

2

x only exists within the add1 function. All your main function knows is the value that's returned from calling add1, not the name of the variable it was previously stored in. You need to assign that value to a variable, and pass that into doub:

result = add1(value)
doub(result)

Also note, Python is not C; there's no such thing as typecasting. int is a function that you call on a value:

value = int(input('Enter a number '))
Sign up to request clarification or add additional context in comments.

1 Comment

'Also note, Python is not C; there's no such thing as typecasting. int is a function that you call on a value: value = int(input('Enter a number '))' ------------ Noted. Btw thx for ur response.
0

Try this:

def main():
    value = int(input('Enter a number '))
    #This is more pythonic; use the int() function instead of (int)         
    doub(add1(value))

def add1(value):
    x = value + 1
    return x


def doub (x):
    return x*2

main()

3 Comments

hi linusg,thx for your response, i tried this and after i input a number nothing but >>> shows up.
Yes, that's because you have no print statement in your code. Try replacing doub(add1(value)) with print(doub(add1(value)))
You are right, this did work. Thank you very much for your help it is greatly appreciated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.