Python Lesson 3
Python Lesson 3
Python Numbers
• Numeric types in Python
➢ int
➢ float
➢ Complex
• Type Conversion
• Random Number
• Test Yourself with Exercises
Python Casting
• Specify a Variable Type
• Constructor functions
➢ int()
➢ float()
➢ str()
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
• Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
• To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Random Number
Python does not have a random() function to make a random number, but Python has a built-in
module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
In our Random Module Reference you will learn more about the Random module.
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with casting.
Python is an object-orientated language, and as such it uses classes to define data types, including its
primitive types.
• int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal (providing
the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals
Examples
Integers: Floats: Strings:
x = int(1) # x will be 1 x = float(1) # x will be 1.0 x = str("s1") # x will be 's1'
y = int(2.8) # y will be 2 y = float(2.8) # y will be 2.8 y = str(2) # y will be '2'
z = int("3") # z will be 3 z = float("3") # z will be 3.0 z = str(3.0) # z will be '3.0'
w = float("4.2") # w will be 4.2
The following code example would print the data type of x, what data type would that be?
x = 5
print(type(x))
Number Exercise:
x = 5
x = (x)