Variables
title: Python Variables author: Juma Shafara date: "2023-11" date-modified: "2024-08-14" description: What are variables and how do we use them in Python? keywords: [python, python programming, python variables]

Variables
Table of Contents
- Variables
- Data Types
- Numbers
- Number Methods
- Strings
- Type Conversion
- Python Booleans
- Exercise
- Varibles are used to store values.
- To create a variable, use the equal sign `(=)`.
In the examples below, we create varibales name fruit and name and we assign them values 'mango' and 'viola' respectively
Rules to consider
Before choosing a variable name, consider the following.
- Spaces are not allowed in a variable name eg `my age = 34`
- A variable name can not start with number eg `1name = 'Chris'`
- Variable names can not have special characters eg `n@me = 'Comfort'`
- Are case sensitive. Ie Name and name are not the same!
Examples of good variable names
Data Types
In this section of the tutorial, you will learn the most basic data types in Python
Numbers
These are two basic types of numbers and they are called:
- integer(numbers without decimal places)
- floating point numbers(numbers with decimal places)
Strings
Strings are simply text. A string must be surrounded by single or double quotes
Booleans
Boolean data type can only have on fo these values: True or False
Note!
The first letter of a Boolean is in upper case.
Booleans are often the result of evaluated expressions.
Forexample, when you compare two numbers, Python evaluates the expression and returns either True or False
These are often used in if statments.
In this example, if the value of the variable age is more than 18, the program will tell the user that they are allowed to enter
Note!
You will learn more about if statements later in the course
Checking the Type of a Boolean
We can check the data type of a Boolean variable using the type() method.
Lists
- A list is an ordered collection of data
- It can contain strings, numbers or even other lists
- Lists are written with square brackets (`[]`)
- The values in lists (also called elements) are separated by commas (`,`)
A list can contain mixed data types
Checking data types
To check the data type of an object in python, use type(object), for example, below we get the data type of the object stored in names
Converting Types
Convert to String
The str() method returns the string version of a given object
Convert to Integer
The int() method returns the integer version of the given object.
Convert to Float
The float() method returns the floating point version of the given object.
Exercise
Write a program to assign the number 34.5678 to a variable named “number” then display the number rounded to the nearest integer value.