[英]Using List Comprehension I want to Print odd even with string indicating “Even” for even numbers and “Odd for odd numbers”
[英]Print the list of odd or even numbers between a range using python. Output should be in a single line along with the string
这是我的代码:
start=int(input('enter the starting range:'))
end=int(input('enter the ending range:'))
for d in range(start,end):
if d%2!=0:
print('The odd numbers between',start,'&',end,'is:',d)
当前输出为:
enter the starting range:20
enter the ending range:30
The odd numbers between 20 & 30 is: 21
The odd numbers between 20 & 30 is: 23
The odd numbers between 20 & 30 is: 25
The odd numbers between 20 & 30 is: 27
The odd numbers between 20 & 30 is: 29
想要的输出是:
'The odd numbers between 20 & 30 is: 21,23,25,27,29'
我需要做哪些改变?
使用列表理解,你可以让它更短
start=int(input('enter the starting range:'))
end=int(input('enter the ending range:'))
# New lines
numbers = ", ".join([str(i) for i in range(start, end) if i % 2 != 0])
print(f"The odds numbers between {start} and {end} are:", numbers)
在循环之前打印消息,然后在循环期间打印数字:
start = int(input('enter the starting range:'))
end = int(input('enter the ending range:'))
# use end='' to avoid printing a newline at the end
print(f'The odd numbers between {start} & {end} is: ', end='')
should_print_comma = False
for d in range(start,end):
if d%2!=0:
# only start printing commas after the first element
if should_print_comma:
print(',', end='')
print(d, end='')
should_print_comma = True
start=int(input('enter the starting range:'))
end=int(input('enter the ending range:'))
s = ""
for d in range(start,end):
if d%2!=0:
s += str(d) + ", ";
print('The odd numbers between',start,'&',end,'is:',s)
你可能应该把它放在一个函数中,但这只是一个偏好。
简单且非常简洁的解决方案:(添加我的评论,以便您了解我所做的)
start = int(input('enter the starting range: '))
end = int(input('enter the ending range: '))
#create an empty list
numbers = []
for d in range(start,end):
if d % 2 != 0:
#if number is odd, add it to the list
numbers.append(d)
#we use end=" " to make sure there is no new line after first print
print('The odd numbers between',start,'&',end,'are:',end=" ")
#* symbol is used to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively
print(*numbers,sep = ",")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.