我的任务是:
You have been asked to write a program that will give the name of a shape depending on the number of sides. The user can only enter numbers between 3 and 8, if they enter any other number then the program should tell them to enter a number between 3 and 8.
下面是我的答案:
#Sides and shapes
sides = int(input("How many sides on the shape are there? "))
if sides ==3:
print ("Your shape is the triangle")
if sides ==4:
print ("Your shape is the square")
if sides ==5:
print ("Your shape is the pentagon")
if sides ==6:
print ("Your shape is the hexagon")
if sides ==7:
print ("Your shape is the heptagon")
if sides ==8:
print ("Your shape is the octagon")
elif sides != range(3,9):
print ("You should enter a number between 3 and 8")
在elif
语句之后,我还需要以某种方式循环它,以便如果用户输入的不是3-8,那么它将继续要求用户输入3到8之间的数字。你知道吗
elif
语句由于某种原因不起作用,并在F5中输出这个答案:
How many sides on the shape are there? 6
Your shape is the hexagon
You should enter a number between 3 and 8
range(x, y)
输出介于x
和y
之间的数字范围。然后将一个整数(即边的值)与一个列表进行比较。显然它不等于列表,因为它是一个整数!你知道吗range()
产生一个不同类型的对象;integer != range()
总是为真。你知道吗使用
<
或<=
和链接测试整数是否超出范围:或者使用
not in
查看数字是否超出范围:或者只需对所有测试使用
elif
,但第一个测试除外,对最后一个分支使用else
;仅当if..elif
测试不匹配时才会选择它:注意,现在只有一个
if
;从逻辑上讲,elif
和else
部分属于这个if
语句。任何其他的if
形成一个单独的、新的选择集,你的sides != range(3, 9)
表达式总是正确的,这意味着elif
测试在if slides == 8
不正确的时候都是正确的。你知道吗可以使用dictionary简化代码。它允许您将一个键与一个值相关联;将数字作为键,您可以简单地测试
sides
是否在字典中,或者返回一个默认值,如果不是:这里,^{} method 返回给定键的值,如果键不存在,则返回默认值。你知道吗
如果需要继续循环,请基于以下内容测试是否存在密钥和分支:
有关如何请求用户输入并处理错误输入的更多提示,请参见Asking the user for input until they give a valid response。你知道吗
您的
elif
只与前面的if
关联,因此对于任何不是八角形的东西,它都会击中elif
,然后正如其他人注意到的那样,您的比较并不是测试您是否在正确的范围内,而是将int与列表进行比较。你知道吗可能您真的希望所有的
if
语句,除了第一个是elif
,另一个作为elif
的语句是整个块的else
子句。你知道吗更好的是,你可以有一个字典来映射消息的边数,如果字典中没有键,你可以打印错误消息。你知道吗
对于循环,如果你把整个东西放在
while True
中,你可以在每次成功之后break
,而不是在无效的边数之后,这将导致循环重复,直到它们最终输入一个有效的数字。你知道吗相关问题 更多 >
编程相关推荐