python variables tutorial for beginners with suitable practical examples

Variables play an important role to store and handle data in a program. Here in this article we will give a brief discussion on python variables.

A brief discussion on Python Variables



Welcome back to our website! Hope you read and understood the Basic information about python programming language - Codeschools.py (codeschoolspy.org). If you didn’t read it yet, go on!

Variables play an important role in programming. Especially, python made the usage of variables easier. It eased the process of defining a variable, and it allocates memory size for the variable on its own. In the last topic, we discussed global variables and python keywords. There we saw that you can’t specify a data type for any variables in python, as python does it for you. But sometimes, like if you want to make a floating calculator, which treats integers as floating-point numbers, and then you must have to specify a data type for a variable. This is known as python casting.

Python casting

Think of this example:


Output:

>>4

Here, the value of a is assigned as 4. But if we want to print a as a floating point number, this is what we have to do.


Output:

>>4.0

See we here used a method, named float(). This converts an integer to a floating-point number. This is known as casting.

You can convert variables like this using some methods you favor. Casting is done by some constructor functions. Python is an OO language (Object-Oriented), so it uses classes to define data types, including its initial types.

Some of the functions or methods used in python for casting are-

int() = converts a number to integer. Cannot convert a string to integer, if any character besides number is attached with the string.

float()= converts an integer into a floating-point number.

You sometimes may have to print 1,2,3,4,5 etc decimal places in python. To do this, you have to use the format() method. See this example:


Output:

>> 4.0000

The syntax will be like,

format (variable_name/any number, “.*f)

*means the number of floating points you want.

.4f will print 4 decimal points.

str() = converts to string. Numbers can be also converted to string! But they won’t behave like numbers anymore, they will not participate in summation and other mathematical functions.

Built-in data types for python

Python has the following data types built-in by default, they can be divided into some categories.

Text type – str

Numeric types – int, float, complex

Sequence types (They can store multiple data in one variables) – list, tuple, range

Mapping types – dict

Boolean types – bool (Boolean only allows two values, True and False)

Set types – set, frozenset

Binary types – bytes, bytearray, memoryview


Getting data type

You can get a variables data type using the type() function as described in the previous tutorial!

Example:


Output:

>><class ‘int’>

Using the python casting method, you can easily specify a data type, and if you don’t, you don’t have to worry a bit! Python will do that automatically for you.

Lets see some examples:

Example

Data type

action

x = str (“Hi”)

string

Specifies the data type to string

x = int (20)

integer

Specifies the data type to integer

x =complex (51ab)

Complex

Specifies the data type to complex

x = frozenset((“a”.”b”,”c”))

Frozenset

Specifies the data type to a frozenset

x =bytes(5)

Bytes

Specifies the data type to  bytes

x = range (1,6)

Range

Specifies the data type to range

And you can try with the datatypes given above.

Let's learn a brief description about each and every data types!

Integers

Integers are those numbers that don’t carry any decimal points with them. Python uses the int() function to specify any integers.

Here is an example of python integers.


Output:

>>5

5

Here, first we let the python interpreter to determine the integer. It specified the variable x as an integer, and we printed it. But for the variable y, we specified the data type manually, which also resulted in the same way. This process is vastly used in getting input from users, as python always takes a string input from the user. We will discuss about that later.

Float

Floats are the numbers which contains decimal points. They are specified by the function float().

>>5.0

5.0

This is the usage of the float() function, which converts an integer into a float. And if you enter a floating-point number in the float() function, it won’t do anything to the number!

String

Python treats any characters, emojis and texts as strings. These can be some examples of string,

I love python!

A

J

Remember, in python there is no char data type, or character data type. A character is represented as a string of length one (means a text with only one character). It is represented by str class (Python uses class for everything.)

Python uses ‘’ or “” (Single or double quotes) to determine a string. That means a string have to be wrapped up with ‘’ or “”. Like,

a = “Hi!”
b = ‘Python is easy!’

the wrappers should be exactly the same. If you use ‘ first, you can’t end the string with ”.

Complex

Complex numbers are the imaginary numbers. We use 1 as our unit for measurement, that means if we say your home is 5 miles away from my home, it is calculated by your home 5 times away than 1 mile. We always do our calculations like that, but we generally never think of it.

In complex numbers, we use -1 as our unit of calculation. We all know that no negative numbers can be inside a root sign, so, this number is imaginary. It is also illustrated as i.

Those who understands complex numbers, we know that complex numbers are generally written in the format of a+bi, where i is the imaginary unit. And this is how we assign a complex number in a variable,


Example:

>>  2+3i

2+4i

List, tuple and range

We will have a tutorial on that topic. Stay tuned!

Bool

To communicate with a computer you can make only two words. A computer only understands the presence and absence of electricity. So, if you let the presence of electricity as true or 1, and the absence of electricity as 0 or false, you will get the bool or Boolean communication method. Boolean algebra is a type of algebra where the whole world is evaluated with only 2 conditions, true and false. If a condition you gave in the interpreter on the if else method, and it evaluates true, motherboard gets a bolt of electricity, but if it is evaluated as false, motherboard doesn’t receive any electricity. That’s how computers evaluate a condition.


True:

>> True

<class ‘bool’>

True

True

False

Here, the value of x was assigned as True. As there are no quote marks wrapping it, and the first letter is on the uppercase, python evaluated it as a Boolean operator. then for the next variables we used the function bool() to specify those variables as a Boolean operator. We set the value of y 1, and we know that 1 means the presence of electricity. So, python converted 1 as True. For the variable a we set it’s value 5. 5 means the electricity flowing through the motherboard is 5 times than the normal electricity. (Bool defines 2-5 volts of electricity as 1 and 0-1 volts of electricity as 0) so, the value 5 here means 10-25 volts of electricity. But no matter how much electricity is flowing, there is a presence of electricity. So Boolean defines 5 as True. And we assigned 0 to z, which was evaluated as false.

Set types

Sets are also used to store multiple values in one variable. But the main difference between a set and a list is, set is unordered and unindexed, where list is ordered or indexed (the elements of a list starts from the count of 0). Sets are written with curly brackets ({}), which resembles the set theory of mathematics.

Here’s how we can create a set:

See the results of the code. It prints the third element first and goes on, which means it just printed the elements in reverse. But you can’t be sure of it, it can print the elements anyhow it wants, as there is no indexing for the variables.

Set follows 3 rules, they are, Unordered, Unchangeable and it doesn’t allow duplicate values in it. In brief, the elements you enter can’t be changed anywhere else in the program, but it allows you to add elements. It doesn’t index its elements, and it doesn’t allow duplicate values in it.

Set can convey 3 types of data.

-          Integer (intset = {1,2,3})

-          String (strset = {“go”, “move”, “run”})

-          Boolean (boolset = {True, False, True})

Set can also contain multiple data types in one variable name.

Mulset = {1, “this is a set which contains multiple data types”, True}

Binary types

Binary types will be described later!

Constants

Constants are the values that can’t change in a code later. Python is not equipped with constants. But you can use Uppercase letters for your name of the variable, just to make sure you won’t use them later.

You can use tuples to create a constant though. Tuples are a special kind of list which doesn’t let its elements to change during the execution of a program. To create a tuple with one value, you have to follow the syntax below-

This process will be described later.

You can use another method to create constants. You have to open another .py or python file in the same directory where your main python script is. Then you have to create a variable ad store a value in it. Like you will use Pi as a constant in your program. To do so, first create a new .py file in the same directory and name it as constant.py



Then open your main script, my one is login. And write import constant (the subsidiary file name)

Then follow these syntaxes:

That’s how you access the variable of another file.

Usage of Binary, hexadecimal, and octal in code

Decimals are a number system which contains 10 numerical values, 1,2,3,4,5,6,7,8,9,0. Binary numbering system is a numbering system which contains 2 numbers, 0 and 1, hexadecimals contain 16, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F and octals contain 8, 0,1,2,3,4,5,6,7.

To specify a number as,

Hexadecimal, you need to add 0x in front of its value.

Hex_example = 0x5E

Octal, you need to add 0o, (zero and a lowercase o)

Oct_example = 0o17

Binary, you need to add 0b,

Bin_example = 0b1010


Hope you liked our tutorial! Stay with us for a step-by-step free python tutorial! We always try to post every day.