Python: User Input and If/Elif/Else statements.

In today’s lesson I will teach you how to get user input, and how to use if statements, else statements, and elif(else if) statements.First, you must understand what a variable is. A variable is basically a way to store something that can vary. That is important to know for this lesson
because it is the easiest way to store user input. Here is a basic example:

print("Hello, what is the secret word?")
word = raw_input("Secret Word: ")
print("You entered: %s"%(word))

In this example, we print a message, get user input, and the return it in a message. Now, how can we check if the password is correct? That’s where if statements come in.

if word == "pineapple":
	print("You guessed correct!")

Now, if the word is correct, it prints a message. What if we want to tell someone that they are getting close, and when they are wrong? That’s where you use elif and else statements.

elif word == "apple":
	print("Almost there!")

Now, if the user types in ‘apple’, the program will tell them that they are close, but if it isn’t ‘pineapple’ or ‘apple’, then it will go to the else statement, which then returns ‘Wrong!’. Remember that it will ignore everything else if it matches one of the conditions, so if it is correct, the program will exit after printing ‘You guessed correct!’, while if it is apple, it will skip the first part and return ‘Almost there!’, and then exit. I hope you learned somethiing in this lesson, and check back soon for more!!!

Note: You must put the above code blocks in order in a .py file for the program to work(keep all spaces, but be sure to change the text in quotes to learn!).

Complete script.

Leave a Reply(Markdown is On)