Code sample :
# No prior type declaration is required
# Python is dynamically typed
# Variable names are case-sensitive
num = 5
print(num)
real = 5.5
print(real)
text = "Python Rocks!!"
print(text)
# A variable can refer to any data type
my_string = 'Hello, World!'
my_flt = 45.06
my_bool = 5 > 9 # A Boolean value will return either True or False
print(my_bool) # Output : False
my_list = ['item_1', 'item_2', 'item_3', 'item_4']
my_tuple = ('one', 'two', 'three')
my_dict = {'letter': 'g', 'number': 'seven', 'symbol': '&'}
# Variables can change type, simply by assigning a new value of a different type.
m = 10
print(m)
m = "this is a string"
print(m)
# chain assignment
a = b = c = 300
print(a, b, c)
print(id(a), id(b), id(c)) # 2422970673456 2422970673456 2422970673456
# Python also allows you to assign several values to several variables
# within the same line.Each of these values can be of a different data type
j, k, l = "shark", 2.05, 15
print(j, k, l)
# global and local variables
glb_var = "global"
def var_function():
lcl_var = "local"
print(lcl_var) # local
print(glb_var) # Print glb_var within function - global
var_function()
print(glb_var) # global
# local variable can't be accessed outside scope
# print(lcl_var) # NameError: name 'lcl_var' is not defined
# defining same global variable name inside function
num1 = 5 # Global variable
name = "Abcd"
def my_function():
global name
# same variable name as global variable num1 - this will have local scope
num1 = 10
num2 = 7 # local variable
print(num1) # Print local variable num1 - 10
print(num2) # Print local variable num2 - 7
name = "Raghu"
# Call my_function()
my_function()
print(num1) # Print gloabl variable num1 - 5
print(name) # Print the updated name - Raghu
# Note :
# The naming of variables follows the more general concept of an identifier.
# Variable names must be made up of only letters, numbers, and underscore (_).
# Variable names cannot begin with a number.
# Best practices:
# The Class names starting with a capital letter.
# All other identifiers should begin with a lowercase letter.
# Declare private identifiers by using the (‘_’) underscore as their first letter.
# Avoid using names with only one character. Instead, make meaningful names.
# You can use underscore to combine multiple words to form a sensible name.