简体   繁体   中英

Python if statement not functioning

print("Hello World")
myName = input("What is your name?")
myVar = input("Enter a number:")
if myName == "MZ" or myVar != 0:
    print("MZ is great")
elif myName == "MV":
    print("MV is ok")
else:
    print("Hello World")

No matter what I input as name myName or number myVar , it always prints MZ is great .

Please help. Thanks

First off, MZ is great!

This happens because of or myVar != 0 . Since input() returns a string (in Python 3) and you compare it to a number, myVar will never be equal to the number 0. You should do something like:

myVar = int(input("Enter a number:"))

You should probably also catch ValueError in case the user types a bad number.

Change

if(myName == "MZ" or myVar != 0)

to

if(myName == "MZ" or myVar != "0")

User input is string by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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