如何让 Python 将逗号识别为用户输入中的小数点?

How can I get Python to recognize comma as the decimal point in user input?

这里是超级新手。

我正在关注使用 Python 自动化无聊的东西这本书,我决定制作一个小脚本来帮助我进行一些基本的百分比检查。我不想每次都想打开 Excel。

所以脚本得到两个输入,一个旧价格和一个新价格,然后计算价格的百分比变化。我想我是对的。

一旦我尝试输入浮点数(这是正确的术语,是吗?)并在欧洲使用逗号,就会出现问题。

我找到了一个主题here,其中回答了类似的问题,但似乎有一个关于是否调用 setlocale 的问题,并且(据我所知)它没有处理如何转换输入?

我的代码如下:

    def izracun_odstotkov():    #function to calculate the difference in % between original price and new price
    while True:
        try:
            prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue

        if prvotna_cena == 0:
                print('Prvotna cena ne more biti 0.')
        else:
            break

    while True:
        try:
            nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue
        else:
            break

    print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')

while True:
    izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.

您可以使用替换方法:

prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))