一般来说,我对代码非常熟悉,不过到目前为止,我的大部分经验都是使用Python的。这就是为什么我不知道该怎么做让人难过。。。你知道吗
我在Python类中有一个赋值,要求我计算直角三角形的面积。我已经成功地完成了分配,但我想更进一步,并限制用户输入除整数以外的任何内容作为输入。我从Codecademy上学到的东西中尝试了多种想法,尽管我似乎不明白。任何帮助都将不胜感激!你知道吗
以下是我迄今为止编写的代码;它可以正常工作,但如果用户要键入除数字以外的任何内容,我希望它返回一个类似“请输入有效数字”的字符串:
from time import sleep
import math
print("Let\'s find the area of a right triangle!")
sleep(2)
triangleBase = float(input("Enter the base value for the triangle: "))
print("Great!")
triangleHeight = float(input("Enter the height value for the triangle: "))
print("Great!")
sleep(2)
print("Calculating the area of your triangle...")
sleep(2)
def triangleEquation():
areaString = str("The area of your triangle is: ")
triangleArea = float(((triangleBase * triangleHeight) / 2))
print('{}{}'.format(areaString, triangleArea))
triangleEquation()
这应该让你开始。我把剩下的留给你(如果你也愿意允许浮动,提示,提示),因为你说你想更进一步,这样你仍然会保留成就感。你知道吗
注意:您还可以使用
is
习惯用法:if type(triangleHeight) is int
。。。你知道吗你很接近。您注意到您的代码引发了一个异常。您所需要做的就是捕获该异常并再次提示。本着“不要重复你自己”的精神,这可以是它自己的功能。我清理了其他一些东西,比如使用全局变量的计算函数,以及转换不需要转换的东西(例如,“foo”是str,不需要
str('foo')
),然后相关问题 更多 >
编程相关推荐