我是Python的新手,想知道为什么会发生这种情况。 这是代码:
import turtle
What_Calculate = turtle.numinput("Area of Different Shapes Calculator", "Type 1 to calculate the area of a square, Type 2 to calulate the area of a rectangle, Type 3 to calculate the area if a triangle, Type 4 to calulate the area of a circle, or click [q] to quit:")
while What_Calculate !="q":
if What_Calculate == 1:
Length_Square = eval(input("What is the length of the square?:"))
Area_Squ = Length_Square * Length_Square
print("The area of the square is ", Area_Squ, ".")
What_Calculate = input("Click another number or click [q] to exit:")
elif What_Calculate == 2:
Length_1 = eval(input("What is the first length?:"))
Length_2 = eval(input("What is the second length?:"))
Area_Rec = Length_1 * Length_2
print("The area of the rectangle is ", Area_Rec, ".")
What_Calculate = input("Click another number or click [q] to exit:")
elif What_Calculate == 3:
Length = eval(input("What is the length?:"))
Height = eval(input("What is the height?:"))
Area = Length * Height / 2
print("The area of the triangle is", Area)
What_Calculate = input("Click another number or click [q] to exit:")
elif What_Calculate == 4:
Diameter = eval(input("What's the diameter of the circle?:"))
Radius = Diameter / 2
Pie = 3.14
Area = Pie * Radius * Radius
print("The area of the circle is ", Area, ".")
What_Calculate = input("Click another number or click [q] to exit:")
这是问题所在:
用户输入了要使用的计算器后,代码便会起作用,直到给出答案为止。
在What_Calculate = input("Click another number or click [q] to exit:")
,键入q
可以正常退出,但是1
-4
根本不起作用。如果我没看错,在这种情况下while
循环不应该循环,直到What_Calculate
为空?
答案 0 :(得分:1)
问题是What_Calculate = input("Click another number or click [q] to exit:")
返回一个字符串,该字符串在if / elif / elif / elif中总是失败。因为它是字符串而不是数字,所以"1" != 1
。我可以看到的最简单的方法是添加
try:
What_Calculate = int(What_Calculate)
except ValueError:
#Some code to handle what happens if What_Calculate cannot be turned into an int.
到while循环的开始。将其包含在try / except循环中可让您检测用户是否输入了不是整数且不是字母'q'的内容。
答案 1 :(得分:0)
input()返回一个字符串...您正在检查一个整数
答案 2 :(得分:0)
input()函数返回一个字符串,并且由于循环中的所有比较都是数字,因此它将在第一次通过后永远循环。您不应该同时将What_Calculate
用作int和字符串-我的建议(尝试更改尽可能少的代码)是将比较从if What_Calculate == 1:
更改为if What_Calculate == "1":
依此类推,然后更改您的turtle.numinput
调用以要求输入字符串而不是数字。