1

I am struggling to figure out how to do this I am trying to convert this if/elif/else code

# gets user input for credit score
credit_score = input('What is your credit score? ')
credit_score = int(credit_score)

#determines what the interest rate is based off credit score
if credit_score < 0 :
    interest_rate = 27
elif 300 <= credit_score <= 579 :
    interest_rate = 19
elif 580 <= credit_score <= 669 :
    interest_rate = 18
elif 670 <= credit_score <= 739 :
    interest_rate = 11
elif 740 <= credit_score <= 799 :
    interest_rate = 7
else :
    interest_rate = 5

#prints result
print('Your interest rate will be:', interest_rate, '%')

into this switch/case code

# gets user input for credit score
credit_score = input('What is your credit score? ')
credit_score = int(credit_score)

# determines what the interest rate is based off credit score
match interest_rate :
    case credit_score < 0 :
        interest_rate = 27
    case 300 <= credit_score <= 579 :
        interest_rate = 19
    case 580 <= credit_score <= 669 :
        interest_rate = 18
    case 670 <= credit_score <= 739 :
        interest_rate = 11
    case 740 <= credit_score <= 799 :
        interest_rate = 7
    case credit_score >= 800 : 
        interest_rate = 5

# prints result
print('Your interest rate will be:', interest_rate, '%')

My issue is with the comparison operators. I would really like them to stay in the code but cannot figure out how. Do I need to do it a different way or...?

  • Are you asking for a good way to meet your goals, or do you specifically want an answer using pattern matching? – Mark Dec 07 '21 at 04:25
  • 1
    While you can do this (and it was easy for me to find the linked duplicate by [using a search engine](https://duckduckgo.com/?q=python+match+case+range), I don't really understand why you'd want to. The `elif` chain isn't any more verbose or complex. The main advantage of the new `match` construct is that you can easily assign *components of* "matching" *structured* data to separate variables. – Karl Knechtel Dec 07 '21 at 04:26
  • You also don't need both comparisons since you're using `elif`. If you put them in the right order then each `if` implies that the next one is outside that range. For example if you start `if credit_score >= 800` then your next clause can be `elif credit_score >= 740`; you don't need to check it's also less than 800 because if it were 800 or greater, it would have been caught by the first `if`. And so on... – kindall Dec 07 '21 at 04:34

0 Answers0