[英]Asking user (yes/no) question of whether to show a plot. Using (if/else) statements to run block of graphing code or not
I want to ask a user if they would like to see a certain graph.我想问用户是否想看某个图表。 If they say "yes," I want my block of plot code to run.
如果他们说“是”,我希望我的情节代码块能够运行。 If they say "no," I want it to return
None
and go to the next question.如果他们说“不”,我希望它返回
None
并转到下一个问题。
When I run my cell and input a 'yes'
it just goes to the next question.当我运行我的单元格并输入
'yes'
时,它就会转到下一个问题。 The plot code works outside of the if
statement.情节代码在
if
语句之外工作。 I am on a mac using Jupyter Notebook, running an Anaconda supported Python environment.我在 Mac 上使用 Jupyter Notebook,运行 Anaconda 支持的 Python 环境。
yeses=['yes','Yes','YES','y','Y']
nos=['no','No','NO','n','N']
p = input("Would you like to see the signal pattern of the song? (yes/no): ")
f = input("Would you like to see a plot of all the frequencies used in this song? (yes/no): ")
s = input("Would you like to see a spectrogram of the song? (yes/no): ")
if p in yeses:
plt.subplot(2,1,1)
plt.plot(time, sound[:,0], 'r')
plt.xlabel("time, s [left channel]")
plt.ylabel("signal, relative units")
plt.subplot(2,1,2)
plt.plot(time, sound[:,1], 'b')
plt.xlabel("time, s [right channel]")
plt.ylabel("signal, relative units")
plt.tight_layout()
plt.show()
else:
return None
I assume you typed: yes CTRL-ENTER我假设你输入了:是的 CTRL-ENTER
Maybe you received "yes\n"
?也许你收到了
"yes\n"
? Use repr(p)
to diagnose, and p.rstrip()
to fix, stripping any trailing newlines.使用
repr(p)
进行诊断,使用p.rstrip()
进行修复,去除任何尾随的换行符。
You wrote你写了
yeses = ['yes', 'Yes', 'YES', 'y', 'Y']
You could more concisely use你可以更简洁地使用
yeses = ['yes', 'y']
and rely on p.lower()
to uniformly downcase all user inputs.并依靠
p.lower()
统一缩小所有用户输入。
Write a tiny helper function if the code does that repeatedly.如果代码重复执行此操作,请编写一个小的辅助函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.