Python Variables

Python Variables:

In Python, variables are used to store data or values.

A variable is created the moment you first assign a value to it.

Casting: also known as type conversion, is a process that converts a variable’s data type into another data type.

Case-sensitive: In python, the language treats uppercase and lowercase characters differently. For example, in Python, the variable "x" is not the same as the variable "X".

Rules for Python variables:

  • Variable names in Python can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
  • They must start with a letter or an underscore but cannot start with a digit.
  • Variable names are case-sensitive, meaning "myVariable" and "myvariable" are different variables.
  • Avoid using reserved keywords (e.g., "if", "while", "for") as variable names.

Camel Case: Each word, except the first, starts with a capital letter.

Pascal Case: Each word starts with a capital letter.

Snake Case: Each word is separated by an underscore character.

Unpack a collection: If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking.

Global Variable: Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Output:-

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

 

The Global Keyword: To create a global variable inside a function, you can use the global keyword.

Output:-

 

 

Related Articles

post a comment