Ramis Rafay
Ramis Rafay

Reputation: 33

How to create if statements using strings in python 3.x

So I decided to make some silly simple code to practice on my own, and I have trouble finding what it is im doing wrong. Python displays 'syntax error' but im not sure what im doing wrong.

>>> x= str(input("Select a colour: Red, Blue or Green"))
Select a colour: Red, Blue or Green:
>>>if x==str(Red):
...    print("Charmander")
...elif x==str(Blue):
...    print("Squirtle")
...elif x==str(Green):
...    print("Bulbasaur")
... else:
...    exit()

Upvotes: 1

Views: 7156

Answers (1)

Keatinge
Keatinge

Reputation: 4341

Couple things here..

  1. This isn't necessarily wrong (the code will still work) but there's no reason to convert input to a str, it already is a string
  2. Strings need to be in quotes, not inside str(). Use "Red" instead
  3. Maybe use better variable names, x is unclear
  4. The last exit is useless

Your code fixed would look something like:

selected_color = input("Select a colour: Red, Blue or Green ")
if selected_color == "Red":
    print("Charmander")
elif selected_color == "Blue":
    print("Squirtle")
elif selected_color == "Green":
    print("Bulbasaur")

Improvements

Since you are just converting a colour to a pokemon you could use a dict here

pokemonColors = {"Red" : "Charmander", "Blue" : "Squirtle", "Green" : "Bulbasaur"}
print(pokemonColors[input("Select a colour: Red, Blue or Green ")])

Notice that this will give a KeyError for a color not in the dict, you could use .get() with a default to fix this if you want though.

Upvotes: 5

Related Questions