Python Variables


In this tutorial, we will learn about Python Variables

 

What are Variables ?


In programming, a variable is a named container that stores a value.

This value can be any data type, such as a number, string, or boolean.

Variables allow programmers to assign values to a name, making it easier to work with and manipulate data in their programs.

 

Defining variables in Python


In Python, variables are defined using the equal sign (=). For example, if we wanted to define a variable called “age” and set its value to 25, we could do the following:

age = 25


This tells Python to create a variable called “age” and assign it the value 25. Once a variable is defined, we can use it in our code by referencing its name.

 

Data types


In Python, there are several different data types that can be stored in a variable. Some of the most common data types include:

 

•    Integers: Whole numbers such as 1, 2, 3, etc.
•    Floats: Numbers with decimal places such as 1.5, 2.75, etc.
•    Strings: Text values such as “hello”, “world”, etc.
•    Booleans: True or False values.

 

To specify the data type of a variable in Python, we can use the following syntax:

variable_name = data_type(value)

 

For example, to define a variable called “name” as a string with the value “John”, we could use the following code:

name = str(“John”)


Working with variables in Python


Once a variable is defined, we can use it in our code by referencing its name. For example, if we wanted to print the value of the “age” variable we defined earlier, we could do the following:

print(age)


This would output “25”, which is the value we assigned to the “age” variable.

We can also perform operations on variables. For example, if we wanted to add 5 to the value of the “age” variable and store the result in a new variable called “new_age”, we could do the following:

 

new_age = age + 5


This would create a new variable called “new_age” with the value 30, which is the result of adding 5 to the value of the “age” variable.

 

Rules For Declaring Python Variables 


  1. Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  2. Variable names cannot start with any digit.
  3. Variable names are case-sensitive, so myVar and myvar are different variables.
  4. Avoid using python keywords like if, while, for, etc. as variable names.
  5. You can't use special characters like spaces, hyphens, or punctuation in variable names.

 

 

© 2022-2023 All rights reserved.