Printing and input in Python #2
In this article, we will start discussing the basics of Python including printing and input. To follow along, you can download an IDE like Visual Studio Code or use an online editor such as replit.com.
First, let's discuss printing. To print something in Python is as easy as this:
print("my first program")
My first program
This code will output "my first program". Pretty simple right? All you need is the function name print followed by parentheses with quotation marks inside to indicate you are using text (called a string in python). The text you would like to print goes inside the quotes. If you're coming from another programming language, you may have noticed the code segment had no semicolon at the end. Python does not use semicolons.
At this point, we can now print whatever we want. This is great, but it isn't really interesting to users of the program. What if we wanted the user to interact with our program? This is where input comes in
To read input, you use the Python function called input similar to the print function above. For example, the following code will read a string from a user:
input("What is your name? ")
What is your name? Bob
This will prompt the user for their name (after which they could enter a name like Bob). You may have noticed the space at the end of the quote. This allows some room, so the user can enter their name. If the space was omitted, the output would like this:
What is your name?Bob
You may have noticed nothing happened when the user entered their name. All we did was ask for their name after all. What if we wanted to print a greeting with their name? This is where variables come in. Currently, we just ask for their name without doing anything with it. Using a variable, we can store their response and do something with it:
name = input("What is your name? ")
print("Hello " + name)
What is your name? Bob Hello Bob
This code will prompt the user for their name and then print a greeting. The first code stores their response in a variable called name. The second line uses a new technique: concatenation. Concatenation allows you to combine two strings into one. The string "Hello " will combine with whatever name they enter such as "Bob". These two strings will combine into one string called "Hello Bob" which is then printed out.
Congratulations! You finished your first Python lesson. In the next lesson, we will discuss variables and data types.