🐍 Python Data Types#
👨🏫 Vikesh K
📓 Lab 01
💡 A journey of a thousand miles begins with a single step- Chinese Proverb 💡
📝Lab Agenda#
Variables
Python keywords
Data Types
Properties
Conversion
OS Package
import
installation
Exercises
Theory#
Variables store values and keep code organized.#
This process of storing something in a variable is often called variable assignment, or simply “assignment” for short. You can assign almost anything to a variable.
x = 3
x
3
You can then use the stored values for calculations
y = x + 10
y
13
print()
allows you to see the values of the variables
pue = 45
print(pue)
45
In case of multiple code line in jupyter
if you don’t use the print()
command, only the last code line will be shown in the output
x = 3
y = 'Hello'
# show output
x
y
'Hello'
x = 4
x = 5
# show output
print(x)
print(y)
5
Hello
type()
tells you the data type of the variable
print(type(x))
print(type(y))
<class 'int'>
<class 'str'>
The breadth of a rectangle is 10 and length is 11. What is the area and the perimeter of the rectangle?
Calculate the area and perimeter and then take the breadth as 13 and length as 15 and recalculate the values. Calculate this in the normal manner and using proper variables
Normal way to calculate
area = 8 * 9
print("the area is:", area)
perimeter = 2 * (8 + 9)
print("the perimeter is:", perimeter)
the area is: 72
the perimeter is: 34
Using variables
# define the length and breadth
length = 8
breadth = 9
area = length * breadth
print("the area is:", area)
perimeter = 2 * (length + breadth)
print("the perimeter is:", perimeter)
the area is: 72
the perimeter is: 34
Variable Summary#
Used to store information to be used in a computer program
Has three components:
kind given by
type()
,value given by
print()
memory address given by
id()
There are rules in variable names:
Should start with alphabet or _ (underscore)
cannot start with a number
cannot have a space
can be alpha-numeric
should avoid
keywords
while naming
Python has got 4 major datatypes#
int
is for whole numbers: 1, 2, 4
# store the value
x = 2
# check the data type
print(type(x))
<class 'int'>
float
is for numbers with decimals: 1.2
, 3.14
# store the value
y = 2.0
# check the data type
print(type(y))
<class 'float'>
string
is used for text: hello
, my name
a = "Learning Python is fun"
print(a)
print(type(a))
Learning Python is fun
<class 'str'>
string
can be saved using single quote or double quotes
p = 'Japan'
q = "Japan"
z = 'japan'
print(p)
print(q)
Japan
Japan
# are both are equal?
p == q
True
case
matters in Python`
# are both are equal?
p == z
False
bool
is used for True/ False
p = True
q = False
# check the data type
print(type(p))
print(type(q))
<class 'bool'>
<class 'bool'>
You can convert one datatype into another
The conversion can be done using
int()
,float()
,bool()
,str()
There will be some exceptions, like a string can’t be converted to a number, however a number can be
x = 2
print(x)
print(type(x))
2
<class 'int'>
float(x)
2.0
h = '45'
print(h)
print(type(h))
45
<class 'str'>
Check the type with int()
function
type(int(h))
int
type(float(x))
float
type(x)
int
Change the type to float
x = float(x)
type(x)
float
y = 5
print(y)
print(type(y))
5
<class 'int'>
x = '5'
print(type(x))
<class 'str'>
int
to float
conversion
x = float(x)
print(x)
print(type(x))
5.0
<class 'float'>
float
to int
conversion
y = 2.9
print(y)
print(type(y))
2.9
<class 'float'>
Warning
Be careful on changing a float
to an int
. Numbers after decimal point will be dropped
y = int(y)
print(y)
print(type(y))
2
<class 'int'>
y = 3.5
y = int(y)
print(y)
3
float
to bool
conversion
0 always converts to False
Any value other than 0 is True, whether positive or negative
y = -2.3
print(y)
print(type(y))
-2.3
<class 'float'>
bool(y)
True
z = 0
print(z)
print(type(z))
0
<class 'int'>
z = bool(z)
print(z)
print(type(z))
False
<class 'bool'>
Bool to Int
int(True)
1
int(False)
0
Data Type Summary#
Source: Jovian ML
Data type |
Example |
---|---|
|
3.14 |
|
3 |
|
‘john’ |
|
True, False |
Every data-type has a specific property in Python and are used to represent different kinds of data
One can check for the data type of an item using
type(item)
One can convert one data type into another using :
int()
,str()
,float()
andbool()
Packages in Python#
Note
In Python, whenever you want to run/launch a package, you need to import
it.
In the smart phone analogy, this is equal to tapping on an app to start it. You would have pre-installed apps and apps that you need to install.
Remember, like in a phone’s pre-installed apps, os
is one of the pre-installed apps.**
You won’t get any message if a package is imported successfully. Only if you do a wrong loading, error message will be shown
While importing you can also use alias, by the command as, this is often done. It helps to make the code crisp
# import the module
import os
print("The code ran")
The code ran
You will see an error message if you load something wrongly. Example: loading a non-existing package
import os
print("The code ran")
The code ran
Note
Installing a new package
We can install a new package using pip
. The most easiest way is to install a package within the Jupyter notebook.
The syntax is !pip install packagename
Installing plotly
package
Let’s install a package and understand the process. Run the cell below
The below code will generate some text detailing the installation.If you get an error, please google for the answer. If you can’t figure it out, send me a note
# !pip install plotly
To check if the installation happened properly, running the below code should not give any error
# loading the package
import plotly
print("All ran properly")
All ran properly
Checking the installed version of a package
The syntax to check a version of the installed packages. packagename.__version__
# checking the version of pandas
import pandas as pd
print(pd.__version__)
2.2.0
# checking the version of numpy
import numpy as np
print(np.__version__)
1.23.5
print(plotly.__version__)
5.9.0
The os
package in python helps us interact with the os system#
What is my current working directory (folder) - cwd
?
import os
os.getcwd() # get me the Current Working Directory (Folder)
'C:\\Users\\vkoul\\Desktop\\DA_Training_book\\pythonbook'
Can we see the files in the directory?
# os.listdir() # list directory
❓Exercises#
Some of the exercises below are strech exercises, you may need to rely on Google to answer them. This should be a good experience of figuring out things on your own
Data Types#
Q1 What is the type of the following: 2.0
# your code here
Q2 What is the result of the following code segment: type(int(13.6))
# your code here
Q3 What is the result of the following code segment: int(4.99)
# your code here
Q4 What is the result of the following code segment: int(False)
# your code here
Q5 What is the result of the following code segment: 1/3
? What data type it is?
# your code here
Q6 What is the data type of the `’3’``
# your code here
Variables#
Q1 What is the value of x
after the following lines of code?
x = 2
x = x + 2
# your code here
Q2 What would be the value of y
in the following operation y = 2 + 5*4
# your code here
Q3 What is the type of the variable x after the following: x = 2/2
?
# your code here
Strings#
Q1 Is "China"
and "china"
same for python?
x = "China"
y = "china"
x == y
False
Q2 Is "japan"
and 'japan'
same for python?
# your code here
Q3 How would you determine the length of the string: "japan"
# your code here
Q4 What is the result of the following operation: '2'+'3'
?
# your code here
Q5 What is the result of the following : str(2) + str(2)
?
# your code here
Q6 If you executed name = 'Buzz'
, what would be the output of print(name[0:2])
?
# your code here
Q7 If you executed var = '01234567'
, what would be the result of print(var[::2])
?
# your code here
Q8 What is the result of the following: 'hello'.upper()
?
# your code here
Q9 What is the result of the following: "123".replace("12", "pqr")
?
# your code here
Q10 What is the result of "netherlands".find("land")
?
# your code here
Q10 How to reverse a string? x = "London"
# your code here
🧠Points to remember#
The counting in Python starts from 0.
We can check for a data-type using the
type()
function.Python can also do reverse count, it starts from -1.
One can convert a data type into another using different functions
int()
,str()
,float()
float
is for the decimal numbersYou can do different operations on strings-
.upper()
,.replace()
,.find()
We can slice a string using
[start:stop:steps]
operationRemember the
stop
is not inclusive
Also, you can find the reverse of a string using
string[::-1]