2017-09-27 41 views
-1

我想獲得用戶對其信用評級的輸入,例如AAA,A,BBB等,然後爲此分配利率。例如,如果用戶具有良好的信用評級,例如AAA,我將收取1%的利率。從字符串輸入收集數字數據

我已經插入了我在VBA中用於這個特定功能的代碼,所以你有我想要的/它是如何工作的想法,雖然我刪除了各種行,因爲我只添加了代碼,以便更好地瞭解我正在努力。

creditRate = InputBox("Please enter credit rating:") 

If creditRate = "AAA" Then GoTo intcalc Else 
If creditRate = "A" Then GoTo intcalc Else 
If creditRate = "BBB" Then GoTo intcalc Else 
If creditRate = "BB" Then GoTo intcalc Else 
If creditRate = "CCC" Then GoTo intcalc Else 
If creditRate = "DDD" Then GoTo intcalc Else 

If creditRate = "AAA" Then intRate = 0.01 Else 
If creditRate = "A" Then intRate = 0.03 Else 
If creditRate = "BBB" Then intRate = 0.05 Else 
If creditRate = "BB" Then intRate = 0.06 Else 
If creditRate = "CCC" Then intRate = 0.08 Else 
If creditRate = "DDD" Then intRate = 0.1 Else 
+0

你** ** DEFINITELY沒有這樣的代碼在VBA - 即如果其他的語法是不合法的。此外,找到一種方法來避免'GoTo'跳轉。 99.99999%的時間是可以避免的。 –

回答

0

在Python這最有可能被使用的字典,基於散列的數據結構,其允許(相當)任意鍵的查找來計算。這樣的字典可以按照如下

rate_dict = {"AAA": 0.01, "A": 0.03, "BBB", 0.05, "BB", 0.06, "CCC": 0.08, "DDD": 0.1} 

你可以這樣設置使用

int_rate = rate_dict[credit_rate] 

如果credit_rate從用戶輸入設置,你可能需要檢查是否利率(使用Python的標準命名約定)創建它是否有效。你可以做到這一點與

if credit_rate in rate_dict: 
    ... 

如果你要問用戶輸入一個有效的輸入,使用無效的值開始並重復,直到用戶提供了一個有效的。一個簡單的方法來做到這將是

credit_rate = '*' 
while credit_rate not in rate_dict: 
    credit_rate = input("Credit rating: ") 

如果你想提供的錯誤信息,然後用break在可接受值的無限循環可能會更具可讀性。

while True: 
    credit_rate = input("Credit rating: ") 
    if credit_rate in rate_table: 
     int_rate = rate_dict[credit_rate] 
     break 
    print(credit_rate, "is not a known credit rating" 

讀者使用Python 2應小心使用raw_input內置的,因爲在input嘗試計算輸入作爲一個Python表達式舊版本。

+0

對於有效性檢查,如何更改它,以便取代循環中的腳本,直到用戶輸入有效的輸入。例如對於貸款金額我做到了這一點。我似乎無法格式化評論回覆,所以代碼搞砸了抱歉,但我確信你會得到即將發生的事情。 .loanAmt = 0 而真: 嘗試: LoanAmt = INT(輸入( '什麼是你心目中的貸款金額?')) 除了ValueError異常: 打印( 「!不是有效的選擇」) 繼續 其他: 打印('您的期望貸款金額是£'+ str(LoanAmt)) 中斷 – JPWilson

+0

已更新爲嘗試並以正確的方式引導您。 – holdenweb

0

Python還提供一個默認字典,該字典在字典中不存在鍵時返回默認值。

from collections import defaultdict 
rates = defaultdict(lambda: None, { 
        "AAA" : 0.01, "A" : 0.03, 
        "BBB" : 0.05, "BB" : 0.06, 
        "CCC" : 0.08, "DDD" : 0.1 
         }) 

所以

rate = rates['AAA'] #rate = 0.01 

rate = rates['D']) #rate = None