+ 2
Doesn't the match case (in python) work on solo learn?
I made a code using match case, and it was getting errors, i couldn't find the error, i ran the code in pydroid3 app and it worked... https://code.sololearn.com/cr0IberQ2WWl/?ref=app
10 odpowiedzi
+ 8
The python version in playground is 3.9, and match case is introduced at 3.10.
Therefore you can't run match case with python in here.
+ 6
The match that is used in newer versions of than Python3.9, of course, is probably a good thing, but in this case it is absolutely not necessary, it is enough to call the get() method:
data = {
'Singapore': 1,
'Ireland': 6,
'United Kingdom': 7,
'Germany': 27,
'Armenia': 34,
'United States': 17,
'Canada': 9,
'Italy': 74
}
a=input()
print(data.get(a))
P.S: "And you have an error in the line print(data.get['Singapore'])"
+ 5
Rain, yes, the print(data[a]) would work, but provided that the input is correct, otherwise it will give an error, and the get() method eliminates the error by outputting "None" by default, or an alternative text:
print(data.get(a,f"No data available for {a}"))
+ 4
Solo , don't forget the default value if nothing matches.
print(data.get(a, 'no country found'))
I agree, a simple dictionary.get() will do the same thing if the cases are just for directly matching keys.
+ 4
Bob_Li, thank you, I know and have already given an answer about this...😎
+ 3
Shin Chan ,
Pydroid3 just upgraded to Python 3.11.4 a few weeks ago, and I was also playing around with match case there as you were. It's a useful control flow syntax.
Other languages like C and Kotlin already have similar control flow syntax. Interesting that it took Python a long time to get it, and good that it finally did.
match case also introduces a new meaning for the _ symbol in Python as the wild card for the last case that never fails.
I read that Python's philosophy on reusing special symbols is, it's better to change the meanings of a few special characters depending on the context rather than introduce a different special symbol for each purpose and end up with a huge list of special symbols that programmers would have to hunt for on their keyboards.
So Python is easy to type, but you have to learn all the different contexts where the same symbols mean different things.
+ 3
Solo ,
Excellent point about refactoring. In fact, this would work.
print(data[a])
+ 3
Solo right, I did not see that. I guess I did not scroll down far enough.😅
But yes, I wish Sololearn would upgrade their Python version so we can play around with the newer features.
A better justification for using match is if you want a more flexible input. Then a simple dictionary.get() would not be enough.
match a:
case 'Singapore'|'SGP'|'SG'|'singapore'|'sgp'|'sg':
print(data.get('Singapore'))
...
here is a nice link for country name abbreviations
https://www.iban.com/country-codes
0
hi, idk