我可以使用哪种Python3方法将输入限制为赋值中的整数?

2024-10-04 07:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

一般来说,我对代码非常熟悉,不过到目前为止,我的大部分经验都是使用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()

Tags: ofthe代码用户import内容inputvalue
2条回答

这应该让你开始。我把剩下的留给你(如果你也愿意允许浮动,提示,提示),因为你说你想更进一步,这样你仍然会保留成就感。你知道吗

def triangleEquation(triangleBase, triangleHeight):
    if type(triangleHeight) == int and type(triangleBase) == int:
        areaString = "The area of your triangle is: "
        triangleArea = float(((triangleBase * triangleHeight) / 2))
        return '{}{}'.format(areaString, triangleArea)
    else:
        return 'Integers only.'

注意:您还可以使用is习惯用法:if type(triangleHeight) is int。。。你知道吗

你很接近。您注意到您的代码引发了一个异常。您所需要做的就是捕获该异常并再次提示。本着“不要重复你自己”的精神,这可以是它自己的功能。我清理了其他一些东西,比如使用全局变量的计算函数,以及转换不需要转换的东西(例如,“foo”是str,不需要str('foo')),然后

from time import sleep
import math

def input_as(prompt, _type):
    while True:
        try:
            # better to ask forgiveness... we just try to return the
            # right stuff
            return _type(input(prompt.strip()))
        except ValueError:
            print("Invalid. Lets try that again...")

def triangleEquation(base, height):
    area = base * height / 2
    print('The area of your triangle is: {}'.format(areaString, area))


print("Let\'s find the area of a right triangle!")
sleep(2)

triangleBase = input_as("Enter the base value for the triangle: ", float)
print("Great!")

triangleHeight = input_as("Enter the height value for the triangle: ", float)
print("Great!")
sleep(2)

print("Calculating the area of your triangle...")
sleep(2)

triangleEquation(triangleBase, triangleHeight)

相关问题 更多 >