gpt4 book ai didi

python - 带有是/否输入的 While 循环 (Python)

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:15 24 4
gpt4 key购买 nike

我正在构建一个脚本来绘制平滑值和绘图值。但是,我无法获得控制 while 循环的是/否函数。

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

我收到“NameError: name 'reply' is not defined.”

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")

当我调整 reply[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")

最佳答案

尝试:

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
$

关于python - 带有是/否输入的 While 循环 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com