18 Python Strings, Input, and Variables
One of the key things in wrangling data is understanding how strings and variables work in Python.
The file used in the screencast is called “name.py” and is made up of these elements below, the code will all work in Jupyter notebooks.
We know how to print out strings:
print("Hello, James, welcome to Python.")
But we can also store strings in a variable, so that we can use them later:
= "Hello, James, welcome to Python." welcomeMsg
A variable is a box with a name, we can get the contents of the box by using its name. This prints the same thing as above.
print(welcomeMsg)
We can also join strings together, using a + character.
= welcomeMsg + "I hope you enjoy yourself."
longerMsg
print(longerMsg)
# ==> Hello, James, welcome to Python.I hope you enjoy yourself
Hmmm, that doesn’t have a space between the sentences. Let’s add a space. Now we’re joining three strings together.
= welcomeMsg + " " + "I hope you enjoy yourself."
longerMsg
print(longerMsg)
# ==> Hello, James, welcome to Python. I hope you enjoy yourself.
You could also do this by adding a space at the start of the second string
= welcomeMsg + " I hope you enjoy yourself." longerMsg
Q: Why is this all printing on a line single?
A: Because the strings are joined together before being passed to print you get a newline after each print statement, one statement, one newline.
So now we output variables. Eventually we will read variables from csv files, but for now we can declare them directly:
= TYPE_YOUR_NAME_HERE yourName
In previous years we have used the input
function which brings up a text entry field. DataCamp doesn’t support this.
When you press enter whatever you typed is put into the yourName variable. Now you can personalize the message:
print("Hello " + yourName + ", welcome to Python.")
= TYPE_A_DESIGNER_HERE
yourDesigner
print("That's a lovely outfit, " + yourDesigner + " is so fetch.")
In addition to our recorded class, I have a screencast from a previous year. The code is the same as above. Introduction to Strings and Variables