英文:
How to make the def function work in a if statement?
问题
我是 Python 新手,正在制作一个基于文本的冒险游戏。为了增加趣味性,我找到了这个文本效果:
```python
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.03)
delay_print("Hello World")
所以我试图让这个脚本在 if 语句中起作用。在 if 语句外部,它完美运行,但一旦我把它放到 if 语句中,这个定义就不起作用了。VSC 没有显示错误,但什么都没有发生。
这是不起作用的脚本:
choice = input("left or right? ")
if choice == "left":
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.03)
delay_print("Left")
英文:
I am new to python and i am making a text based adventure game, to make it more interesting instead of printing the questions normally i found a text effect shown here
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.03)
delay_print("Hello World")
So i am trying to make this script work within an if statement. it works perfectly outside a if statement but the second i put it into a if statement the def stops working. VSC does not show an error but nothing happens
here is the script that does not work
choice = input("left or right? ")
if choice == ("left"):
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.03)
delay_print("Left")
答案1
得分: 1
- 你应该把导入语句放在你的脚本顶部。
- 在循环之外定义
display_print
函数,并在if语句中调用它。(没有必要在if语句内定义函数,你可以直接在那里调用它。)
这应该可以工作:
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.03)
choice = input("左还是右?")
if choice == "左":
delay_print("左")
英文:
- You should put the import statements at the top of your script.
- Define the
display_print
function outside the for loop and call it in the if statement. (There is no reason to define the function inside the if statement, you can just call it there.)
This should work:
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.03)
choice = input("left or right? ")
if choice == "left":
delay_print("Left")
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论