Creating and assigning values to variables

In Python, variables don't need to be declared explicitly to reserve memory space. So, the declaration is done automatically whenever you assign a value to the variable. In Python, the equal sign = is used to assign values to variables.

Consider the following example:

#!/usr/bin/python3
name = 'John'
age = 25
address = 'USA'
percentage = 85.5
print(name)
print(age)
print(address)
print(percentage)

Output:
John
25
USA
85.5

In the preceding example, we assigned John to the name variable, 25 to the age variable, USA to the address variable, and 85.5 to the percentage variable.

We don't have to declare them first as we do in other languages. So, looking at the value interpreter will get the type of that variable. In the preceding example, name and address are strings, age is an integer, and percentage is a floating type.

Multiple assignments for the same value can be done as follows:

x = y = z = 1

In the preceding example, we created three variables and assigned an integer value 1 to them, and all of these three variables will be assigned to the same memory location.

In Python, we can assign multiple values to multiple variables in a single line:

x, y, z = 10, 'John', 80

Here, we declared one string variable, y, and assigned the value John to it and two integer variables, x and z, and assigned values 10 and 80 to them, respectively.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset