我是Python的初学者,我需要一些关于案例的帮助:我需要打印从for循环输入的数字对 - 例如
count_of_numbers = int(input())
for numbers in range(2*count_of_numbers):
number = int(input())
假设我们输入 3 2 1 4 5 0 4,我需要打印配对数字的总和 - 3 + 2、1 + 4 等。有人可以告诉我这是如何完成的吗?
我试图保留你的大部分代码:
count_of_numbers = int(input("Please enter the number of pairs: "))
for i in range(count_of_numbers):
number1 = int(input("Number 1 = "))
number2 = int(input("Number 2 = "))
print ("Sum of " + str(number1) + " and " + str(number2) + " = " + \
str(number1 + number2))
我做了一些改变:
count_of_numbers
。我本可以使用“+ 1”,但更喜欢从零开始,因为不使用变量 i
(以前的 numbers
)。input()
调用中添加了一些文本我想这可以解决你的问题。在您的代码编译器中尝试此代码。我希望你能得到你想要的输出。
count_of_numbers = int(input())
digits = []
for numbers in range(1, 2*count_of_numbers):
number = int(input())
digits.append(number)
for i in range(0, len(digits), 2):
if (i + 1) >= len(digits):
break
print(digits[i] + digits[i+1])
简短而甜蜜的解决方案。看看你是否喜欢。
您只需输入数字,它就会自动添加备用总和。
input_var = list(map(int,input("Enter The Numbers : ").split(' ')))
if len(input_var)%2 != 0:
input_var.append(0)
for x in range(0,len(input_var),2):
print(f"""The sum of {input_var[x]} and {input_var[x+1]} is : """,end=' ')
print(input_var[x] + input_var[x+1])
输出如下:
Enter The Numbers : 3 2 1 4 5 0 4
The sum of 3 and 2 is : 5
The sum of 1 and 4 is : 5
The sum of 5 and 0 is : 5
The sum of 4 and 0 is : 4
如果输入的长度是偶数则很好,如果不是则自动在最后一位加上0
希望你会喜欢。
谢谢你:)
如果您想添加一些输入验证以确保用户输入整数:
from typed_input import int_input # pip install typed_input
def main() -> None:
count_pairs = int_input('How many pairs will you like to add: ')
total = 0
for i in range(1, count_pairs + 1):
a = int_input(f'Enter number {i}: ')
b = int_input(f'Enter number {i + 1}: ')
a_plus_b = a + b
print(f'{a} + {b} = {a_plus_b}')
total += a_plus_b
print(f'Overall total = {total}')
if __name__ == '__main__':
main()
用法示例:
How many pairs will you like to add: 3
Enter number 1: 2
Enter number 2: 1
2 + 1 = 3
Enter number 2: 4
Enter number 3: 5
4 + 5 = 9
Enter number 3: 0
Enter number 4: 4
0 + 4 = 4
Overall total = 16