Python 3.4.1 打印新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25535325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3.4.1 Print new line
提问by WillyJoe
I have quick question that I have been trying to figure out for some time now. I am writing a code that takes inputted number ranges(a high, and a low) and then uses an inputted number to find out if there are multiples of that number within the range. It will then add total the sum of odd and even numbers and add how many there are. I've got everything to calculate correctly but my problem is I can't separate the line "90 75 60 45 30" from the other line "3 even numbers total to 180". I'm sure it's something simple but I can't figure it out. Would someone be able to point me in the right direction? thanks in advance for time and consideration.
我有一个快速的问题,我一直试图弄清楚一段时间。我正在编写一个代码,它接受输入的数字范围(高和低),然后使用输入的数字来确定该范围内是否有该数字的倍数。然后它会将奇数和偶数的总和相加,并加上有多少。我已经得到了正确计算的一切,但我的问题是我无法将“90 75 60 45 30”行与另一行“3个偶数总计为180”分开。我确定这很简单,但我无法弄清楚。有人能指出我正确的方向吗?提前感谢您的时间和考虑。
The below code returns:
下面的代码返回:
Number of high range?: 100
Number of low range?: 20
Multiple to find?: 15
90 75 60 45 30 3 even numbers total to 180
2 odd numbers total to 120
Code:
代码:
def main():
x = int(input('Number of high range?: '))
y = int(input('Number of low range?: '))
z = int(input('Multiple to find?: '))
show_multiples(x,y,z)
def show_multiples(x,y,z):
for a in range(x,y,-1):
if a % z == 0:
print (a,end=' ')
even_count = 0
even_sum = 0
odd_count = 0
odd_sum = 0
for num in range(x,y,-1):
if num % z == 0 and num % 2 == 0:
even_count += 1
even_sum += num
for number in range(x,y,-1):
if number % z == 0 and number % 2 == 1:
odd_count += 1
odd_sum += number
print(even_count,'even numbers total to',even_sum)
print(odd_count,'odd numbers total to',odd_sum)
main()
采纳答案by Cocksure
print('\n', even_count, ' even numbers total to ', even_sum, sep='')
should do it. Just manually put in a new line somewhere
应该这样做。只需手动在某处添加新行
回答by jonrsharpe
A minimal example of the problem:
问题的最小示例:
>>> def test1():
for _ in range(3):
print("foo", end=" ")
print("bar")
>>> test1()
foo foo foo bar # still using end=" " from inside the loop
A minimal example of one solution:
一种解决方案的最小示例:
>>> def test2():
for _ in range(3):
print("foo", end=" ")
print() # empty print to get the default end="\n" back
print("bar")
>>> test2()
foo foo foo
bar
This empty printcan sit anywhere between the end of the forloop in which you printthe individual numbers and print(even_count, ..., for example:
这个空print可以位于for循环末尾之间的任何地方,其中您print的个人数字和print(even_count, ...,例如:
...
odd_sum += number
print()
print(even_count, 'even numbers total to', even_sum)

