while循环中的多个输入,以及Python中的try-except块

while循环中的多个输入,以及Python中的try-except块,python,Python,我正在尝试创建一个ROI计算器。我只想接受int格式的输入。我创建了一个try except块,以避免以其他格式输入。但是,如果任何用户在Rent或Loss中输入错误的输入(例如str),我的逻辑将失败 如果他们这样做,while循环将再次从Investment请求输入。我想绕过它,让代码从相应的变量本身请求输入,无论是Rent还是Loss。有什么建议吗 print('This is a ROI calculator. Please enter below details:') while T

我正在尝试创建一个ROI计算器。我只想接受
int
格式的输入。我创建了一个
try except
块,以避免以其他格式输入。但是,如果任何用户在
Rent
Loss
中输入错误的输入(例如
str
),我的逻辑将失败

如果他们这样做,while循环将再次从
Investment
请求输入。我想绕过它,让代码从相应的变量本身请求输入,无论是
Rent
还是
Loss
。有什么建议吗

print('This is a ROI calculator. Please enter below details:')

while True:
    try:
        Investment=int(input('Investment:'))
        Rent=int(input('Rent/month:'))
        Loss=int(input('Loss/year:'))
        if Loss:
            break
    except ValueError:
        print('Please enter in a number format only')

def ROI(Investment,Rent,Loss):
    Net_profit=int((Rent*12) - Loss)
    ROI=((Net_profit/Investment)*100)
    ROI=round(ROI,2)
    print(f'Your Return on Investment is: {ROI}')

ROI(Investment,Rent,Loss)

使用功能的威力:

def inputInt(text):
    """Ask with 'text' for an input and returns it as int(). Asks until int given."""
    while True:
        try:
            what = int(input(text))
            return what                # only ever returns a number
        except ValueError:
            print('Please enter in a number format only')

while True:
        Investment = inputInt('Investment:') 
        Rent = inputInt('Rent/month:') 
        Loss = inputInt('Loss/year:') 
        if Loss:   # this will break as soon as Loos is != 0 ?
            break
 # etc

因此,您总是在下面处理数字输入,并在始终返回整数的特定函数中保持输入收集和错误处理的循环。

使用函数的幂:

def inputInt(text):
    """Ask with 'text' for an input and returns it as int(). Asks until int given."""
    while True:
        try:
            what = int(input(text))
            return what                # only ever returns a number
        except ValueError:
            print('Please enter in a number format only')

while True:
        Investment = inputInt('Investment:') 
        Rent = inputInt('Rent/month:') 
        Loss = inputInt('Loss/year:') 
        if Loss:   # this will break as soon as Loos is != 0 ?
            break
 # etc

因此,您总是在下面处理数字输入,并在始终返回整数的特定函数中保持输入收集循环和错误处理。

您好,欢迎使用Stackoverflow。您应该将投资变量移出循环。您可以将它放在另一个块中,以避免以其他格式输入。这是否回答了您的问题?大家好,欢迎来到Stackoverflow。您应该将投资变量移出循环。您可以将它放在另一个块中,以避免以其他格式输入。这是否回答了您的问题?