简体   繁体   English

检查两个变量是否相等

[英]Checking if two variables are equal

In my code I'm making a basic multiplying game. 在我的代码中,我正在做一个基本的乘法游戏。

But in my game, 但是在我的游戏中

When you get the answer right, it says you got it wrong 当您得到正确答案时,它表示您弄错了

Here's my whole code: 这是我的整个代码:

import random

score = 0
while True:
    num1 = random.choice(range(1,12))
    num2 = random.choice(range(1,12))
    answer = num1 * num2
    a = input("Solve for " + str(num1) + "x" + str(num2))
    if a == answer:
        print("congrats you got it right")
        score += 1
    else:
        print("Wrong sorry play again")
        print("Score was: " + str(score))
        break

When I get the right answer I get 当我得到正确答案时,我得到

Solve for 7x10 70
Wrong sorry play again
Score was: 0

Other languages might let you get away with this, but Python is strongly typed. 其他语言可能会让您难以理解,但是Python是强类型的。 The input function gets a string, not a number. 输入函数获取字符串,而不是数字。 Numbers can't be equal to strings. 数字不能等于字符串。 Either convert the number to a string or the string to a number before you compare them. 在比较它们之前,要么将数字转换为字符串,要么将字符串转换为数字。 You can use str or int to convert. 您可以使用strint进行转换。

Function input returns what was typed as a string ... in order to compare it with the answer, you need to either convert it to int : 函数input返回键入为字符串的内容 ...为了将其与答案进行比较,您需要将其转换为int

if int(a) == answer:

or the other way around (convert answer to str ): 或相反(将答案转换为str ):

if a == str(answer):

The first one may raise an exception if a is not parseable to an int . 如果a无法解析为int则第一个可能引发异常。 Here the docs . 这里是文档

PS: I really wonder how ur random library picked a 1070 sampling from 0 to 11... PS:我真的很想知道您的随机库是如何从0到11选取1070个采样的...

Or use int(input()) : 或使用int(input())

import random

score = 0
while True:
    num1 = random.choice(range(1,12))
    num2 = random.choice(range(1,12))
    answer = num1 * num2
    a = int(input("Solve for " + str(num1) + "x" + str(num2)))
    if a == answer:
        print("congrats you got it right")
        score += 1
    else:
        print("Wrong sorry play again")
        print("Score was: " + str(score))
        break

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

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