VARIABLE
VARIABLE
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name (age, car name, total
volume). Rules for Python variables: A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the python keyword.
Example
Legal variable names:
◦ myvar = "John"
◦ my_var = "John"
◦ _my_var = "John"
◦ myVar = "John"
◦ MYVAR = "John"
◦ myvar2 = "John“
◦ 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.
Example:
Answer:
input
◦ fruits = ["apple", "banana", "cherry"] apple
x, y, z = fruits banana
print(x) cherry
print(y)
print(z)
Output variable
The Python print() function is often used to output variables.
x = "Python is awesome"
print(x)
Answer:
In the print() function, you output multiple variables, separated
by a comma
Python is awesome
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome".
Global Variables
◦ 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.
Example:
Answer:
x = "awesome"
myfunc()
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside
that function.
To create a global variable inside a function, you can use the global keyword.
Example:
def myfunc(): Answer:
global x
x = "fantastic"
Python is fantastic
myfunc()
print("Python is " + x)
THANK YOU
◦ Tshering Ghalley
◦ Jurme Dorji
◦ Samten Tamang
◦ Ngawang Eden Gyeltshen
◦ Tsheyang Youden