Python IF ELSE语句现在正在工作[重复](Python IF ELSE statement not working [duplicate])

这个问题在这里已有答案:

简单的python if语句不工作 1回答

一些简单的问题。 我有我的第一个程序,我正在尝试使用python。 IF ELSE声明无效。 即使用户输入了正确的数字,输出仍然是“不正确”。 我很好奇,如果随机数和用户输入是不同的数据类型。 在说我尝试将两者都转换为int而无济于事。

代码如下:

#START from random import randrange #Display Welcome print("--------------------") print("Number guessing game") print("--------------------") #Initilize variables randNum = 0 userNum = 0 #Computer select a random number randNum = randrange(10) #Ask user to enter a number print("The computer has chosen a number between 0 and 9, you have to guess the number!") print("Please type in a number between 0 and 9, then press enter") userNum = input('Number: ') #Check if the user entered the correct number if userNum == randNum: print("You have selected the correct number") else: print("Incorrect")

This question already has an answer here:

simple python if statement not working 1 answer

I have my first program I am trying to make using python. The IF ELSE statement is not working. The output remains "Incorrect" even if the correct number is inputted by the user. I'm curious if it's that the random number and the user input are different data types. In saying that I have tried converting both to int with no avail.

Code below:

#START from random import randrange #Display Welcome print("--------------------") print("Number guessing game") print("--------------------") #Initilize variables randNum = 0 userNum = 0 #Computer select a random number randNum = randrange(10) #Ask user to enter a number print("The computer has chosen a number between 0 and 9, you have to guess the number!") print("Please type in a number between 0 and 9, then press enter") userNum = input('Number: ') #Check if the user entered the correct number if userNum == randNum: print("You have selected the correct number") else: print("Incorrect")

最满意答案

在Python 3 input返回一个字符串,你必须转换为int :

userNum = int(input('Number: '))

请注意,如果输入不是数字,则会引发ValueError 。

On Python 3 input returns a string, you have to convert to an int:

userNum = int(input('Number: '))

Note that this will raise a ValueError if the input is not a number.

更多推荐