下面的问题使用函数get_numbers()从用户读取多个整数。定义了三个未完成的功能,这些功能应仅打印用户输入的某些类型的数字。完成未完成的功能,必要时添加循环和分支。将输出与以下示例匹配:
数字是:5 99 -44 0 12
我已经弄清楚如何完成第一个功能。 很难完成奇数和负数的比较。
由于某些原因
def print_odd_numbers(numbers):
if numbers % 2 == 1:
print('Odd numbers:', numbers)
不工作吗?
size = 6
def get_numbers(num):
numbers = []
user_input = input('Enter %s integers:\n' % num)
i = 0
for token in user_input.split():
number = int(token) # Convert string input into integer
numbers.append(number) # Add to numbers list
print(i, number)
i += 1
return numbers
def print_all_numbers(numbers):
# Print numbers
print('Numbers:')
def print_odd_numbers(numbers):
# Print all odd numbers
print('Odd numbers:')
def print_negative_numbers(numbers):
# Print all negative numbers
print('Negative numbers:')
nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
Enter 5 integers:
0 5
1 99
2 -44
3 0
4 12
Numbers: 5 99 -44 0 12
Odd numbers: 5 99
Negative numbers: -44
答案 0 :(得分:0)
该代码无法正常工作,因为numbers
是数字列表。尝试以下代码:
def print_odd_numbers(numbers):
print('Odd numbers: ')
for n in numbers:
if n % 2 == 1:
print(n, end=' '))
您还可以使用列表理解:
def print_odd_numbers(numbers):
odd = [n for n in numbers if n % 2 == 1]
print('Odd numbers:', ' '.join(map(str, odd)))
答案 1 :(得分:-1)
模数必须为== 0才能视为偶数,如果number%2!= 0,那么它将被视为奇数