Understanding Variables and Simple Data Types in Python
This is the 2nd post in a series of learning the Python programming language.
In Python, variables are used to store and manipulate data. A variable is simply a name that refers to a value, and the value can be of various types, such as a string, integer, or float. In this post, we will discuss the basic concepts of variables and the simple data types in Python, including how to create and use variables, and how to perform basic operations with them.
Creating Variables
In Python, you can create a variable by assigning a value to it using the assignment operator (=). The variable name can be any combination of letters, numbers, and underscores, but it cannot start with a number. Here are some examples of creating variables in Python:
x = 5
y = "Hello World"
z = 3.14
You can also assign multiple variables at once:
x, y, z = 5, "Hello World", 3.14
Variable Names
When naming variables in Python, it is important to follow a few conventions. Variable names should be descriptive, lowercase and use underscores to separate words (snake case). For example, variable_name
is a better name than VariableName
or variablename
. Additionally, Python has a few keywords that cannot be used as variable names, such as if
, else
, True
, False
, None
, and
, or
, not
etc.
Re-assigning Variables
Once a variable has been created, you can change its value by re-assigning it a new value. For example:
x = 5
x = 10
In the above example, the value of x is first set to 5, and then re-assigned to the value of 10.
Data Types
In Python, variables can hold values of different types, known as data types. The most common data types include:
- Integers (int): Whole numbers, such as 1, 2, and 3
- Floats: Numbers with decimal points, such as 3.14, 2.718, and 1.6180339
- Strings (str): Sequences of characters, such as “hello” and “world”
- Booleans (bool): Logical values, either True or False
You can check the type of a variable using the type() function:
x = 5
print(type(x)) # prints <class 'int'>
Working with Integers
The integer data type is used to represent whole numbers, both positive and negative. Integers are one of the most basic data types and are used in a wide range of applications, from mathematical calculations to indexing in data structures.
Creating Integers
In Python, you can create an integer by assigning a whole number to a variable. For example:
x = 5
y = -10
You can also use the int()
function to convert other data types to an integer. For example:
x = int(3.14) # x is 3
y = int("5") # y is 5
Integer Operations
In Python, you can perform a variety of operations with integers, such as addition, subtraction, multiplication, and division. Here are some examples:
x = 5
y = 2
print(x + y) # prints 7
print(x - y) # prints 3
print(x * y) # prints 10
print(x / y) # prints 2.5
You can also use the modulus operator (%) to find the remainder of a division:
print(7 % 3) # prints 1
You can also use the floor division operator (//) to perform division and round down to the nearest integer:
print(7 // 3) # prints 2
Integer Methods
In Python, integers have several built-in methods that you can use to manipulate and retrieve information about them. Here are a few examples:
x = 5
print(x.bit_length()) # prints 3, as 5 can be represented using 3 bits
print(x.real) # prints 5, as x is a real number
You can also use the divmod()
function to get the quotient and remainder of a division:
x = 7
y = 3
print(divmod(x, y)) # prints (2, 1)
Conversion
You can convert integers to other data types such as strings and floats. For example:
x = 5
y = str(x) # y is '5'
z = float(x) # z is 5.0
Working with Floats
The float data type is used to represent numbers with decimal points, both positive and negative. Floats are often used in mathematical calculations and scientific applications.
Creating Floats
In Python, you can create a float by assigning a number with a decimal point to a variable. For example:
x = 3.14
y = -2.718
You can also use the float()
function to convert other data types to a float. For example:
x = float(5) # x is 5.0
y = float("3.14") # y is 3.14
Float Operations
In Python, you can perform a variety of operations with floats, such as addition, subtraction, multiplication, and division. Here are some examples:
x = 3.14
y = 2.718
print(x + y) # prints 5.8580000000000005
print(x - y) # prints 0.42200000000000015
print(x * y) # prints 8.53452
print(x / y) # prints 1.155261221486387
You can also use the ** operator to raise a number to a power:
x = 2.0
print(x ** 2) # prints 4.0
Float Methods
In Python, floats have several built-in methods that you can use to manipulate and retrieve information about them. Here are a few examples:
x = 3.14
print(x.as_integer_ratio()) # returns a tuple ( numerator, denominator) which is the closest ratio between x and integers.
print(x.is_integer()) # returns True if x is an integer, False otherwise
Rounding
Python provides the round()
function to round a float to a given number of decimal places. For example:
x = 3.14159
print(round(x, 2)) # prints 3.14
Accuracy
It’s important to be aware that floats are not always exact and may lead to inaccuracies in certain calculations. For example:
x = 0.1 + 0.1 + 0.1
print(x) # prints 0.30000000000000004
In this example, the value of x is not exactly 0.3, but rather a very close approximation. This can cause issues in certain cases such as financial calculations, so it’s important to be aware of the limitations of floats and consider using the decimal module for more precise calculations.
Working with Strings
The string data type is used to represent sequences of characters, also known as text. Strings are one of the most commonly used data types in programming and are used for a wide range of applications, from displaying text to storing data.
Creating Strings
In Python, you can create a string by enclosing a sequence of characters in either single quotes (‘…’) or double quotes (“…”). For example:
x = "Hello World"
y = 'Python is fun!'
You can also use the str()
function to convert other data types to a string. For example:
x = str(5) # x is '5'
y = str(3.14) # y is '3.14'
String Concatenation
In Python, you can use the + operator to concatenate two or more strings. For example:
x = "Hello"
y = "World"
z = x + " " + y
print(z) # prints "Hello World"
You can also use the * operator to repeat a string multiple times:
x = "Na" print(x * 16 + " Batman!") # prints "NaNaNaNaNaNaNaNaNaNaNaNaNaNaNaNa Batman!"
String Indexing
In Python, you can access individual characters in a string using indexing. String indexing in Python starts from 0. For example:
x = "Hello World"
print(x[0]) # prints "H"
print(x[-1]) # prints "d"
You can also use slicing to access a range of characters in a string:
x = "Hello World"
print(x[2:5]) # prints "llo"
String Methods
In Python, strings have several built-in methods that you can use to manipulate and retrieve information about them. Here are a few examples:
x = "Hello World"
print(x.upper()) # prints "HELLO WORLD"
print(x.count("l")) # prints 3
Escape Characters
In Python, you can use escape characters to represent special characters such as newlines and tabs in strings. For example:
x = "Hello\nWorld"
You can also use the print()
function to display the string with the special characters interpreted:
x = "Hello\nWorld"
print(x) # prints "Hello" on the first line, "World" on the second line
String Formatting
In Python, you can use string formatting to include variables within a string. This can be done using the format()
method or by using f-strings (formatted string literals) introduced in Python 3.6.
x = 5
y = 3.14
z = "Python"
print("The value of x is {} and the value of y is {} and the value of z is {}".format(x, y, z))
or using f-strings
x = 5
y = 3.14
z = "Python"
print(f"The value of x is {x} and the value of y is {y} and the value of z is {z}")
Both will output the same result.
The value of x is 5 and the value of y is 3.14 and the value of z is Python
Working with Booleans
The boolean data type is used to represent logical values, i.e., true or false. Boolean values are often used in conditional statements, loops, and other control structures to make decisions in a program.
Creating Booleans
In Python, you can create a boolean value by assigning the keywords True
or False
to a variable. For example:
x = True
y = False
You can also use the bool()
function to convert other data types to a boolean. For example:
x = bool(5) # x is True
y = bool(0) # y is False
Boolean Operations
In Python, you can perform a variety of operations with booleans, such as negation, conjunction, and disjunction. Here are some examples:
x = True
y = False
print(not x) # prints False
print(x and y) # prints False
print(x or y) # prints True
You can also use comparison operators like ==, !=, >, <, >=, <= to compare values, which will return a boolean value
x = 5
y = 10
print(x == y) # prints False
print(x != y) # prints True
Boolean Methods
In Python, Booleans do not have any built-in methods as they are considered a very basic data type. But, you can use them in various other data types methods, and functions.
Conversion to other data types
You can convert booleans to other data types such as integers and strings. For example:
x = True
y = int(x) # y is 1
z = str(x) # z is 'True'
You can also convert strings and integers to booleans, and in python, any non-zero number is considered true, and zero is considered as false.
x = bool("True") # x is True
y = bool(0) # y is False
Summary
Understanding the basics of variables & simple data types and how to use them effectively is an important aspect of programming in Python.
If you like the post, don’t forget to clap. If you’d like to connect, you can find me on LinkedIn.