Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python Variable

Back


Variable


Creating Variables

x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)

Declare multiple variables in one line

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

Unpack a Collection

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)    # apple
print(y)    # banana
print(z)    # cherry


Variable Names

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"

Scope

Output Variables

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

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


# 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



TOP