F-strings
f-strings provide a simple and intuitive way to format strings in Python, making it easier to read and maintain code. To use f-strings, simply prefix the string with 'f' or 'F' and place variable names or expressions inside curly braces {}. The contents within the curly braces are then replaced with the value of the respective variable or expression.
F-strings allow variables to be inserted directly without the need for converting them to strings, thus enhancing readability and convenience in code writing. Additionally, f-strings can include not only variables but also function calls or expressions. Overall, f-strings offer a straightforward and intuitive method for formatting strings in Python, facilitating easier reading and maintenance of code.
scores = [
{'name':'영수','score':70},
{'name':'영희','score':65},
{'name':'기찬','score':75},
{'name':'희수','score':23},
{'name':'서경','score':99},
{'name':'미주','score':100},
{'name':'병태','score':32}
]
for s in scores:
name = s['name']
score = s['score']
print (name+'의 점수는 '+str(score)+'점 입니까?')
print (f'{name}의 점수는 {score}점 입니까?')
Try and Except
`try` and `except` are used for exception handling in Python. The code that might raise an exception is placed inside the `try` block, and the potential exceptions are handled using the `except` block. This allows the program to gracefully handle exceptional situations.
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby'},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
for a in people:
try:
if a['age'] > 20:
print(a['name'])
except:
print(a['name'], 'error')
In this case, if I use elif or else after the if statement, all the results including the age below 20 will appear as well.
To fix the error where the line doesn't have age, we can use the try and except statements.
'Study Note > Python' 카테고리의 다른 글
9. Method vs Function / Dictionary vs List (0) | 2024.03.28 |
---|---|
8. Function simplification (0) | 2024.03.27 |
6. Set & tuples and list (0) | 2024.03.27 |
5. Uses of [] {} () (0) | 2024.03.26 |
4. Function [Def] (0) | 2024.03.26 |