Overview of Variables, Data Types and Data Structures

tags: #python/intro

Python Variables

In programming, a variable is a container (storage area) to hold data. For example,

number = 10

Here, number is the variable storing the value 10.

Assigning Values to a Variable

In Python, values can be assigned to a variable by using the assignment (=) operator. The type of data assigned to the variable defines the data type:

# assign value to site_name variable
varstr = 'hello world'

print(varstr)

# Output: hello world

We can assign multiple values to multiple variables by separating each variable and its corresponding value by a ,:

a, b, c = 5, 3.2, 'Hello'

print(a)  # prints 5
print(b)  # prints 3.2
print(c)  # prints Hello 

If the number of variables on the left does not match the number of values on the right, a ValueError occurs.

You can assign the remaining values as a list by prefixing the variable name with *.

a, *b = 100, 200, 300

print(a)
print(type(a))
# 100
# <class 'int'>

print(b)
print(type(b))
# [200, 300]
# <class 'list'>

Rules for Naming Variables

  1. Variable names should have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (**_**) in place of spaces. For example:
snake_case
MACRO_CASE
camelCase
CapWords
  1. Avoid using keywords like ifTrueclass, etc. as variable names.

  2. Do not begin variable names with a number. Always start with a character. Subsequent characters may be letters, digits, dollar signs, or underscore character.

  3. While technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

  4. Variable names in Python are case-sensitive
AGE = 65

print(age) # will not work. age is not the same as AGE.

Powered by Forestry.md