Python For Beginner's Day - 3

Python Variables

  • It is a reserved memory location to store the data values.

    Creating Variables:

  • A Variable is created, when a value is assigned to it.

  • Variables are not required to be declared with any particular type and can be changed after they have been set.

  • If a variable data type to be specified, that can be done by Casting.

  • To get the type of the variable, use type() function.

  • String Variables can be declared either by using Single or Double Quotes.

Variable Names

  • are case-sensitive(a, A are 2 different variables)

  • can have a short name like x, y.... or it can be a descriptive like firstname, age, ...

  • must start with underscore(_) or a letter and can contain alpha-numeric characters and _ (A-Z, a-z, 0-9 and _).

  • cannot start with number.

  • cannot be any of Python Keywords.

  • Legal Variable Name Declaration:

  • Illegal Variable Name Declaration:

  • Multi word variable names can sometimes be difficult to read. So those can be written in

    • Camel Case: Each word except the first, starts with capital letter. Eg: varName = "Sita"

    • Pascal Case: Each word starts with Capital letter. Eg: VarName = "Sita"

    • Snake Case: Each word is separated by an underscore(_). Eg: var_name = 'Sita'

Assign Multiple Values:

  • Values can be assigned to multiple variables in one line.

    Eg:

  • NOTE : Make sure the number of variables assigned should match the number of values.

  • Single Value can be assigned to multiple variables in one line.

    Eg:

  • If there is a collection of values in a list, these values can be extracted to variables. This is called as unpacking.

    Eg:

Output Variables - print() Function

  • As we already saw in our examples above, print() is used to output variables.

  • It can also be used to output multiple variables, separated by comma(,) or using + operator.

  • + operator works as mathematical operator for integers.

    NOTE: By using + operator, it's not possible to combine string and integer. Instead, separate with commas which supports with any data type.

    Global Variables:

  • can be used both inside and outside the function.

  • If the same variable is created inside the function, then it is called a local variable and can be used inside the function. The global variable with same name remains as it is and with the original value.

'global' Keyword:

  • As seen above about local variable, in order to make that as global inside the function use 'global' keyword.

  • Also, to change the value of global variable inside the function.