Python:编写一个程序,要求用户输入颜色、线宽、线长和形状

Python: Write a program that asks the user for a color, a line width, a line length and a shape

Write a program that asks the user for a color, a line width, a line length and a shape. The shape should be either a line, a triangle, or a square. Use turtle graphics to draw the shape that the user requests of the size, color, line width and line length that the user requests. For example, if these are the user choices for color, width, line length and shape

什么颜色?蓝色
什么线宽? 25
什么线长? 100
直线、三角形还是正方形?三角形

这是我的尝试:

color = input('Enter your preferred turtle line color: ') 
width = input('Enter your preferred turtle line width: ')
length = input('Enter your preferred turtle line length: ')
shape = input('Specify whether you want to draw a line, triangle, or square: ')

import turtle
s = turtle.Screen()
t = turtle.Turtle()
t.pencolor(color)
t.pensize(width)
if shape == 'line':
    t.forward(length)

elif shape == 'triangle':
    t.forward(length)
    t.right(45)
    t.forward(length)
    t.right(90)
    t.forward(length)

else:
    t.forwad(length)
    t.right(90)
    t.forwad(length)
    t.right(90)
    t.forwad(length)
    t.right(90)
    t.forwad(length)

我收到此错误:

Traceback (most recent call last):
  File "<pyshell#42>", line 4, in <module>
    t.forward(length)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/turtle.py", line 1637, in forward
    self._go(distance)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/turtle.py", line 1604, in _go
    ende = self._position + self._orient * distance
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/turtle.py", line 257, in __mul__
    return Vec2D(self[0]*other, self[1]*other)
TypeError: can't multiply sequence by non-int of type 'float'

有人可以解释为什么转发命令中的长度无法通过吗?

你的 else 条件语句有一个语法错误:t.forwad(length) 而不是 t.forward(length)

我看到的第一个问题是你遗漏了一个'r'。

t.forwad(length)

应该是

t.forward(length)

此外,如果您使用 input()widthlength 将是字符串,但需要进行类型转换。 Specifically,长度必须是整数或浮点数,宽度必须是正整数。

length = None
while not length:
    try:
        length = float(input('Enter your preferred turtle line length: '))
    except ValueError:
        print('You need to enter a number')

width = None
while not width:
    try:
        width = int(input('Enter your preferred turtle line width: '))
    except ValueError:
        print('You need to enter a positive integer')
    else:
        if width < 1:
            print('You need to enter a positive integer')
            width = None

我这里的代码将使用循环从用户那里获得正确的输入。它会尝试拒绝错误的输入。例如,如果用户在您询问长度时键入 'pumpkin'。

类似地,我捕捉长度和宽度条目问题的方式,你会想要捕捉用户输入形状和颜色的问题。确保用户输入有效的颜色。确保形状在允许的形状列表中。

最后一个问题是您的代码缩进不正确。您需要在 if:else: 子句后缩进。

下面是整个程序的运行情况:

import turtle

s = turtle.Screen()
t = turtle.Turtle()

length = None
while not length:
    try:
        length = float(input('Enter your preferred turtle line length: '))
    except ValueError:
        print('You need to enter a number')

width = None
while not width:
    try:
        width = int(input('Enter your preferred turtle line width: '))
    except ValueError:
        print('You need to enter a positive integer')
    else:
        if width < 1:
            print('You need to enter a positive integer')
            width = None
color = None
while not color:
    color = input('Enter your preferred turtle line color: ')
    try:
        t.pencolor(color)
    except:
        print('You need to enter a color that I know.')
        color = None
shape = None
while not shape:
    shape = input('Specify whether you want to draw a line, triangle, or square: ')
    if shape.lower() not in ['line', 'triangle', 'square']:
        shape = None
        print('I only draw lines, triangles and squares!')


t.pensize(width)
if shape.lower() == 'line':
    t.forward(length)
elif shape.lower() == 'triangle':
    t.forward(length)
    t.right(120)
    t.forward(length)
    t.right(120)
    t.forward(length)
else:
    t.forward(length)
    t.right(90)
    t.forward(length)
    t.right(90)
    t.forward(length)
    t.right(90)
    t.forward(length)

s.exitonclick()

请注意,我还修复了三角形...

您正在使用 Python 3.x,并且 input() returns 是一个字符串,而不是一个浮点数。 在将结果用作数字之前,您需要对其进行转换:

length = float(input('Enter your preferred line length: '))

问题是turtleclass、length里面的某处乘以了一个浮点数。如果 length 本身就是一个数字,那么一切都会好起来的。但是在你的例子中,length 是一个字符串,所以 Python 必须执行 string * float。现在,string 被视为一个字符序列。在 Python 中,将序列乘以整数('ab'*3 = 'ababab')是有效的,但不能乘以其他类型(特别是浮点数)。这就是为什么您收到有关将序列乘以非 int 类型的错误消息的原因。

import turtle

s = turtle.Screen()
t = turtle.Turtle()

length = None
while not length:
    try:
        length = float(input('Enter your preferred turtle line length: '))
    except ValueError:
        print('You need to enter a number')

width = None
while not width:
    try:
        width = int(input('Enter your preferred turtle line width: '))
    except ValueError:
        print('You need to enter a positive integer')
    else:
        if width < 1:
            print('You need to enter a positive integer')
            width = None
color = None
while not color:
    color = input('Enter your preferred turtle line color: ')
    try:
        t.pencolor(color)
    except:
        print('You need to enter a color that I know.')
        color = None
shape = None
while not shape:
    shape = input('Specify whether you want to draw a line, triangle, or square: ')
    if shape.lower() not in ['line', 'triangle', 'square']:
        shape = None
        print('I only draw lines, triangles and squares!')strong text

如果您想要的值可以使用 turtle 模块提供的图形输入方法获得,那么将命令行输入与 turtle 图形混合似乎不是一个好主意:

  • textinput(title, prompt)

  • numinput(title, prompt, default=None, minval=None, maxval=None)

这些旨在防止命令行代码需要捕获的一些错误。这是用图形输入法重写的程序:

from turtle import Turtle, Screen, TurtleGraphicsError

screen = Screen()

length = None
while not length:
    length = screen.numinput('Select Length', 'Enter your desired line length:', minval=1)

width = None
while not width:
     width = screen.numinput('Select Width', 'Enter your desired line width:', minval=1, default=1)

turtle = Turtle()
turtle.pensize(width)

color = None
while not color:
    try:
        color = screen.textinput('Select Color', 'Enter your desired line color:')
        turtle.pencolor(color)
    except TurtleGraphicsError:
         color = None

shape = None
while not shape or shape.lower() not in {'line', 'triangle', 'square'}:
    shape = screen.textinput('Select Shape', 'Specify whether you want a line, triangle, or square:')
shape = shape.lower()

if shape == 'line':
    turtle.forward(length)
elif shape == 'triangle':
    for _ in range(3):
        turtle.forward(length)
        turtle.right(120)
else:
    for _ in range(4):
        turtle.forward(length)
        turtle.right(90)

screen.exitonclick()