我正在使用 Python、Flask 和 forex_python.converter 創建一個外匯貨幣轉換器?,F在,當用戶在主頁上提交要轉換的貨幣和金額時,它會將他們定向到一個單獨的網頁,僅顯示其表單輸入的值。最終這將顯示轉換后的外匯金額。如果用戶輸入了錯誤的外匯代碼或字符串作為金額,他們將被引導回同一頁面,并且會使用 Flasks 的 Flash 消息顯示錯誤橫幅。我已經能夠成功地為錯誤的外匯代碼輸入創建錯誤橫幅,但是我正在努力解決如何為無效金額創建錯誤橫幅的問題。理想情況下,如果用戶輸入的“金額”是字母、空白或符號而不是數字,則橫幅將顯示“不是有效金額”。現在,橫幅將始終出現,但用戶數量永遠不會轉換為浮點數。我通過使用將用戶輸入的金額轉換為浮點數來嘗試此操作float(),當金額為整數(或浮點數)時,該方法成功運行,但是如果輸入是其他內容,我會收到錯誤并且我的代碼停止。我已經被這個問題困擾了幾個小時了,所以如果有人有任何解決這個問題的策略,我將不勝感激。我的 python 代碼和 3 個 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 [email protected]('/', methods=['POST', 'GET'])def home(): return render_template('home.html')# result page. User only arrives to result.html if inputs info [email protected]('/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貢獻1813條經驗 獲得超2個贊
您可以使用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')

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