In Python, there are several ways to express odd numbers, either directly with numbers or with corresponding data types.
This article will provide an in-depth introduction to the expressions of odd numbers in Python, including integers, booleans, list inferences, generator expressions, and decorators. Autumn and Winter Check-in Challenge
Through the Xi of this article, readers will be able to become proficient in the expression of odd numbers in python and use them freely in practical programming.
Parity of integers.
In Python, integers can be divided into odd and even numbers based on the remainder of their division by 2.
In general, the integer n is odd if and only if the remainder of n divided by 2 is 1. For example:
n = 7if n % 2 == 1:(tab)print(f"It's an odd number")else:(tab)print(f"It's an even number")
The output is:
7 is an odd number. Parity of Boolean type.
In Python, the Boolean type has two values, true and false. Since true is equal to 1 and false is equal to 0, the operator % can be used to calculate the remainder of the Boolean value and thus its parity. For example:
value = trueif value % 2 == 1:(tab)print(f"It's an odd number")else:(tab)print(f"It's an even number")
Output: true is an odd number.
List derivations and generator expressions.
In Python, you can use list inferences or generator expressions to generate a series of odd numbers. For example:
List derivation:
odd_numbers = [i for i in range(10) if i % 2 != 0]print(odd numbers) output: [1, 3, 5, 7, 9].
Generator Expression:
odd_number = (i for i in range(10) if i % 2 != 0)for number in odd number:print(number) output: 1, 3, 5, 7, 9
Parity judgment of decorators and functions.
In Python, a decorator is a feature that makes enhancements or modifications to a function. We can use decorators to create a function that determines the parity of the function parameters.
For example: def is odd(func):(tab)def wrapper(*args):(2tab)for arg in args:(3tab)if arg % 2 != 0:(4tab)return true(3tab)else:(4tab)return false(tab)return func(wrapper)
In practice, you can pass in parameters to determine parity.
is_odddef check_odd(n):(tab)return n % 2 != 0
For example, check odd(3) outputs true, and check odd(4) outputs false.
Summary. This article describes the expressions for odd numbers such as integers, Booleans, list derivatives, generator expressions, and decorators.
Through the Xi of this article, readers can become proficient in the expression of odd numbers in python and use them freely in practical programming.