Jump to content

Short version of if statments Python 3.x

Hey!

Is there a shorter version of this code in Python. Thanks! 

 



check = input("Put in the letter: ")
word = "word"

if(check == word[0]):
print(check)
else:
print("_")

if(check == word[1]):
print(check)
else:
print("_")

if(check == word[2]):
print(check)
else:
print("_")

if(check == word[3]):
print(check)
else:
print("_")

Link to comment
Share on other sites

Link to post
Share on other sites

 

Hey!
Is there a shorter version of this code in Python. Thanks! 
 
    check = input("Put in the letter: ")    word = "word"       if(check == word[0]):        print(check)    else:        print("_")    if(check == word[1]):        print(check)    else:        print("_")    if(check == word[2]):        print(check)    else:        print("_")    if(check == word[3]):        print(check)    else:        print("_")

 

print(check if (check == word[0]) else "_")

etc.

if a == b:    print("yes")else:    print("no")

is equivalent to

print("yes" if a == b else "no")
Link to comment
Share on other sites

Link to post
Share on other sites

Thanks!

You could also use elif (else if) statements to shorten it. Just so you know, you don't need parentheses in python around your if statement conditionals.

check = input("Put in the letter: ")word = "word" if check == word[0]:    print(check)elif check == word[1]:    print(check)elif check == word[2]:    print(check)elif check == word[3]:    print(check)else:    print("_")

That code is a bit better, but you could go one step further and use boolean operators (and, or, not) to make it even more concise

check = input("Put in the letter: ")word = "word" if check == word[0] or check == word[1] or check == word[2] or check == word[3]:    print(check)else:    print("_")

CPU: AMD FX-6300 4GHz @ 1.3 volts | CPU Cooler: Cooler Master Hyper 212 EVO | RAM: 8GB DDR3

Motherboard: Gigabyte 970A-DS3P | GPU: EVGA GTX 960 SSC | SSD: 250GB Samsung 850 EVO

HDD: 1TB WD Caviar Green | Case: Fractal Design Core 2500 | OS: Windows 10 Home

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×