如何使def函数在if语句中工作?

huangapple go评论60阅读模式
英文:

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

  1. 你应该把导入语句放在你的脚本顶部。
  2. 在循环之外定义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("左")
英文:
  1. You should put the import statements at the top of your script.
  2. 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>



huangapple
  • 本文由 发表于 2023年5月25日 12:01:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定