-1

I created a file

#name file ask.py
def ask_name():
    user = input("What is your name?: ")

and i imported it

import ask
ask.ask_name()
print(user)

but python tells me that "user" is not defined.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • 1
    so many ways this can be done...but you'll probably want to add `return user` in `ask.py` module, then it would be possible to define "user" by changing that line to `user = ask.ask_name()` then your print statement will work. – chickity china chinese chicken Apr 21 '17 at 23:43

2 Answers2

3

It's not: user is a variable internal to ask_name, not an attribute of ask. Try this:

#name file ask.py
def ask_name():
    user = input("What is your name?: ")
    return user

# Main file
import ask
local_input = ask.ask_name()
print(local_input)
Prune
  • 76,765
  • 14
  • 60
  • 81
0

the user variable "lives" only inside the 'ask_name` function (read this excellent post to learn more about variable scope), so it's undefined within the main script. you can have the function return the user's input, and print that returned value.

#name file ask.py
def ask_name():
    return input("What is your name?: ")

# Main file
import ask
print(ask.ask_name())
Community
  • 1
  • 1
teknoboy
  • 175
  • 1
  • 2
  • 12