Python Basic Tutorials

Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more

Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c

To make everything easy: We refer CPython as Python

Python Variables,Constants and Literals

Python Variables

Basically, Variables are the names given to the literals or any objects in python.

In python, there are so many data types(such as integer, strings, booleans) and data structures (such as tuples, lists, dictionaries). During programming, we need to identify each data of any data type or of any data structure in order to perform any operation, & which is done by assigning the data/value to the variable name.

More specifically, variables are like the named container in which we can store data.

Let's take a Simple Example
Here, "David" is assigned to the string variable named name.
Also, 03 is assigned to the integer variable named roll_no.
Then, True is assigned to the Boolean variable named flag.

>>>name = "David"    #string class object
>>>roll_number = 03  #integer class object
>>>flag = True       #boolean class object

So, in python there is no need to explicitly specify the data type of the variable, the python interpreter identifies the data type of any variables based on which datatype's value is stored in that particular variable.

Value assignment to the variable in Python

Now, let us assign some values to the variables and print them.


name = "Harry"
age = 24
is_married = False
fav_foods = ["Rice", "Spicy_Pizza", "Chicken_Rolls", "Breads", "Burger"]
print(f"Details of {Name}!!!\n")
print("Name: ", name)
print("Age: ", age)
print("Marital_status: ", is_married)
print("Favorite Food List: ", fav_foods)
Output:
Details of Harry!!!
Name: Harry
Age: 24
Marital_status: False
Favorite Food List: ['Rice', 'Spicy_Pizza', 'Chicken_Rolls', 'Breads', 'Burger']

Every time we assign the values to the same variable, the latest value overwrites previous value


>>>country = 'Russia'
>>>print(country)
   Russia
>>> #Now let us assign another value to the same variable `country`.
>>>country = 'USA'
>>>print(country)
   USA

Python Constants

The Constants are those variables in python which values cannot be modified. Its value is permanent for every scenario. For example, PI is a constant which is defined in the math module.

Declaring and Assigning values to Constants

To declare and assign the values to the constants, we need to create a module. Modules are python files that contain several methods, functions, variables that can be used by importing them into the main program.

A simple Example

Let us create a file of extension .py in which we declare constants. Here, we will assign corresponding constant values to the corresponding constant variables.


#constant.py
PI = 3.14
g = 9.8 #acceleration due to gravity.

Let us import the module and use it.


>>>import constant
>>>print(constant.PI)
   3.14
>>>print(constant.g)
   9.8

Python Literals

Literals are the values that are assigned to the variables and constants. In python, there are various kinds of literals available Which are basically the different values of different data types stored in the variable.

Let us create and store the literals of different datatype in variables.

Example1-Numeric literals

num1 = 32423 #Number literal
num2 = 5j #Complex literal
num3 = 5.23 #float literal

print(num1, type(num1))
print(num2, type(num2))
print(num3, type(num3))
Output:
32423 <class'int'>
5j <class'complex'>
5.23 <class'float'>
Example2-String literals

string_literal = "Harry" #String Literal
char_literal = "A" #Character Literal
multiline_literal = """This is
                    multiline statement.""" #Multiline Literal
unicode_literal = "\U00000394" #Unicode Literal

#Though all the literal type belongs to class String.
print(string_literal, type(string_literal))
print(char_literal, type(char_literal))
print(multiline_literal, type(multiline_literal))
print(unicode_literal, type(unicode_literal))
Output:
Harry <class 'str'>
A <class 'str'>
This is
multiline statement. <class 'str'>
Δ <class 'str'>
Example3-Boolean literals

Boolean literals have two values: either True or False.


true_literal = True
false_literal = False

print(true_literal, type(true_literal))
print(false_literal, type(false_literal))
True <class 'bool'>
False <"class 'bool'>
Example4-None literals

None literal is the special kind of literal in python. It is used to specify there is nothing in the field.


none_literal  = None
print(none_literal, type(none_literal))

Output:
None <class 'NoneType'>
Note: a function will return None if it does not return a value.
def show():
    print("Hi!!!")

r = show()
print(r,type(r)) #outputs: None <class 'NoneType'>


Example5-Collection literals

Different data structures in python, like lists, dictionaries, tuples, sets, arrays are also taken as literals.


numbers = (1,2,3,4) #tuple literal
student = {"Name":"John","Roll_Num":"0012","Address":"Utah"} #Dictionary literal
student_list = ["Richards", "Nancy", "Albert", "Larry"]
city_number = {44600,44500,49200,43221}

print(numbers,type(numbers))
print(student,type(student))
print(student_list,type(student_list))
print(city_number,type(city_number))
Output:
(1, 2, 3, 4) <class 'tuple'>
{'Name': 'John', 'Roll_Num': '0012', 'Address': 'Utah'} <class 'dict'>
['Richards', 'Nancy', 'Albert', 'Larry'] <class 'list'>
{44600, 49200, 44500, 43221} <class 'set'>

Python variable scope

Python variable scope means the ability that show from which part of the program we can access any variables. The concept of the scope is the access range of any variable name.

There are basically 3 types of variable access they are:

  • Local Scope The variables which are defined within a function and its access range are only within that function. That is called local variable scope.

    a=10 #global variable
    def local():
        a=20 #local variable
        print(a)
    
    local() # will print 20 from inside func
    
    print(a) # will print 10
    
    Output:
    20
    10
  • Global Scope

    The variable which can be accessed from any part of the program is known as the Global scope variable. When we want to use the same variable name within the various local functions, we declare a global scope variable.

    we can make any variable global using the global keyword.

    Example
                
    a=2
    b=3
    
    def add():
        global a
        global b
        a=10   #change global value of `a`
        print(a+b) #outputs 13
    
    def sub():
        global a
        global b
        print(a-b) #outputs 7
    
    add() # global value of `a` becomes 10
    sub()
                
            
    Output:
    13
    7
    
  • Builtin Scope

    If python does not find a Global or Local scope variable in the program it looks for a built-in scope variable. The built-in scope variable is those variables that are already defined within a built-in module.

    For example, the 'PI' variable from the math module is a built-in scope variable.

    
    from math import pi
    print(pi)
    
    Output:
    
    3.141592653589793