In the world of programming, data types are the building blocks that shape the digital landscape."
Variables in Python are like containers for storing data values. Python has various data types including integers, float (decimal numbers), strings, and boolean values.
Integers are the data type used to represent whole numbers. Unlike strings
, integers are not surrounded by quotes.
In order to check what is the type of the variable we can use function type()
and print its output.
# Int
number_of_apples = 5
my_age = 22
print("There are", number_of_apples, "apples in the basket")
print(type(number_of_apples))
print("My age is:" my_age)
print(type(my_age))
The are 5 apples in the basket
<class 'int'>
My age is: 22
<class 'int'>
As python
is a dynamical language (it means that the programmer doesn't declare types explicitly) this can cause some issues in the future with advanced data types. So if you are not sure what type is stored in the variable don't hesitate to call type()
.
Floats are numbers that have a decimal point. They can show fractions as well as whole numbers, like the change you get back from a dollar or how much of a cake is left.
Sometimes, you'll see really big or small floats written with an "e" which is just a shortcut way of writing zeros.
# Float
apple_price = 0.99
print("Apple price:", apple_price, "pounds")
print("Type of apple_price variable:", type(apple_price))
Apple price: 0.99 pounds
Type of apple_price variable: <class 'float'>
In Python
, you can perform all the basic mathematical operations you're familiar with from arithmetic.
This includes addition
, subtraction
, multiplication
, division
, and even more complex operations like exponentiation
.
Here are the the table where each operator described within Python
syntax"
Operator | Description |
---|---|
+ | addition |
- | subtraction |
* | multiplication |
/ | division (always returns a float) |
// | Floor division (divides and rounds down to nearest integer) |
** | Exponentiation (raises a number to the power of another) |
% | Modulo (gives the remainder of a division) |
# Two numbers
num1 = 15
num2 = 4
# Operations
sum_result = num1 + num2
difference_result = num1 - num2
division_result = num1 / num2
integer_division_result = num1 // num2
exponentiation_result = num1 ** num2
modulo_result = num1 % num2
# Displaying the results
print("Addition of", num1, "and", num2, "=", sum_result)
print("Subtraction of", num1, "from", num2, "=", difference_result)
print("Division of", num1, "by", num2, "=", division_result)
print("Integer division of", num1, "by", num2, "=", integer_division_result)
print("Exponentiation of", num1, "to the power of", num2, "=", exponentiation_result)
print("Modulo of", num1, "by", num2, "=", modulo_result)
Addition of 15 and 4 = 19
Subtraction of 15 from 4 = 11
Division of 15 by 4 = 3.75
Integer division of 15 by 4 = 3
Exponentiation of 15 to the power of 4 = 50625
Modulo of 15 by 4 = 3
Here is a practical task which we remeber from school, where we need to calculate the circumference
of the circle
# Constants
PI = 3.14159
# Radius of a circle
radius = 5
# Calculating area (PI * r^2)
area = PI * (radius ** 2)
# Calculating circumference (2 * PI * r)
circumference = 2 * PI * radius
print("Given a circle with a radius of:", radius)
print("Area of the circle:", area)
print("Circumference of the circle:", circumference)
Given a circle with a radius of: 5
Area of the circle: 78.53975
Circumference of the circle: 31.4159
A string in Python
is a series of characters. It is used to represent text.
As you know already, strings in Python
are enclosed either in single quotes (')
or double quotes (")
, and they can include letters, numbers, and various symbols. Also when we ask a user for input, we store the str
type into the variable.
# String Examples
greeting = "Hello, Python learners!"
course_name = 'The best Python Course in the United Kingdom, or even in the whole world!'
student_name = input("Input your name:")
print(greeting)
print("The course you are taking is called:", course_name)
print("Name of the student is", student_name)
Hello, Python learners!
The course you are taking is called: The best Python Course in the United Kingdom, or even in the world!
>> Adam
Name of the student is Adam
Boolean/bool
, is a data type that can only have two values: True
or False
.
Booleans are often the result of comparisons
or conditions
in Python and are extremely important for decision-making in code.
is_student = True
is_weekend = False
print("Is student:", is_student)
print("Is it the weekend:", is_weekend)
Is student: True
Is it the weekend: False
In all programming languages, sometimes there is a need to convert data from one type to another. This process is known as type conversion or typecasting.
It's especially important when the data type of a value is not suitable for a specific operation.
In this example, Python
automatically converts data types after ariphmetical operation.
num_int = 6 # Integer type
num_float = 1.5 # Float type
# Python automatically converts num_int to a float
total = num_int + num_float
print("Total:", total)
print("Type of total:", type(total))
Total: 7.5
Type of total: <class 'float'>
Explicit conversion requires the programmer to convert data types manually. Python provides functions like int()
, float()
, str()
, etc.. for explicit conversions.
There are several examples provided below which explain the need of such converstaions.
If we try to make math operations between strings, it will result in an error:
Avoid doing this!
# Both variables are of type 'str' (string)
salary = "1000"
tax = "200"
# Attempting to subtract/multiply/divide two strings - will cause an error!!
net_income = salary - tax
print("Net income: ", net_income)
ERROR!
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Note: In such cases we would want to convert the types
of variables
This is a recommended approach
# These variables are ``strings`` representing ``numbers``
salary_str = "1000"
tax_str = "200"
# Converting ``str`` variables to ``int``
salary_int = int(salary_str)
tax_int = int(tax_str)
# Now we can perform the subtraction with ``int`` variables
net_income = salary - tax
print("Net income: ", net_income)
Net income: 800
We can convert user's
input into the integers while using input()
function.
# Asking the user to input their age and converting it into the integer
age= int(input("Please enter your age: "))
print("Type of age is: ", type(age))
print("You are", age, "years old.")
Please enter your age:
>> 21
Type of age is: <class 'int'>
You are 21 years old.
Objective: Write a program that calculates the volume and total surface area of a cube from the length of its edge.
Input:
One integer: the length of the cube’s edge.
Output:
The program should output the volume and the total surface area of the cube.
Objective: Create a program that calculates the total cost of three computer sets. Each set consists of a monitor, system unit, keyboard, and mouse.
Input:
Four integers on separate lines: the cost of the monitor, system unit, keyboard, and mouse, respectively.
Output:
The total cost of three computer sets.
Objective: Write a program that computes the sum, difference, and product of two integers entered by the user.
Input:
Two integers on separate lines.
Output:
The sum, difference, and product of the two integers, each on a separate line.
What data type would you use to represent a person's name in Python?
A) int
B) str
C) bool
D) float
Which of the following is the correct way to convert the string '123' to an integer?
A) int("123")
B) "123".int()
C) str(123)
D) integer("123")
What is the result of this operation: 10 // 3?
A) 3.33
B) 3
C) 3.0
D) 4
Which function would you use to read a user's input as a string in Python?
A) input()
B) print()
C) read()
D) getString()
How would you print the type of a variable
x
in Python?
A) print(x)
B) print(type(x))
C) type(print(x))
D) print(x.type)
What will be the output of the following code?
x = "10"
y = 5
print(x + y)
What does the
%
operator do in Python?
A) Multiplies two numbers
B) Divides two numbers and returns the integer part
C) Adds two numbers and returns their modulo
D) Divides two numbers and returns the remainder
What will be the output of the following Python code?
temperature_str = "25.5"
temperature = float(temperature_str) + 10
print(temperature)
A) 35.5
B) 25.510
C) "35.5"
D) TypeError
Objective: Develop a program to convert inches to centimeters.
Input: The user inputs a length in inches.
Output: The program outputs the equivalent length in centimeters.
Conversion: 1 inch = 2.54 cm.
Input: 10
Output: 25.4 cm
Objective: Write a program that converts a temperature from Fahrenheit to Celsius.
Input: The user enters a temperature in Fahrenheit.
Output: The program prints the temperature in Celsius.
Formula: Celsius = (Fahrenheit - 32) * 5/9.
Input: 32
Output: 0.0 Celsius
Objective: Create a script to calculate simple interest.
Input: The user enters the principal amount, the rate of interest (as a percentage), and the time period in years.
Output: The script outputs the calculated simple interest.
Formula: Simple Interest = (Principal * Rate * Time) / 100.
Input: Principal = 1000, Rate = 5, Time = 3
Output: Simple Interest is 150.0