Variables

In a previous exercise, we learned to print different statements with print(""). While it is great to print out a number or a sentence, we haven’t given them a meaning. Variables are simply names that we can give to values such as strings, numbers, and booleans. Here’s how to make a variable named s in Python. We say s is a string that has the value "Hello, World!".

s = "Hello, World!"
x = 88
happy = True

Press run.

Screenshot of what variables example looks like in replit

Note that variables are not printed out to the console. Instead, the variable simply saves the string, number, or boolean into the computer’s memory. We can use these variables in other statements. For example, the following code would print "Hello Nuevo Foundation" to the console:

str1 = "Hello"
str2 = "Nuevo Foundation"
print(str1 + " " + str2)

You can also do the following to print strings together while adding spaces in between the words.

str1 = "Hello"
str2 = "Nuevo Foundation"
print(str1, str2)

What the Type!

Before learning how to create variables, we need to learn the concept of type. Type describes what is being stored in the box.

Python is a dynamically typed language, meaning, unlike languages like Java, you don’t have to specify the type of variable it is before you assign a value to it. And, if you have an integer in the box and then you remove the integer and place a string in the box, python will allow you to do that. But, you must use the variable based on the type.

The following are the important data types:

TypeDescriptionExamples
intinteger20, 30, 35
charcharacter such as a symbol or a single alphabet letter'A','b', '(', ']'
Stringa sequence of char"Hello", "Bonjour", "Hola"
booleanhas a value of either true or falsetrue, false
doublefractional numbers2.0, 3.14, 9.33

Let’s revisit the three variables we talked about in the first example and identify their data types. s is a string, x is an int, and happy is a boolean.

Challenge

Next, use the variables and what you learned in the previous activities to print out the following to the console. You must use the variables!

Computer
5
ComputerComputer
10
ComputerComputerComputer
15

Hint: If you’re stuck, consider using the + operator. Remember that you can use the variables comp and five multiple times in the same line!