Python函数和变量的麻烦 [英] Python functions and variables trouble
问题描述
到目前为止,我已经创建了此代码...
def print_slow(str):对于str中的字母:sys.stdout.write(字母)sys.stdout.flush()time.sleep(0.005)def menu():print_slow("------------- [MENU] -------------")打印(" ")print_slow("1)输入一个句子.")打印(" ")print_slow("2)查找单词的位置.")打印(" ")print_slow("--------------------------------")打印(" ")print_slow(>>>")选择= str(input(")))打印(" ")time.sleep(0.5)如果选择=="1":选项1()如果选择=="2":option2()def option1():print_slow(输入句子")句子= str(input(:"))打印(" ")菜单()def option2():如果不是句子:print_slow(请先输入一个句子!")time.sleep(0.5)打印(" ")别的:句子Uppercase =句子.upper()[代码继续...]
基本上,当我测试它时,我首先按下选项2,它应该给出输出请先输入一个句子!".
然后我按菜单中的选项1,它会提示我输入一个句子(我把我的名字叫鲍勃"作为测试),并且确实如此.
我在输入句子后按了选项2,它应该继续输入我的代码-而是显示错误消息请先输入句子!" >
我该如何解决?
您正在函数 option1
中设置 local 变量 sentence
.该变量在 option2
中不可见,因为它仅位于 option1
内部,并且在 option1
完成后将被清除.
如果要共享变量,则需要至少在 option1
中将其定义为 global
:
def option1():print_slow(输入句子")全局句句子= str(input(:"))打印(" ")菜单()
但是请注意,使用全局变量通常是不良代码质量的标志.在您的情况下,让 option1
返回 sentence
到 main
并从 main
传递它会更有意义.到 option2
.
I have created this code so far...
def print_slow(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.005)
def menu():
print_slow("-------------[MENU]-------------")
print(" ")
print_slow("1) Enter a sentence.")
print(" ")
print_slow("2) Find the position of a word.")
print(" ")
print_slow("--------------------------------")
print(" ")
print_slow(">>> ")
choice = str(input(" "))
print(" ")
time.sleep(0.5)
if choice == "1":
option1()
if choice == "2":
option2()
def option1():
print_slow("Enter sentence")
sentence = str(input(": "))
print(" ")
menu()
def option2():
if not sentence:
print_slow("Please enter a sentence first!")
time.sleep(0.5)
print(" ")
else:
sentenceUppercase = sentence.upper()
[code goes on...]
Basically when I test it, I press option 2 first and it should give the output 'Please enter a sentence first!', which it does.
I then press option 1 in the menu and it should prompt me to input a sentence (I put 'my name is bob' as a test) and it does.
I then pressed option 2 after inputting the sentence and it should continue with my code - instead it gives the error message 'Please enter a sentence first!'
How can I fix this??
You're setting a local variable sentence
inside function option1
. This variable is not visible in option2
since it lives inside option1
only and will be cleaned up once option1
is finished.
If you want to share the variable, you need to define it as global
at least in option1
:
def option1():
print_slow("Enter sentence")
global sentence
sentence = str(input(": "))
print(" ")
menu()
Note, however, that using global variables is usually a sign of bad code quality. In your case, it would make more sense to have option1
return sentence
to main
, and pass it from main
to option2
.
这篇关于Python函数和变量的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!