All technological notes.
Variables: containers for storing data values.Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Variables do not need to be declared with any particular type, and can even change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
x, y, z = "Orange", "Banana", "Cherry"
print(x) # Orange
print(y) # Banana
print(z) # Cherry
x = y = z = "Orange"
print(x) # Orange
print(y) # Orange
print(z) # Orange
unpacking: to extract the values in a collection, such as list, tuple etc, into variables.fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x) # apple
print(y) # banana
print(z) # cherry
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total*volume).
Rules for Python variables:
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.
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
# illegal variable name
# 2myvar = "John"
# my-var = "John"
# my var = "John"
# Camel Case
myVariableName = "John"
# Pascal Case
MyVariableName = "John"
# Snake Case
my_variable_name = "John"
The Python print() function is often used to output variables.
+ operator to output multiple variablesThe best way to output multiple variables in the print() function is to separate them with commas, which even support different data types.
x = "Python"
y = "is"
z = "awesome"
print(x, y, z) # Python is awesome
print(x + y + z) # Pythonisawesome
x = 5
y = 10
print(x + y) # 15
x = 5
y = "John"
print(x + y) #error: combine a string and a number with the + operator, Python will give you an error.
print(x, y) #5 John
global variables: Variables that are created outside of a function.
local variables: variables only used within a function.
The global variable with the same name will remain as it was, global and with the original value.
x = "awesome" # global variable
def myfunc():
x = "fantastic" # local variable
print("Python is " + x) # Python is fantastic
myfunc()
print("Python is " + x) # Python is awesome
global Keyword
global variable inside a functionglobal variable inside a function.
# create a global variable
def myfunc():
global x # declare x inside myfunc() as a global variable
x = "fantastic"
myfunc()
print("Python is " + x) # Python is fantastic
# change a global variable
x = "awesome"
def myfunc():
global x # declare x inside myfunc() as a global variable
x = "fantastic"
myfunc()
print("Python is " + x) # Python is fantastic