-1

What is the root of the error I get when running this function and why? The error I get is "name 'one' is not defined". I did define it though?

def One():
    one = input("Type something: ")

def Two(one):
    One()
    print(one)

Two(one)
  • You only defined it in the function `One`. You need to define it outside of the function to be accessible everywhere. – chrisbyte Oct 20 '22 at 19:40

3 Answers3

1

one is defined, and therefore only visible inside the One() method.

You could get around this by using a global:

# This is our global
one = None

def One():
    global one
    one = input("Type something: ")

def Two():
    global one
    print(one)

Two()

or better yet, to return the value from One()

def One():
    one = input("Type something: ")
    return one

def Two():
    one = One()
    print(one)

Two()
Luiz
  • 148
  • 1
  • 9
0

When you first run the program, the two functions are ignored and the first line to be executed is line 8, Two(one). The function 'Two' does exist however the parameter for it has not been defined yet.

jacob_a26
  • 1
  • 1
0

A variable created within a function is only scoped to that function. You have a separate variable named one defined within function Two(one), but it is a parameter that needs to be passed in when Two() is called.

The global suggestion given works, or you could have function One() return the value the user entered, and then print that value.

def One():
    return input("Type something: ")

def Two():
    user_input = One()
    print(user_input)

Two()
nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12