Return to Level1Techs.com

Learning Python: Tell me what I'm doing wrong

I’m trying to make simple program that asks the user “Who shot first?”

a) I need to know how I can make different inputs (such as: ‘Han’, ‘han’, ‘Han Solo’, and ‘han solo’) equal the variable “name”.

b) I need to know how to make the program print a new line after asking the user the question.

Here is what I have so far.

 name = str(input('Who shot first?'))  #  Asks the user a question and stores the input as a variable.
 
 if name == 'Han':  #  Replies accordingly to the users input.
     print('Thats right!')
 if name == 'Greedo':
     print('Wrong! Greedo did not shoot first.')
 else:
     print('Incorect! Han shot first.')

I also just realized that I get this output when entering “Han” It prints both answers when it should only be printing one.

a) make the input string lowercase (make the strings in ifs to be lowercase too), then maybe split it by spaces (to get the words) and check if the word array contains relevant names (edge case if array contains both “han” and “greedo”);

b) add \n (line feed, aka new line) inside the input string.

About your edit, that’s coz you need 2nd if to be elif (aka else if)

3 Likes

Ah, perfect. That fixed both of those issues.

However I’ll have to look up how to make arrays.

All you need to do is use string split function. I don’t recall the exact signature (I barely use python) so check with the reference and docs.

As for actual arrays pretty sure you can just use lists. (Does vanilla python even has static arrays? :thinking:)

1 Like

Wait, you might not even need to split. Python must have something along the lines string.contains('han')I bet it does.

This is what I’ve come up with.

  # This program is to ask the user a question.

name = str(input('Who shot first?\n'))  #  Asks the user a question and stores the input as a variable.

if name in ('Han', 'han', 'han solo', 'Han Solo'):  #  Replies accordingly to the users input.
    print('Thats right!')
elif name == 'Greedo':
    print('Wrong! Greedo did not shoot first.')
else:
    print('Incorect! Han shot first.')

It seems to work.
image

1 Like

you can use lower() to shorten your lists and account for capitalization errors:

name = input().lower()
if name in ['han', 'han solo', 'solo', 'hansolo', 'hs']:
    print("That's right!")
elif name in ['greedo', 'gredo', 'g']:
    print('Wrong!')

You can also use double quotes instead of single quotes in this case, since “That’s” is a contraction, and using single quotes would close the string before the “s”.

1 Like

You don’t have to split it, but if you did, you could use:

name = input().lower().split()
if ((i in ['han', 'solo']) for i in name):
    print("That's right!")

or you could use the generator using the input string itself

name = input().lower()
if (i in name for i in ['han', 'solo']):
    print("That's right!")
1 Like