[Python] How to write an if statement in one sentence.

[Python] How to write an if statement in one sentence.

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')

▼ Write if statement in a row

「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.

▼ Minus remainder

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

Comprehension notation

・ 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.


Summary,
  1. Extract the elements included in grade in the inclusion notation one by one.
  2. Use the if statement to determine the value to add to grade.
  3. Repeat for the number of elements
  4. List the values of "grade + 0 or remainder"
  5. Return with return.

## Example of a program using one-sentence notation and inclusion notation of if statement

Compare two strings to see if they contain the same character.

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

[Python] How to write an if statement in one sentence.
Difference in how to write if statement between ruby ​​and python
How to write Ruby to_s in Python
How to develop in Python
How to write string concatenation in multiple lines in Python
How to create an image uploader in Bottle (Python)
How to write a Python class
[Python] How to do PCA in Python
[python] How to check if the Key exists in the dictionary
[Introduction to Python] How to write conditional branches using if statements
How to write soberly in pandas
How to collect images in Python
Write an HTTP / 2 server in Python
How to define multiple variables in a python for statement
How to convert 0.5 to 1056964608 in one shot
[Road to intermediate Python] Use if statement in list comprehension
How to check if a value exists in an enum
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to check in Python if one of the elements of a list is in another list
How to use PubChem in Python
How to handle Japanese in Python
An alternative to `pause` in Python
How to know the internal structure of an object in Python
How to make a string into an array or an array into a string in Python
How to create a heatmap with an arbitrary domain in Python
[Introduction to Python] How to use the in operator in a for statement?
How to write offline real time Solve E04 problems in Python
The 14th offline real-time how to write reference problem in python
How to display legend marks in one with Python 2D plot
The 18th offline real-time how to write reference problem in Python
How to calculate "xx time" in one shot with Python timedelta
[Introduction to Python] How to use class in Python?
How to access environment variables in Python
[Introduction to Udemy Python3 + Application] 33. if statement
How to dynamically define variables in Python
How to do R chartr () in Python
python3 How to install an external module
How to convert Python to an exe file
How to write Python document comments (Docstrings)
[Itertools.permutations] How to put permutations in Python
How to work with BigQuery in Python
How to get a stacktrace in python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to use regular expressions in Python
How to display Hello world in python
How to write this process in Perl?
How to use is and == in Python
Python if statement
[Python] if statement
The 17th offline real-time how to write reference problem implemented in Python
How to write the correct shebang in Perl, Python and Ruby scripts
[Introduction to Python] How to judge authenticity with if statement (True and None)
How to write a string when there are multiple lines in python