Python,我可以在 while 语句检查条件发生之前格式化用户输入吗?

Python, can I format user input before a while statement checks for a condition to happen?

这是一个愚蠢的问题,但是:

我需要得到一个代表我的用户投资组合的浮点数,所以我需要检查输入是否为数字,如果它包含逗号,我想用点来更改它。

我有这段代码:

portfolio_size = input('Insert portfolio size:')
portfolio_size = portfolio_size.replace(",", ".")

while not(portfolio_size.isnumeric()):
    print("\nInput Wrong \nPlease try again!")
    portfolio_size = input('Insert portfolio size:').replace(",",".") #This doesn't work
val = float(portfolio_size)
print(val)

我想过使用 while not 语句来创建一个循环,但我对如何使用 replace(",",".") 方法在这种情况下,因为“while not”不接受任何类型的字符串,如果我尝试输入类似“33,18”的内容,它将再次提示我输入

是否有解决方法或更优雅的方法来获得相同的结果?

isnumeric 函数不检查它是否是 float(它只适用于 int

试试这个:

portfolio_size = input('Insert portfolio size:')
portfolio_size = portfolio_size.replace(",", ".")

while True:
    if portfolio_size.isnumeric():
        break
    
    try:
        float(portfolio_size)
    except ValueError:
        print("\nInput Wrong \nPlease try again!")
        portfolio_size = input('Insert portfolio size:').replace(",",".") #This doesn't work
        continue
    
    break
    
val = float(portfolio_size)
print(val)

它看起来不像 pythonic 代码,但我希望它能帮助你

您可以尝试转换为浮点数,如果转换不成功则捕获异常:

portfolio_size = ''
valid = False

while not valid:
    portfolio_size = input('Insert portfolio size:')

    try:
        portfolio_size = float(portfolio_size.replace(",", "."))
    except ValueError:
        print("\nInput Wrong \nPlease try again!")
        continue

    valid = True

print(portfolio_size)