Sunday, October 19, 2014

Intro to Python: Getting input

Intro to Python: Basic input

In my previous tutorial, I went over how to print out basic texts to the terminal. That's all fun and games, but what if we also want to receive input from the user as well? Let's say, for the sake of example, that we are making a text-based RPG and we wish to have the player enter a name for our hero. This is done in python by using a method called raw_input().

To use our previous example, one thing I could do is this:

print("What is your name?")
name = raw_input() 

Now, when we run this program in the codeacademy labs, we should get this as the output:

Code Explanation


 As you can see, I got the output "What is your name?". On a new line, I inputted the name. I used my name Chris here as an example, but you can put in whatever name you want.

Now, let's go through the code each line.

print("What is your name?")

This line will output the text "What is your name?" to the screen. 

name = raw_input()  

This line is getting input from the user. You may have noticed that I am making a variable called name and assigning it to the input. Don't worry about that too much right now, just know that now the variable name is equal to whatever input I got from the user. 

 String Concatenation

I can add an extra line of code such as

print("Hello " + name + "!")  

to the end of the code. Now, when I run the program I get this output:


 In the last line of code, what I did is concatenate the strings with a variable. This sounds complicated, but it's actually very simple. Concatenation just means you are adding to things together. In this case, I am adding the strings together.

To give another example of this, I could do something like:

print("Hello " + "World" + "!")  

This will give me the output:


See? Simple! Try getting the input from the user with new variables now to see if you fully understand. If the program doesn't run correctly the first time, don't worry. Just double check your program to see if there are any simple mistakes. If you still can't get it, reread this tutorial or find other examples of code online to help you.

In my next tutorial, I will be going over if and else statements and using them with variables.


 
 

 

No comments:

Post a Comment