Sep 3, 2022

Python Variables

Creating a Python variable 

In python, there isn't a way to declare variables what you can do is you can create a variable and assign a value same time. 

name = "John"
x = 8

You can use an expression as an assigned value in a variable. In the below scenario, expression evaluate first then that value is assigned to the variable on the left-hand side.

value = 8 + 3
full_name = "John" + "Doe"

Previously assigned variables can be used to build up the expression

x = 6
y = 7
new_value = x + y

Here x and y variables need to create earlier before it assigned to the new_value variable.

You can also create multiple variables at once using a comma(,) In the below example x, and y variables are created at once and assigned x to the value 6 and y to the value of  7.

x, y = 6, 7


Nature of the python variables


If you create python variables by assigning the same values then those variables point to the same object location. see the below example.

country = "United Kingdom"
europe_country = "United Kingdom"

print("identity country ", id(country))  # gives the identity of the country variable
print("identity europe country ", id(europe_country))
output:
 identity country 140222437532528
 identity europe country 140222437532528



Python variables pointing to the same memory location
Python variables pointing to the same memory location


Data Types in Python


Unlike other languages like java, C#, and C, Python doesn't have primitive data types. it only has class-type data. you can check the data type of a variable using the type() function in python.

print(type(1))
print(type('name'))
print(type(True))
print(type(1.6))

output:
  <class 'int'>
  <class 'str'>
  <class 'bool'>
  <class 'float'>


No comments:

Post a Comment