While循环,有/无输入(Python)

2024-04-29 14:05:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个脚本来绘制平滑和绘制值。但是,我无法使用yes/no函数来控制while循环。

我将while条件设置为“N”,并等待用户在退出之前说他们喜欢绘图(输入Y)。

我收到一个“NameError:name'reply'未定义。”

import matplotlib.pyplot as plt
import numpy

while True:
    reply[0] = 'n'
    def yes_or_no(question):
        reply = str(input(question+' (y/n): ')).lower().strip()
        if reply[0] == 'y':
            return 1
        if reply[0] == 'n':
            return 0
        else:
            return yes_or_no("Please Enter (y/n) ")

# a bunch of math
# plots for the user

yes_or_no('Do you like the plot')
break
print("done")

当我调整回复[0]以回复程序挂起时(见下文)

print("started")
while True:
    reply = 'n'
    def yes_or_no(question):
        reply = str(input(question+' (y/n): ')).lower().strip()
        if reply[0] == 'y':
            return 1
        if reply[0] == 'n':
            return 0
        else:
            return yes_or_no("Please Enter (y/n) ")

yes_or_no('Do you like the plot')
print("done")

Tags: orthenoimporttruereturnifdef
3条回答

尝试:

def yes_or_no(question):
    reply = str(input(question+' (y/n): ')).lower().strip()
    if reply[0] == 'y':
        return 1
    elif reply[0] == 'n':
        return 0
    else:
        return yes_or_no("Please Enter (y/n) ")

print("started")
while True:
    # DRAW PLOT HERE;
    print("See plot....")
    if(yes_or_no('Do you like the plot')):
        break
print("done")

为了清晰起见,最好将函数定义与循环分开。另外,否则它将在每个循环中被读取,浪费资源。

输出:

$ python ynquestion.py 
started
See plot....
Do you like the plot (y/n): n
See plot....
Do you like the plot (y/n): N 
See plot....
Do you like the plot (y/n): NO
See plot....
Do you like the plot (y/n): No
See plot....
Do you like the plot (y/n): no
See plot....
Do you like the plot (y/n): yes
done
$
def yes_or_no(question):
    while True:
        answer = input(question + ' (y/n): ').lower().strip()
        if answer in ('y', 'yes', 'n', 'no'):
            return answer in ('y', 'yes')
        else:
            print('You must answer yes or no.')

yes_or_no('Do you like the plot?')

你应该看看一些关于“如何编码”的教程。有几个“误解”。不过,这里有一个更干净的版本:

import matplotlib.pyplot as plt
import numpy

def bunch_of_math():
    ...

def plotting():
    ...

# move this into the loop in case you want to calc and plot
# new stuff every iteration
bunch_of_math()
plotting()

print("start")

while True:
    reply = str(input(question+' (y/n): ')).lower().strip()
    if reply == 'y':
        break
    elif reply == 'n':
        break
    else:
        print("please select (y/n) only")
        continue

print("done")

在循环中声明函数是不好的风格,特别是在不需要这样做的情况下。您的代码将在每次迭代时重新创建函数,只有在每次迭代中以某种方式更改函数时才需要这样做。

reply[0] = 'n'意味着您想使用索引0访问列表或数组(容器数据结构)reply,并在其中写入'n'。您尚未初始化此类容器。此外,您根本不需要容器,因为您不存储每个用户输入。您只需要关心用户的最新答案->;一个变量就足够了。

if reply[0] == 'y':
    return 1
if reply[0] == 'n':
    return 0
else:
    return yes_or_no("Please Enter (y/n) ")

有两个if条件:Python将检查== 'y',然后总是再次检查== 'n'。您需要使用elif来声明else if条件,否则会浪费资源或遇到意外行为。此外,您从未使用返回值。while循环只是用break语句退出,因为它是一个循环。因此,您的return语句是没有意义的。

相关问题 更多 >