Lesson 1 of 0
In Progress

Lesson #4: Numbers

There are three numeric types in Python. Integers, floating-point numbers, and complex numbers fall under the Python numbers category. They are defined as int, float, and complex classes in Python.

Int

āœļø Reminder: Int, or integer, is a whole number, without decimals, and can be either positive or negative.

In the previous lesson, we learned how to define an integer.

Examples:

age = 25
number_of_products = 3240
available_products = 45343
products_in_stock = 89
files_uploaded = 88430
y = -10
x = -1032342342312

Float

āœļø Reminder: Float or floating-number is a number, positive or negative, containing one or more decimals, and can be either positive or negative.

In the previous lesson, we learned how to define a float.

Examples:

price = 25.99
total_cost = 109.99
height_cm = 45.5
km = 90.4
temperature_in_celsius = 19.1
y = -10.65

Complex

āœļø Reminder: In python, you can put ā€˜jā€™ or ā€˜Jā€™ after a number to make it imaginary, so you can write complex literal easily.

In the previous lesson, we learned how to define a complex.

Examples

a = 5j
b = 47j
c = 10 + 5j

Casting

Casting is the process of changing the data type of an object by using the following constructor functions:

  • int()
  • float()
  • str()

int()

The int() converts string and float to an integer number.

a = int(34)   # a will be 34
b = int(5.6) # b will be 5
c = int(“4532”) # c will be 4532

float()

The float() converts string and integer to a float number.

a = float(45)     # a will be 45.0
b = float(32.5)   # b will be 32.5
c = float(“1”)   # c will be 1.0

str()

The str() converts a variety of data types to string.

a = str(“temp6”)    # a will be ‘temp6’
b = str(52)    # b will be ’52’
c = str(5.0# c will be ‘5.0’

Random

Python provides several functions for generating random numbers in the random module.

šŸ’” Note: A module is a collection of pre-made code that you can import into your code to add extra functionalities.

To import the random module use the following syntax:

import random

The following code produces and displays a random integer between 1 and 10:

import random

print(random.randint(1, 10))