Unit 2 · Python mode... Activate! · Lesson 16 of 57
Input
You made the variable company_name in the last lesson, and you gave it the value CyberAcad
The thing that sucks about that is... what if we want company_name to not only be CyberAcad, but be say... Microsoft, or Apple, or Google?
Well, I could just make you change what's in the string four times, but that is soooooooooooooo boring!
What if you could, perchance, type text directly INTO the screen and store it in a variable?
Introducing: input()
There's a function for that! It's called input().
Remember how return teleports a value back to wherever the function was called? input() does the exact same thing, except the value is whatever the user types.
company_name = input("What company? ")
Here's what happens:
- Python shows
What company?in the console and waits. - You type something, like
Microsoft, and press Enter. input()teleports"Microsoft"back to where it was called...- ...which means the line turns into
company_name = "Microsoft"!
The string inside the parentheses is the question you ask the user. It's optional, but please be nice and ask something. (A blank console just silently waiting for you is kind of creepy.)
Notice the space at the end of
"What company? "? That's so whatever you type doesn't get squished right up against the question mark. Python won't add spaces for you, remember?
Let's say hi to ourselves!
- Use
input()to ask for a name, and store it in a variable calledname. - Print
Helloand the name glued together, with a!at the end.
When you run it, type your name into the console and press Enter. If your name is Rishabh, it should print:
Hello Rishabh!
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.