我正在使用 Python、Flask 和 forex_python.converter 創(chuàng)建一個(gè)外匯貨幣轉(zhuǎn)換器。現(xiàn)在,當(dāng)用戶在主頁上提交要轉(zhuǎn)換的貨幣和金額時(shí),它會(huì)將他們定向到一個(gè)單獨(dú)的網(wǎng)頁,僅顯示其表單輸入的值。最終這將顯示轉(zhuǎn)換后的外匯金額。如果用戶輸入了錯(cuò)誤的外匯代碼或字符串作為金額,他們將被引導(dǎo)回同一頁面,并且會(huì)使用 Flasks 的 Flash 消息顯示錯(cuò)誤橫幅。我已經(jīng)能夠成功地為錯(cuò)誤的外匯代碼輸入創(chuàng)建錯(cuò)誤橫幅,但是我正在努力解決如何為無效金額創(chuàng)建錯(cuò)誤橫幅的問題。理想情況下,如果用戶輸入的“金額”是字母、空白或符號(hào)而不是數(shù)字,則橫幅將顯示“不是有效金額”?,F(xiàn)在,橫幅將始終出現(xiàn),但用戶數(shù)量永遠(yuǎn)不會(huì)轉(zhuǎn)換為浮點(diǎn)數(shù)。我通過使用將用戶輸入的金額轉(zhuǎn)換為浮點(diǎn)數(shù)來嘗試此操作float(),當(dāng)金額為整數(shù)(或浮點(diǎn)數(shù))時(shí),該方法成功運(yùn)行,但是如果輸入是其他內(nèi)容,我會(huì)收到錯(cuò)誤并且我的代碼停止。我已經(jīng)被這個(gè)問題困擾了幾個(gè)小時(shí)了,所以如果有人有任何解決這個(gè)問題的策略,我將不勝感激。我的 python 代碼和 3 個(gè) HTML 頁面如下:from flask import Flask, request, render_template, flash, session, redirect, url_forfrom flask_debugtoolbar import DebugToolbarExtensionfrom forex_python.converter import CurrencyRatesapp = Flask(__name__)app.config['SECRET_KEY'] = "secretkey"# store all currency rates into variable as a dictionaryc = CurrencyRates()fx_rates = c.get_rates('USD')# home page@app.route('/', methods=['POST', 'GET'])def home(): return render_template('home.html')# result page. User only arrives to result.html if inputs info correctly@app.route('/result', methods=['POST', 'GET'])def result(): # grab form information from user and change characters to uppercase forex_from = (request.form.get('forex_from').upper()) forex_to = (request.form.get('forex_to').upper()) # Where I am running into issues. # I have tried: # before_amount = (request.form.get('amount').upper()) # amount = float(before_amount) amount = request.form.get('amount') print(amount) # if input is invalid bring up banner error if forex_from not in fx_rates : flash(f"Not a valid code: {forex_from}") if forex_to not in fx_rates : flash(f"Not a valid code: {forex_to}") if not isinstance(amount, float) : flash("Not a valid amount.")
2 回答

慕姐8265434
TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以使用try和except
ask_again = True
while ask_again == True:
amount = request.form.get('amount')
try:
amount = float(amount)
ask_again = False
except:
print('Enter a number')

夢(mèng)里花落0921
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用 try catch 方法來執(zhí)行此操作。
try:
val = int(input())
except valueError:
try:
val = float(input())
except valueError:
#show error message
添加回答
舉報(bào)
0/150
提交
取消