Variables :

- Variable is like a container

Example

In [8]:
# Variable x is containing 12

x = 12

print(x)
12

Example

In [10]:
# You can either use "" or '' -> write   x = "This is a test"   or   x = 'This is a test'

x = "This is a test"

print(x)
This is a test

Example

In [37]:
x = 200 

# First way
print(x-100)

# Second way - you can put the result in x instead of new variable
x = x - 100
print(x)
100
100

Example

In [35]:
# You can either use "" or '' for string

x = 'beautiful '
y = "day"

# First way 
print (x+y)

# Second way
z = x+y
print (z)
beautiful day
beautiful day

Example

In [14]:
a, b, c, d = "this is a", "this is b", "this is c", "this is d"

print(a)
print(b)
print(b)
print(d)
this is a
this is b
this is b
this is d
In [30]:
k = m = n = 5

print("the value of k is :", k)
print("the value of m is :", m)
print("the value of n is :", n)
the value of k is : 5
the value of m is : 5
the value of n is : 5
In [9]:
x = 2
y = 'hope '

# First way to print hope twice
print(x*y)

# Second way to print hope twice
z = x * y
print(z)
hope hope 
hope hope 

Global and Local Varibles

- Let's check the following examples to understand the difference between Global and Local variables :

Example

In [52]:
# this is a function  # Check the function section to learn how to write and use functions

x = "Flowers"

def combine_words():
  print("Yellow " + x)

# When you call function combine_words(), it will consider global variable if there is no local variable
combine_words()  
Yellow Flowers

Example

In [51]:
x = "Cars"  # This is a global variable

def combine_words():
    x = "Flowers"    # This is a local variable
    print("Yellow " + x)

combine_words() # when you call function combine_words(), it considers local variable 

print("Yellow " + x)  # when you use print() outside the function, it considers global variable for printing
Yellow Flowers
Yellow Cars

Example

In [54]:
def combine_words():
    global x      # although x is defined inside function, it is a global variable because of global keyword
    x = "Flowers"    
    print("Yellow " + x)

combine_words() # when you call function combine_words(), it considers variable defined inside function

print("Yellow " + x)  # when you use print() outside the function, it considers global variable for printing
Yellow Flowers
Yellow Flowers
In [7]:
x = "cars"

def combine_words():
    global x      # although x is defined inside function, it is a global variable because of global keyword
    x = "Flowers"   # because of global keyword, function ignores x = "Flowers" and sets the value of x = "cars"
    print("Yellow " + x)
    
combine_words() # when you call function combine_words(), in this case it considers global varibale x = "cars"

print("Yellow " + x)  # when you use print() outside the function, it considers global variable for printing
Yellow Flowers
Yellow Flowers