Skip to content

Latest commit

 

History

History
57 lines (57 loc) · 2.76 KB

File metadata and controls

57 lines (57 loc) · 2.76 KB

< Previous       Next >


Whether it's in the form of them entering a username, or password, using a keyboard to control a player in a game, or moving around with a mouse, there's a lot of coding that's responding to input from users.
In the programs you've been working on, if you want the user to enter information with a keyboard you'll use the input function.
Add the following code to a python program:
input("Input You're Asking For")
A small cursor will appear in your output, and you can now type in the output!
In the output area, type something like: "then you can type"

Setting Input to Variables

You can also initialize a variable to input, so to get someone's name as input and then store it as a variable:
name = input("What's your name?\n")
print(name)

Combining Strings and Ints

When you print information out, you may want to combine multiple types of text, like a variable and a string.
To see it in action, add the following code to your program:
print("Hey " + name + " how are you?")
When you run that program, you'll see it all print out as one line. It works with no errors because the name variable is also a string.
Anything you enter with the input function will end up being a string.
In Python print statements can't print out numbers and strings together, it can only print out one type. So to make a number a string you can put str() before it.
age = 14
age_as_word = str(age)
print("You're " + age_as_word)
Then, if you want to make a string into a number, only if it converts, you'd put it between the parenthesis in int() .
Change your program to:
age = "14"
age_as_number = What would you write here?
What would you set the variable age_as_a_number equal to, to turn the string into an int? age_as_num = int(age)
print(age_as_number + 3)
Input has a lot more to it, but as long as you or people you know are the main users, this is a good start. Converting numbers to strings so you can display them, or converting strings to numbers so you can do math operations are a good place to get you started!

Recap

Now you know you can get input from users, and save that information to a variable for your program to use. Also you have some tools for dealing with input that needs to be changed to a number or a string.
Create a new program with at least one input from a user.
Convert the input to an int, or other information to a string to use it in your program!