So far we have learned how to work with text data. Let's move on to how numbers work in Python.
Ensure that you are signed into your GitHub account
Accept the assignment: Project 2 - Temp Converter
Clone the repository to your computer using GitHub Desktop, or open it online using Codespaces
Open lab1.py
When you declared a variable in the past project you did so like this: name = "David"
The double quotation marks around the name mean that it is a string, text data. We can include a number in there though, so what's the problem?
As you can see, if we try to perform any sort of mathematical operation on these numbers, they are not treated numerically. It is just joining strings.
With numbers, we need to ditch the quotation marks. This tells Python that we want a different type of data.
Much better, we get the correct answer: 10
What is happening under the hood? Let's investigate data types using the type() function:
When you run the example above, you can see that num1 is a str (string, text data) and that num2 is an int (integer, whole number).
In addition to int for for whole numbers, we can use float for decimal numbers.
This poses a problem, run the example below and enter a number:
When we get input from the user, it is always a str.
We need to use a function to convert the input into the type of number we need.
Here we have used the float() function to convert our string into a a float, and the int() function to convert our second string into an int.
Complete the following requirements:
Define a variable 'a' and assign it an integer value
Define a variable 'b' and assign it a decimal value
Print the values and types of 'a' and 'b'
Ask the user for a whole number and store it in a variable 'x', converting to an integer
Ask the user for a decimal number and store it in a variable 'y', converting to a float
Print the values and types of 'x' and 'y'
Press Ctrl + F5 to run the program or open a terminal and type python lab1.py
The program should run without any errors and you should see that your variables are either <class 'float'> or <class 'int'>
You should now know the difference between strings, integers and floats in Python and be able to work with all three.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 1 complete"
Press Commit to main
Press Push origin
Here is a video from Harvard's CS50P course that covers the content of the next 3 labs. Optional, but useful if you need further explanation.