The if else statement can be written in one sentence.
-Expression (executed with True) if conditional expression else expression (executed with false)
Official page The expression "x if C else y" first evaluates C instead of the condition x. If C is true, x is evaluated and a value is returned. Otherwise y is evaluated and returned.
Normal if statement
a=5
if a<5:
i*5
else:
i*2
Write in one sentence
a=5
i*5 if a<5 else i*2
▼ Application Let's unravel the contents of the description taught by @shiracamus.
python
def gradingStudents(grades):
return [grade + (0 if grade < 38 or grade % 5 < 3 else -grade % 5)
for grade in grades]
if __name__ == '__main__':
grades_count = int(input().strip())
grades = [int(input().strip()) for _ in range(grades_count)]
result = gradingStudents(grades)
print(*result, sep='\n')
「0 if grade < 38 or grade % 5 < 3 else -grade % 5」
0 if less than 38 and the remainder after dividing by 5 is 3 or less. (True) If False, calculate the remainder by dividing the negative value by 5.
The remainder when dividing a negative value such as "-5% 3". Must be a ** plus integer **
-x%y The quotient is negative. The remainder is 0 <= the remainder <y
In the case of "-5% 3", quotient: -2, remainder: 1 Residual = 3 * (-2) -5 = 1
・ A description to write a for sentence in one sentence. [Expression for Variable in Iterable] └ Output is list
・ Return [Comprehension] └ return is executed after all the comprehension processing is completed.
python
s1,s2="h","world"
def twoStrings(s1, s2):
return "YES" if sum([s2.count(i) for i in set(s1)]) else "NO"
twoStrings(s1, s2)
Recommended Posts