1
I am learning Python on my own and in many videos and subjects programmers advise and emphasize the importance of "clean and organized codes". So I’m trying to create classes and functions in separate files to then import them and use them in a main file, but I find the following problem:
In a separate file (Functions.py for example) I created a function that asks a question and stores it in a global variable:
def Pergunta(X):
global Resposta
Resposta = input(X)
Let’s say, now, that I want to print a greeting inside this very file:
def Pergunta(X):
global Resposta
Resposta = input(X)
print('Sejam bem-vindos, {}!'.format(Resposta))
Doing this, if the name is "Fulano"
the program returns:
'Sejam bem-vindos, Fulano!'
Now my question: if, in another file, I import that same function by adding the variable Resposta = ''
, as follows:
from Funções import Pergunta
Resposta = ''
Pergunta('Qual é o seu nome?')
print('Sejam bem-vindos, {}'.format(Resposta))
The result is that the program does not recognize the input
that I would like to assign (even if I mark the variable as global) and return:
'Sejam bem-vindos, !'
If possible, can anyone explain to me why this happens when I import the function to a new file or how I can get this result correctly?
Thank you for your attention.
Instead of relying on a global variable, I think it makes more sense for the function to simply return the entered value. More or less: https://ideone.com/iHfYok
– hkotsubo
Good evening, hkotsubo, thank you for your attention! So... I saw the file and this approach even works, but my question is whether it works when I import the function to another code/file.py
– Lehetex
Yes, it works: https://repl.it/repls/DenseSunnyProprietarysoftware
– hkotsubo
Sorry for the delay. I finally got to sit down to test and this approach actually worked. I appreciate the help! There was doubt about what happens to variables in this case, but I will take some time to study further. Very grateful!
– Lehetex