A type is how Python represents different types of data.
print('Hello, Python!')
In this section, we will discuss some widely used types in Python.
You can have different types in Python. They can be integers like 11, real numbers like 21.213, they can even be words.
Integers, real numbers, and words can be expressed as different data types.
The following chart summarizes three data types for the last examples.
11 | int |
---|---|
21.3 | float |
"Hello Python" | string |
The first column indicates the expression. The second column indicates the data type.
We can see the actual data type in Python by using the type command.
type(12)
type(2.14)
type("Hello, Python 101!")
We can have int, which stands for an integer and float that stands for float, essentially a real number.
The type string is a sequence of characters.
-4,4,0,1,2,5,55 are some integers. Integers can be negative or positive. It should be noted that there is a finite range of integers but it is quite large.
Floats are real numbers. They include the integers but also numbers in between the integers. Consider the numbers between 0 and 1. We can select numbers in between them.
These numbers are floats. Similarly, consider the numbers between 0.5 and 0.6. We can select numbers in between them.
You can change the type of the expression in Python, this is called typecasting. You can convert an int to a float.
For example, you can convert or cast the integer 2 to a float 2.0. Nothing really changes, if you cast a float to an integer, you must be careful. For example, if you cast the float 1.1 to 1, you will lose some information.
# Convert 2 to a float
float(2)
# Convert integer 2 to a float and check its type
type(float(2))
# Casting 1.1 to integer will result in loss of information
int(1.1)
If a string contains an integer value, you can convert it to int. If we convert a string that contains a non-integer value, we get an error.
# Convert a string into an integer
int('1')
# Convert a string into an integer with error
int('1 or 2 people')
# Convert the string "1.2" into a float
float('1.2')
You can convert an int to a string or a float to a string.
# Convert an integer to a string
str(1)
# Convert a float to a string
str(1.2)
Boolean is another important type in Python. A Boolean can take on two values. The first value is True, just remember we use an uppercase T. Boolean values can also be False with an uppercase F.
# Type of True
type(True)
# Type of False
type(False)
Using the type command on a Boolean value, we obtain the term bool.
This is short for Boolean, if we cast a Boolean True to an integer or float, we will get a 1. If we cast a Boolean False to an integer or float, we get a 0.
If you cast a 1 to a Boolean, you get a True. Similarly, if you cast a 0 to a Boolean, you get a False.
# Convert True to int
int(True)
# Convert 1 to boolean
bool(1)
# Convert 0 to boolean
bool(0)
# Convert True to float
float(True)
Expressions describe a type of operation the computers perform.
Expressions are operations the python performs, for example, basic arithmetic operations like adding multiple numbers.
We call the numbers operands and the math symbols in this case, addition, are called operators.
We can perform operations such as substraction using the subtraction sign.
We can perform multiplication operations using the asterisk.
We can also perform division with the forward slash. 25 / 5 is 5.0. 25 / 6 is approximately 4.167. In Python 3 the version we will using in this course, both will result in a float.
# Addition operation expression
43 + 60 + 16 + 41
# Subtraction operation expression
50 - 60
# Multiplication operation expression
5 * 5
# Division operation expression
25 / 5
We can use double slash for integer division, where the result is rounded.
# Integer division operation expression
25 // 5
# Integer division operation expression
25 // 6
Be aware, in some cases the results are not the same as regular division. Python follows mathematical conventions when performing mathematical expressions.
# Mathematical expression
30 + 2 * 60
The expressions in the parenthesis are performed first.
# Mathematical expression
(30 + 2) * 60
We can use variables to store values. We can then use the value somewhere else in the code by typing the exact name of the variable.
# Store value into variable
x = 43 + 60 + 16 + 41
The old value of the variable is not important. We can store the results of expressions in variables.
We can also perform operations on x and save the result to a new variable, y.
# Use another variable to store the result of the operation between variable and value
y = x / 60
y
# Overwrite variable with new value
x = x / 60
x
We can use the type command in variables as well. It's good practice to use meaningful variable names, so you don't have to keep track of what the variable is doing.
It's common to use the underscore to represent the start of a new word, you could also use a capital letter.
# Name the variables meaningfully
total_min = 43 + 42 + 57 # Total length of albums in minutes
total_min
# Name the variables meaningfully
total_hours = total_min / 60 # Total length of albums in hours
total_hours
# Complicate expression
total_hours = (43 + 42 + 57) / 60 # Total hours in a single expression
total_hours
In Python, a string is a sequence of characters.
# Use quotation marks for defining string
"Michael Jackson"
A string is contained within two quotes. You could also use single quotes.
A string can be spaces or digits.
A string can also be special characters. We can bind or assign a string to another variable.
It is helpful to think of a string as an ordered sequence.
# Use single quotation marks for defining string
'Michael Jackson'
# Digitals and spaces in string
'1 2 3 4 5 6 '
# Special characters in string
'@#2_#]&*^%$'
# Print the string
print("hello!")
# Assign string to variable
Name = "Michael Jackson"
Name
Each element in the sequence can be accessed using an index represented by the array of numbers.
We can also use negative indexing with strings. The last element is given by the index negative one.
We can bind a string to another variable.
We can treat the string as a sequence and perform sequence operations.
# Assign string to variable
Name = "Michael Jackson"
Name
# Print the first element in the string
print(Name[0])
# Print the element on index 6 in the string
print(Name[6])
# Print the element on the 13th index in the string
print(Name[13])
# Print the last element in the string
print(Name[-1])
# Print the first element in the string
print(Name[-15])
# Find the length of string
len("Michael Jackson")
We can also input a stride value i.e. select a variable after a stride or jump of a given length.
# Get every second element. The elments on index 1, 3, 5 ...
Name[::2]
# Get every second element in the range from index 0 to index 4
Name[0:5:2]
We can also incorporate slicing. In this, we return value from a particular start and end.
# Take the slice on variable Name with only index 0 to index 3
Name[0:4]
# Take the slice on variable Name with only index 8 to index 11
Name[8:12]
We can use the len command to obtain the length of the string.
We can concatenate or combine strings. We use the addition symbols. The result is a new string that is a combination of both.
# Concatenate two strings
Statement = Name + "is the best"
Statement
We can replicate values of a string. We simply multiply the string by the number of times we would like to replicate it. The result is a new string. The new string consists of three copies of the original string. This means you cannot change the value of the string but you can create a new string.
# Print the string for 3 times
3 * "Michael Jackson"
# Concatenate strings
Name = "Michael Jackson"
Name = Name + " is the best"
Name
For example, you can create a new string by setting it to the original variable "Michael Jackson" and concatenate it with a new string "is the best". The result is a new string that changes from Michael Jackson to Michael Jackson is the best.
Strings are immutable i.e. once assigned a value cannot be changed.
Back slashes represent the beginning of escape sequences. Escape sequences represent strings that may be difficult to input. For example, backslashes n (\n) represent a new line. The output is given by a new line after the \n is encountered.
Similarly, backslash t (\t) represents a tab. The output is given by a tab where the \t is. If you want to place a backslash in your string, use a double backslash. The result is a backslash after the escape sequence.
# New line escape sequence
print(" Michael Jackson \n is the best" )
# Tab escape sequence
print(" Michael Jackson \t is the best" )
# Include back slash in string
print(" Michael Jackson \\ is the best" )
# r will tell python that string will be display as raw string
print(r" Michael Jackson \ is the best" )
When we apply a method to the string A, we get a new string B that is different from old string. Examples- the method upper. This method converts lowercase characters to uppercase characters.
The method "replace" replaces a segment of the string i.e. a substring with a new string. We input the part of the string we would like to change. The second argument is what we would like to exchange the segment with. The result is a new string with a segment changed.
The method find, find substrings. The argument is the substring you would like to find. The output is the first index of the sequence.
If the substring is not in the string, the output is negative one
# Convert all the characters in string to upper case
A = "Thriller is the sixth studio album"
print("before upper:", A)
B = A.upper()
print("After upper:", B)
# Replace the old substring with the new target substring is the segment has been found in the string
A = "Michael Jackson is the best"
B = A.replace('Michael', 'Janet')
B
# Find the substring in the string. Only the index of the first elment of substring in string will be the output
Name = "Michael Jackson"
Name.find('el')
# Find the substring in the string.
Name.find('Jack')
# If cannot find the substring in the string
Name.find('Jasdfasdasdf')
correct, in this code, we first cast or convert the float to an integer, then use the type function to determine the type
Correct, In Python, if you cast a float to an integer, the conversion truncates towards zero.
What is the result of the following code segment: int(False)
correct // corresponds to integer division
Correct: the value x=x+1 changes the value of x, if x is assigned to its self. It's helpful to replace the value of x with its current value in this case 1 or x=1+1.
correct, Python follows the standard mathematical conventions
Correct, we only retrieve the first two elements.
Correct, the first index 1 from A[1::2] corresponds to the second value, i.e. 9 . The stride value of 2 from A[1::2] selects every second element.
upper returns a copy of the string in which all case-based characters have been converted to uppercase.
the method finds the starting index of a substring
correct, the argument is first evaluated 1+1=2, then the result is cast to a string.
correct, the method replace returns a copy of the string with all occurrences of the old substring