Python Variables

In Python, variables are used to store values. They are like containers that hold data, and you can use them to store different types of data such as numbers, strings, lists, and more. Variables are an important concept in programming, and they are used in almost every program you write.

Declaring Variables

Declaring Variables in Python In Python, you don't need to specify the type of a variable when you declare it. The type of the variable is determined by the value that is assigned to it. To declare a variable, you use the assignment operator "=", which assigns a value to the variable. For example,

1name = "William" # a string 2age = 30 # an integer 3is_student = False # a boolean

In the above example, we declared three variables: "name", "age", and "is_student", and assigned them string, integer, and boolean values respectively.

Modifying Variables

Modifying Variables Once you've declared a variable, you can change its value at any time by reassigning a new value to it. For example,

1name = "William" 2print(name) # Output: William 3name = "Jane" 4print(name) # Output: Jane

In the above example, we first declared the variable "name" and assigned it the value "William". We then printed its value, which is "William". Next, we reassigned the variable "name" with the value "Jane" and printed its value again, which is now "Jane".

Naming Variables

Naming Variables When naming variables in Python, you should follow the rules for naming identifiers. Variables are also identifiers. The rules are:

  • Variables cannot be a keyword.
  • Variables are case-sensitive.
  • They can have a sequence of letters, digits, and underscores, but they must start with a letter or an underscore. The first letter of an identifier cannot be a digit.
  • It's a convention to start an identifier with a letter rather than an underscore.
  • Whitespaces are not allowed in variables.
  • Special symbols such as !, @, #, $, etc. are not allowed in variables.

For example, consider the following code:

1language = "Python" # valid variable 2_version = "3.9" # valid variable 31name = "William" # invalid variable (starts with a digit) 4return = "success" # invalid variable (a keyword)

As you can see in the above examples, valid variables follow the rules for naming identifiers, while invalid variables break one or more of the rules.