Problems prompting user for input in Python

萝らか妹 提交于 2019-12-13 09:48:14

问题


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

I typed in this code above. It says in the python shell "flower" isn't defined. Can someone figure this out for me?


回答1:


Several lines of your code have errors of some sort:

t=turtle.Pen should be: t = turtle.Pen()

You should avoid functions and variables with the same name

def what_to_draw():
    ...
    what_to_draw = sys.stdin.readline()

Use rstrip() to deal with "\n" and .lower() to deal with case:

if what_to_draw == "flower/n":

elif(): requires a condition of some sort otherwise use else:

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



回答2:


Your indentations are wrong, so most of the statements are outside the function body of what_to_draw().
You don't actually call the function, so it won't do anything.
Also, don't use the what_to_draw as a function name and a variable name.
There shouldn't be () after elif:
Instead of print() and stdin, use input() . You don't get the \n that way as well.

Try this and let me know:

import sys
import turtle
t=turtle.Pen()
def what_to_draw():
    draw_this = input("What to do you want to see a sketch of that may or may not be colored?")
    if draw_this == "flower":
        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")

what_to_draw()


来源:https://stackoverflow.com/questions/47426872/problems-prompting-user-for-input-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!