简体   繁体   English

求和/平均值/乘积

[英]Sum/ average / product in python

I am trying to write a program which asks an input of two numbers and then prints the sum, product and average by running it. 我正在尝试编写一个程序,要求输入两个数字,然后通过运行它来打印总和,乘积和平均值。 I wrote a program but it asks an input for 2 numbers everytime i need a sum or average or product. 我写了一个程序,但是每次我需要求和,求平均值或乘积时,它都会要求输入2个数字。 How can I get all 3 at once, just making two inputs once. 我如何一次获得全部3个,而又一次输入2个。

sum = int(input("Please enter the first Value: ")) + \
      int(input("Please enter another number: "))
print("sum = {}".format(sum))

product = int(input("Please enter the first Value: ")) * \
          int(input("Please enter another number: "))
print ("product = {}".format(product))

You need to assign your numbers to variables and then reuse them for the operations. 您需要将数字分配给变量,然后将其重新用于操作。

Example

x = int(input("Please enter the first Value: "))
y = int(input("Please enter another number: "))

print("sum = {}".format(x+y))
print("product = {}".format(x*y))
print("average = {}".format((x+y)/2))

You're going to want to get the numbers first, then do your operation on them. 您将要首先获取数字,然后对它们进行操作。 Otherwise you're relying on the user to alway input the same two numbers: 否则,您将依靠用户始终输入相同的两个数字:

a = int(input("Please enter the first Value: "))
b = int(input("Please enter the second Value: "))

print ("sum = {}".format(a+b))
print ("product = {}".format(a*b))
print ("average = {}".format((a*b)/2))

Use variables to store the input: 使用变量存储输入:

first_number = int(input("Please enter the first Value: "))
second_number = int(input("Please enter another number: "))

sum = first_number + second_number
product = first_number * second_number
average = (first_number + second_number) / 2

print('Sum is {}'.format(sum))
print('product is {}'.format(product))
print('average is {}'.format(average))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM