繁体   English   中英

Python 3:基本算术运算

[英]Python 3: Basic arithmetic operations

我正在尝试编写一个程序来执行简单的算术运算。 我希望程序提示用户输入两个数字,然后计算五个结果:

  • 总和
  • 区别
  • 产品
  • 根据两个整数的商
  • 浮点除法。

现在,我记得在Python 2中 ,通常有raw_input用于字符串和数字输入。 但是,我只是在学习Python 3 ,默认情况下输入是一个字符串,对于数字,我必须指定希望拥有的数字类型:即int(input())或float(input())。

因此,例如,让我们假设我想要完全具有此输出(使用输入4和2.5):

What is the first number? 4
What is the second number? 2.5
The sum is 6.5
The difference is 1.5
The product is 8.0
The integer quotient is 2
The floating-point quotient is 1.6

我将在Python 2中键入以下代码:

x=input ("What is the first number? ")
y=input ("What is the second number? ")

print "The sum is", x+y
print "The difference is", x-y
print "The product is", x*y
print "The integer quotient is", int(x)/int(y)
print "The floating-point quotient is", float(x)/float(y)

但是,我无法在Python 3中完成它。 这是我正在使用的(错误)代码:

x = int(input("What is the first number? "))
y = int(input("What is the second number? "))

print("The sum is: ", x+y)
print("The difference is: ", x-y)
print("The product is: ", x*y)
print("The integer quotient is: ", x/y)
print("The floating-point quotient is: ", x/y)

显然,我收到一条错误消息,因为我的第二个输入(y)等于4.5,它是一个浮点数,而不是我的输入定义的int值 我不必理会把float(x)/ float(y)用作浮点商,因为那也将是矛盾的(因此是错误的)。

我当然可以这样放置float而不是int:

x = float(input("What is the first number? "))
y = float(input("What is the second number? "))

但是在这种情况下,我的产品将得到10.0(而不是10),我的整数商是浮点数(1.6而不是2)

我感到非常沮丧的是,在Python 3中,我不能要求输入通用的类型编号(而不必指定它是float还是int)。 因此,我坚持使用这种简单的程序,不胜感激任何解决方案/说明。

您可以尝试将输入解析为int ,如果不起作用,请将其视为float

def float_or_int(x):
    try:
        return int(x)
    except ValueError:
        return float(x)

x = float_or_int(input("What's x?"))
y = float_or_int(input("What's y?"))

要在Python 3中进行地板分割,您必须使用//运算符明确要求它:

print("The integer quotient is:", x//y)

请注意,对于浮点输入,此“整数商”操作实际上没有任何意义。

暂无
暂无

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

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