【问题标题】:Comparing 3 entered integers in python比较python中输入的3个整数
【发布时间】:2013-09-19 15:53:52
【问题描述】:

我正在尝试执行以下操作:

编写一个程序,读取三个数字并打印“all the same” 如果它们都相同,“都不同”如果它们都不同, 否则“都不是”。

您的程序应该通过 3 个输入语句请求 3 个整数。用一个 if、elif 和 else 的组合来实现算法 这个问题需要的。

但是,每当我输入所有相同的整数时,我都会得到“都一样”和“都不一样”。如何使我的“都不正确”部分正确?

x=input('enter an integer:') 
y=input('enter an integer:') 
z=input('enter an integer:') 
if x==y and y==z: print('all the same') 
if not x==y and not y==z: print('all different') 
if x==y or y==z or z==x: print('neither')

【问题讨论】:

  • 欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。您提供的详细信息越多,您可能收到的答案就越多。
  • PS:看看input()(或Python 2.x 中的raw_input())。其余的应该是微不足道的。
  • x=input('enter an integer:') y=input('enter an integer:') z=input('enter an integer:') if x==y and y==z: print('all the same') if not x==y and not y==z: print('all different') if x==y or y==z or z==x: print('neither') 每当我输入所有相同的整数时,我得到的都是相同的,但两者都不相同。我怎样才能使我的“都不正确”部分正确?
  • 请将该代码编辑到您的问题中 - cmets 会破坏代码格式。
  • -x=input('enter an integer:') -y=input('enter an integer:') -=input('enter an integer:') -if x==y and y==z: print('all the same') -if not x==y and not y==z: print('all different') -if x==y or y==z or z==x: print('neither')

标签: python python-3.x


【解决方案1】:

这里的问题是您对每种情况都使用if。这意味着无论如何都要评估所有案例,并且多个案例都可能为真。

例如,如果所有三个变量都为 1,则案例评估如下:

>>> x = 1
>>> y = 1
>>> z = 1
>>> if x == y and y == z: print("all the same")

all the same
>>> if not x == y and not y == z: print("all different")

>>> if x == y or y == z or z == x: print('neither')

neither
>>> 

你想使用elif(else if)和elsesee the flow control documentation),这样你的条件就变得互斥了:

>>> x = 1
>>> y = 1
>>> z = 1
>>> if x == y and y == z: print("all the same")
elif not x == y and not y == z: print("all different")
else: print("neither")

all the same
>>> 

【讨论】:

    【解决方案2】:

    我的建议是: 1)使用输入 2) 使用 if、elif 和 else 子句

    这样的?

    x = input("Enter the 1st integer")
    y = input("Enter the 2nd integer")
    z = input("Enter the 3rd integer")
    
    if x == y and y == z:
        print("All the numbers are the same")
    
    elif x!= y and y != z: # or use elif not and replace all != with ==
        print("None of the numbers are the same")
    
    else:
        print("Neither")
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2012-08-27
      • 2022-12-04
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      相关资源
      最近更新 更多