17  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:

welcomeMsg = "Hello, James, welcome to Python."

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.

longerMsg = welcomeMsg + "I hope you enjoy yourself."

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.

longerMsg = welcomeMsg + " " + "I hope you enjoy yourself."

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

longerMsg = welcomeMsg + " I hope you enjoy yourself."

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:

yourName = TYPE_YOUR_NAME_HERE
Danger

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.")

yourDesigner = TYPE_A_DESIGNER_HERE

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