Skip to content

Variables and operators

What is it variable?

Variable is a programming construction that have three basis attributes: symbolic name, storage location and value, that allow to access it in code by using it name and get value or storage location. Name is used to identify variable, that's why it's called ID. Storage location usually reflect to computer memory and is represented by address and data length. Value is the content that variable store.

Variable declaration

Variable declaration is defined by name, '=' character and value that will be stored in it. Here are some examples:

    number = 10
    word = "sentence"
    big_number = 99999.999
    truth = True

General pattern to define variable in Python:

    <variable_name> = <variable_value>

Variables naming convention - rules

Due to some restrictions, we are not able to name our variables totally as we want. There're some basis rules, that should be followed when we create new variable:

  • You can change variable value by assign new value to it.
  • Variable name can use only letters a-z, A-Z, numbers 0-9 and symbol _.
  • Lowercase and uppercase does matter!
  • Variable name cannot be started with number!
Permitted names:
    SUPER_VARIABLE = 1
    bestVariableEver123 = "OK"
    _my_name = "Alice"
    next1_variable2 = 5.5
    _____ = True
Prohibited names:
    123variable = 2
    wrong$name%123 = False
    !@AlmOStGoODone!@ = None
    12345 = "bad_name"
    VARIABLE-1 = 0

Variable naming styles

There're several naming styles. They are so popular, that style name is enough to other programmers to recognize what they can expect in project in case of variable naming convention.

  • style camel case (camel) - named this because in variable where there're more than one word, they are "separated" by new word started with uppercase letter (remember: white spaces are prohibited!), however first letter of variable name is lowercase.
    veryLongString = "String that supposed to be very long... Something goes wrong"
  • styl upper camel case - it's similar to camel case, only difference is that name start by uppercase (such style is used in Python - this way classes are named.
    VariableWrittenUpperCamelCase = 1000
  • style snake case - generally used style in Python, name use only lowercase letters and words are separated by '_'
    another_variable_name = 50.5

There're others ways to name variables, i.e. lowercase letters and none word separation characters. Due to low readability this naming convention is not recommended.

Variable scope

In case of scope variables can be divide into:

  • Global variables - it's available in whole file where it was declared
  • Local variable - it's available only in specific block (function, method, class), in which it was declared

Variable display on screen

Variables contain values, so they can be used as functions parameter.

    number = 10
    new_word = "new word"

    print(number)
    print(new_word)

    print(type(number))
    print(type(new_word))

Comments in Python

Character # begin comment, everything after that will be ignored.

    # Declare variable and assign value
    number = 10
    print(number)  # Return 10

If there's need to comment in more than one line, there're two ways to handle it:

  • For every line, that we want to comment we need to use #
  • We can extend comment to more lines by using triple quote or apostrophes (we need characters to open and close comment as it's not end with end of line)
    number = 10
    new_word = "new word"

    '''print(number)
    print(new_word)

    print(type(number))
    print(type(new_word))'''

Key words

Key words are reserved for Python. They cannot be used for variable, function or class name. Otherwise Python will return error.

and as assert async await break
class continue def del elif else
except False finally for from global
if import in is lambda None
nonlocal not or pass raise return
True try while with yield

What is it operator?

Operator is a language constructor that return value. For example we have operators like addition, subtraction or compare.

Operators can use one or more arguments. For example character * i double argument operator, because on it left and right side there're values (here: values that we want to multiply). One argument operator can be -, because we use it to negative numbers (-5, -10.234, etc.). Minus is also double argument operator, as it can be used for subtraction.

The values that an operator acts on are called operands.

Here are operators available in Python:

Arithmetic operators +, -, *, **, /, //, %
Compare operators ==, !=, <, >, <=, >=
Assignment operators =, +=, -=, *=, **=, /=, //=, %=, &=, ^=, |=, <<=, >>=, |=
Identity operators is, is not
Logical operators and, or, not
Membership operators in, not in
Bitwise operators & AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift

Arithmetic operators

They are used for arithmetic operations - addition, subtraction etc.

    # Mathematic operations
    >>> print(1 + 2 + 5 - (2 * 2))
    4
    >>> print(501.0 - 99.9999)
    401.0001
    >>> print(2 ** 3)
    8
    >>> print(10 / 4)
    2.5
    >>> print(10 // 4)
    2
    >>> print(5 % 2)
    1
Operators in Python are sensitive for sequence of actions. Same as in mathematic rules.
    # words concatenation
    name = "John"
    greeting = "Hello, " + name
    print(greeting)  # Return "Hello, John"
    adam = "Adam"
    eva = "Eva"
    print(adam + " and " + eva)  # "Adam and Eva"
    # Words repeat
    message = "Hey"
    print(message * 2)  # Return "HeyHey"
    new_message = "Hi" * 5
    print(new_message)  # Return "HiHiHiHiHi"
    number = 3
    message = message * number
    print(message)  # Return "HeyHeyHey"

A few words of explanation:

  • // it's exponentiation symbol
  • // is a sign of real division (result is always a real number with decimal value even if it's 0)
  • / it's an integer division (result will be integer number if operation is on integer numbers, operator will cut off decimal without rounding.)
  • % it's modulo operator, it returns the remainder of dividing
  • Python allow to add strings (join them, means concatenate) and multiply them by some natural number (as result we get repeated string)

Assignment operators

They are used to assign/add variable value.

    num = 3
    num = num + 4
    print(num)  # num value 7
    num += 2
    print(num)  # num value 9
    num -= 1
    print(num) # num value 8
    num = num * 3
    print(num) # num value 24
    num /= 2
    num **= 3
    num = num // 2
    print(num) # num value 864

Symbol += is shorten version of addition some value to variable value and store it result in same variable. In a same way other double character Assignment operators symbols working.

Compare operators

They are use when we want to compare two values.

    john_1 = "John"
    john_2 = "John"
    print(john_1 == john_2)
    print(1 != 1)
    print(99 < 1.1)
    print(99 > 1.1)
    print(-32 >= -33)
    print(123 <= 123)

Membership operators

Membership operators, (is, is not) compare two variables, check not only value, but also space in memory. If they are equal, operator is return value True, and operator is not value False.

Easiest way to understand difference between membership and assignment operator is to use twins example.

Logical operators

Operators used in boolean algebra operations.

    >>> print(True or False)
    True
    >>> print(False and False and True)
    False
    >>> print(not False)
    True
    >>>is_greater = 40 > 30
    >>> print(not is_greater)
    False

Below is truth table for operators and, or, not.

A B not A A and B A or B
0 0 1 0 0
1 0 0 0 1
0 1 1 0 1
1 1 0 1 1

Identity operators

They are used to check if some variable/value is in some other variable/value.

    print("fox" not in "cow, dog, cat")
    print("cool" in "Python is cool!!")
Here we check if word "lis" is not in (not int) in list of characters on right side of operator and if string "cool" exist in (in) sentence "Python is cool!!".