【问题标题】:Program does not return "Correct" even when the right answer is input即使输入正确答案,程序也不返回“正确”
【发布时间】:2021-02-14 11:26:58
【问题描述】:

我上个月开始学习 Python。即使输入正确答案,以下程序也不会返回“正确”:

import random
n1 = random.randint(2,22)
 
import random
n2= random.randint(1,20)

ans=n1+n2

message = input(f"Enter the answer to the question: {n1}+{n2}=")

print(f"Your answer is {message}")

if message == 'ans': 
    print("Correct")

elif message != 'ans':
    print("Wrong")

input()

【问题讨论】:

  • ans 就位 'ans'' ' 表示字符串不可变
  • 另外,ans 是一个数字,message 是一个字符串,所以它们永远不会相等。您需要将答案转换为整数:message = int(input(.....))
  • 在解释什么是变量之前,您从哪个教程中学习介绍了模块导入和格式字符串?请改用official Python tutorial

标签: python random


【解决方案1】:

你的代码有两个问题:

  1. 您正在与文字字符串 'ans' 进行比较,但您需要与 ans 对象进行比较。
  2. 您需要将用户输入转换为int;默认input的类型是str。
    import random
    n1 = random.randint(2,22)
    
    n2= random.randint(1,20)
    
    ans=n1+n2
    
    message = int(input(f"Enter the answer to the question: {n1}+{n2}="))
    
    print(f"Your answer is {message}")
    
    if message == ans: 
        print("Correct")
    else:
        print("Wrong")
    
    input()

此外,您不需要两次导入同一个模块,您可以使用 if-else 代替 ifelif 来解决您的问题。

【讨论】:

    【解决方案2】:

    蟒蛇式的方式

    import random
    
    n1, n2 = random.randint(2, 22), random.randint(1, 20)
    message = int(input(f"Enter the answer to the question: {n1}+{n2}="))
    
    print(f"Your answer : {message}")
    print("Correct") if n1 + n2 == message else print("Wrong")
    

    【讨论】:

      猜你喜欢
      • 2023-01-24
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多