Data
A fundamental aspect of programming is working with data and manipulating it to produce a desired result. In this section, we will look at the different types of data that can be used in a program and how to manipulate it.
Data Types
In programming, data is classified into different types and the type determines how the data can be used. It is also vital to know what data type to use where. For example, you normally do not want to use a letter to keep track of money.
The various data types are (there are more, but these are mostly used in Python):
Integer:
This is a whole number. Python refers to it as int. An example of an integer is 1.
Floating Point Number:
This is a number with a decimal point. Python refers to it as float. An example of a floating point number is 1.0.
String:
This is text. Python refers to it as str. An example of a string is "Hello World".
Boolean:
This is a True or False value. Python refers to it as bool.
type(1) # int
type(1.0) # float
type("Hello World") # str
type(True) # bool
print(type(1)) # To print the type on the console
You can use the type()
function to check the type of value you are working with.
Variables
Variables are used to store data. They are like containers that hold data and usually give data meaning.
apples = 1 # (1) Creates a variable
isCandy = False
cost = 1.0
goodbyeMessage = "Thank you for buying!"
apples = 6 # (2) Overides the value
bananas = 2
bananas = apples # (3) Copies the value of apples to bananas
print(bananas) # (4) Prints the value of bananas
print(type(bananas)) # (5) Prints the type of bananas
- The syntax for creating a variable is
<variable name> = <value>
. - You can reassign a variable by using the same syntax. The variable will use the new value you store.
- When using a variable, it is just a placeholder for a value. So you can use it to store the value of another variable.
- You can print the value of a variable by using the print function.
- You can check the type of a variable by using the type function.
The name of the variable is always on the left side of the equal sign, the equal sign means we are giving a value to the variable on the left. The value is always on the right side of the equal sign. Like shown above, you can put a variable on the right side as well and it will refer to the value stored in that variable. This whole process is called assignment.
Basic Expressions
Expressions are calculations that can be done to data. They are used to manipulate data. Expressions include addition, subtraction, multiplication, and division.
1 + 1 # (1) The basics operations in Python
2 - 1
2 * 2
4 / 2
variable = 1 + 1 # (2) The result of an expression can be stored in a variable
apple = 1
banana = 2
fruits = apple + banana # (3) Expressions can use variables
banana = banana + 1 # (4) Adds 1 to the previous value of banana
- The operations are just like in math.
- Expresssions are evaluated first and the result is used.
- Expressions can use variables because variables are just placeholders for values.
- Values on the right are evaluated first and then assigned so this is valid.
Expressions will have operators which are the symbols that perform operations. This includes things like the plus sign (+). The operands are the values that are being operated on. Variables can be used as operands because they store values.
When an expression is assigned to a variable, the expressions on the right side will be evaluated first and then the result will be stored in the variable on the left side. This means the variable on the left can be assigned to the same variable on the right. Like the example banana = banana + 1
above. Here the banana was 2. The stuff on the right is evaluated first which ends up equaling 3. Then the value of 3 is stored in the variable banana.
More Operators
Two more operators that are commonly used are the modulus operator (%) and the exponent operator (**). The modulus operator returns the remainder of a division. The exponent operator raises a number to a power.
print(5 % 2) # (1) Returns the remainder of 5 divided by 2
print(2 ** 3) # (2) Raises 2 to the power of 3
- The modulus operator is used to get the remainder of a division.
- The exponent operator is used to raise a number to a power.
Order of Operations
(1 + 1) * 2 - 1 + 3 / 1 # Valid complex expression
Expressions can have more than one operator. In this case, the order of operations is used to determine which operation is done first and the order is similar to math. The order of operations is:
- Parantheses ()
- Exponents **
- Negation -
- Multiplication *, Division /, Modulus % [Left to right]
- Addition +, Subtraction - [Left to right]
Negation refers to the negative sign on numbers.
Other Data Types
Operations can be done on other data types as well.
Floats can do all the operations that integers can do. They can also do the modulus operator. The only difference is that the result will be a float. For example, 5.5 % 2.5
will return 0.5
because 2.5 * 2
is 5
and the remainder that remains is 0.5
.
1.3 + 1.0 # Equals 2.3
2.7 - 1.6 # Equals 1.1
3.7 * 2.0 # Equals 7.4
7.4 / 3.1 # Equals 2.3870967741935485
7.2 % 3.0 # Equals 1.2
Strings can be added together. This is called concatenation. For example, "Hello" + " World"
will return "Hello World"
. Strings can also be multiplied by an integer. This will repeat the string that many times. For example, "Hello" * 3
will return "HelloHelloHello"
.
"Hello" + " World" # Equals "Hello World"
"Hello" * 3 # Equals "HelloHelloHello"
Integers can also do integer division which is division that returns an integer. This is done by using the double slash operator (//). For example, 5 // 2
will return 2
because 2 * 2
is 4
and 5 - 4
is 1
. The remainder is ignored.
5 // 2
Casting
When working with data, sometimes it is common to convert data from one type to another. This is called casting.
Examples of casting involve converting a number to a string to add it to a string or converting a float to an integer to get rid of the decimal point or even converting a string to an integer to use it in an math expression.
str(1) # (1) string casting
str(1.0)
int(1.0) # (2) integer casting
int("1")
float(1) # (3) float casting
float("1.0")
- It will convert any value to a string if possible.
- It will convert any value to an integer if possible.
- It will convert any value to a float if possible.
Casting will give an error if the value cannot be converted to a new type. For example, int("Hello")
will give an error because "Hello"
cannot be converted to an integer.
Stored Values
One common mistake is writing expressions or values but not storing them in a variable or using them.
1 # (1) Not stored values
float(1)
"Hello" + " World"
var = 1 # (2) Stored values
- These values are not stored in a variable so they are not used.
- This value is stored in a variable so it is used.
All the lines in the example above are legal so no errors will be thrown. However, the first three lines are not stored in a variable so they will be lost. Python will evaluate the expression but you cannot use that value for anything.
Taking Input
Usually we build programs that take in some sort of input from the user and do calculates to come up with a result or output to show to the user. An example of this is a calculator. The user will input two numbers and the program will add them together and show the result.
So far we have worked with the print
method that prints out a value to a console. Python has a input
method that similarly prints a value to the console but also waits for the user to input a value. The inputted value is always a String.
input("Enter a number: ") # Gets input from the user
var2 = input("Enter a word: ") # Stores the input in a variable
Both inputs are strings even if we ask for a number! To take a number as input, we need to just cast the string to a number.
Also do note that we can get input from the user but there is no value if we don't store it in a variable to do something with it.
Comments
Now that the programs are getting longer and more complex, it is good habit to write comments. These are lines of text that are ignored by the program and are used as useful notes for the programmer. It is good practice to explain what the program is doing because it is easy to forget while writing complex programs.
# (1) This is a comment
print("Hello World") # (2) This is also a comment
var = 12
# var = 13 (3)
- Comments start with a hash
#
and continue to the end of the line. - Only text after the hash
#
is ignored. - The variable still holds a value of 12 because line 5 is ignored by the program.
Choosing Variable Names
Variable names can be any length and can contain letters, numbers, and underscores. They cannot start with a number. They cannot contain spaces or special characters. They cannot be the same as a keyword (A word reserved by python).
Valid Names | Invalid Names |
---|---|
var | 1var |
var1 | var 1 |
var_1 | var-1 |
var_one | var.one |
A good rule of thumb is to make variable short names which describe its purpose. It makes it easier to read and understand the code.
In Python, it is common to keep variable names in lowercase and use underscores to separate words. This is called snake case. For example, my_variable
.