提示用户在 Python 中输入的问题 [英] Problems prompting user for input in Python
问题描述
import sys
import turtle
t=turtle.Pen
def what_to_draw():
print ("What to do you want to see a sketch of that may or may not be colored?")
what_to_draw=sys.stdin.readline()
if what_to_draw=="flower/n":
t.forward(90)
elif():
print ("What you typed isn't in the code. Try putting a letter or letters to lowercase or uppercase. If that doesn't work, what you typed has not been set to make something happen")
我在上面输入了这段代码.它在 python shell 中说花"没有定义.有人可以帮我解决这个问题吗?
I typed in this code above. It says in the python shell "flower" isn't defined. Can someone figure this out for me?
推荐答案
您的几行代码存在某种错误:
Several lines of your code have errors of some sort:
t=turtle.Pen
应该是:t = turtle.Pen()
你应该避免使用同名的函数和变量
You should avoid functions and variables with the same name
def what_to_draw():
...
what_to_draw = sys.stdin.readline()
使用 rstrip() 处理 "\n" 和 .lower() 处理大小写:
Use rstrip() to deal with "\n" and .lower() to deal with case:
if what_to_draw == "flower/n":
elif():
需要某种条件,否则使用 else:
elif():
requires a condition of some sort otherwise use else:
让我们尝试不同的方法.不要将控制台窗口输入与海龟图形混合在一起,让我们尝试使用 Python 3 海龟新增的 textinput()
函数从海龟内部执行所有操作:
Let's try a different approach. Instead of mixing console window input with turtle graphics, let's try to do everything from within turtle using the textinput()
function that's new with Python 3 turtle:
from turtle import Turtle, Screen
def what_to_draw():
title = "Make a sketch."
while True:
to_draw = screen.textinput(title, "What do you want to see?")
if to_draw is None: # user hit Cancel so quit
break
to_draw = to_draw.strip().lower() # clean up input
if to_draw == "flower":
tortoise.forward(90) # draw a flower here
break
elif to_draw == "frog":
tortoise.backward(90) # draw a frog here
break
else:
title = to_draw.capitalize() + " isn't in the code."
tortoise = Turtle()
screen = Screen()
what_to_draw()
screen.mainloop()
这篇关于提示用户在 Python 中输入的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!