# python Odd even sort instance code for output

• 2021-08-17 00:19:20
• OfStack

We have learned odd and even numbers since primary school, and know that integers can be divided into odd and even numbers. Numbers that can be divisible by 2 are called even numbers, and numbers that cannot be divisible by 2 are called odd numbers. In our python programming, will encounter a lot of numbers and code, sometimes very messy, not easy to operate.

When encountering odd and even numbers, if we sort them, it is beneficial for us to watch the operation. Below, this site teaches you how to sort odd and even numbers in python.

Example:

Enter an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array.

Code:

``````
#  Enter: nums =[1,2,3,4]
#  Output: [1,3,2,4]
#  Note: [3,1,2,4]  It is also one of the correct answers 1 .
def func(nums):
nums_new = []
for i in nums:
if i % 2 == 1:
nums_new.insert(0, i)
else:
nums_new.append(i)
return nums_new
nums =[1,2,3,4]
nums_new=func(nums)
print(nums_new)``````

Instance extension:

``````
random_numbers = []
for i in range(40):
random_numbers.append(random.randint(1, 100))
num1 = []
num2 = []
for number in random_numbers:
if number % 2 == 0:
num1.append(number)
else:
num2.append(number)

print(' Even number: {}'.format(sorted(num1)))
print(' Odd number: {}'.format(sorted(num2)))
print(' List: {} , length: {}'.format(sorted(random_numbers), len(random_numbers)))``````

Related articles: