"Python programiTutorial Part 2: "

 Hey guys ,

Welcome back in new post Python Tutorial part-2 . Lets start the remaining part here..

First Python Program:

Before starting a code we have to install python on your machine for more about installation click me

We will discuss the basic syntax of python. now firstly we will see the first and simple "HELLO WORLD "program. Run this program.

Python provides us two way to run the program:

1.Using Interactive interpreted command prompt.

this is image of Interactive interpreted command prompt with the "HELLO WORLD" program with output.




2.Using a script file.

This is the image of  script file with the code of "HELLO WORLD ' program with out put. 

Script mode has some advantages and disadvantages :

1.We run multiple lines of code at a time in script mode. 

2.Run and interpretation process or debugging is easy in the script mode.

3.It is best for beginners and expert also.

Disadvantages:-

1.we have to save the code every time if you make changes in code

2.It can be tedious when we run single line or multiline of code 



these two are comes with python package at time of installation.


Comment in Python:

What is comment:- Comment are text notes added to the program to provide explanatory information about the program. By looking the comment , we can easily understand the intention of  every line that we have written in the code.  

in python, we can  apply comment using hash character(#).The Python interpreter ignores entire line  followed by a hash character.

python provides the facility to write comment in two way 

1.Single line comment .(hash # ....comment line........)

2.Multiline comment .

python doesn't have explicit support for multiline comment . but we can use # character for multiple line.

Below Image show the example with single line comment or Multi-line comment:


Tokens:
the token can be defined as a punctuator marks, reserved keywords, and each word in statement.
the token is the smallest unit inside the given program .keywords ,identifiers , Literals ,operators are the tokens in the python.

Python Identifiers:-
Identifiers are user define names. it is used to identify variable, function, class, module or other objects.
There are few rules to follow while declaring the python variable. Identifiers and variable declaration rules are same.
Rules:-
1.Varible name must start with Alphabet or underscore(_).
2.Varible cant start with numbers.
3.special character not allowed.
4.The variable name is case sensitive . eg. 'A' and 'a 'consider as difference variable name.
for e.g. with output

some example :-
Value1 : valid
5x        : invalid
_temp  : valid
112      : invalid
data     : valid

Keywords:
 There are certain reserved worlds, called keywords that have standard ,predefined meaning in python.
These key words can be used only for their intended purpose; they cannot be used as programmer-defined  variable names.
following are the keywords in python:-



Python Variables:-
Variable is a name to the memory location in which data can be stored and subsequently recalled. variables are used for holding data values so that they can be utilized in various computations in a program.
A variable name can be chosen by the programmer.
python variable are also known as identifier or it is used to hold value.
In python we don't need to specify the type of variable because python is infer language and smart enough to get variable type.
variable are the example of identifier. identifiers is identify the literals in the program.
rules of variable declaration are same as like identifier declaration that are mentioned in above point identifier.
Declaring and assigning variable:-
Its allows us to create a variable at the required time .we don't need to declare explicitly variable in python. when we assign any value to the variable that variable declared automatically . assignment  operator(=) used to assign the value.
Python allows us to assign a value to multiple variables in single line statement ,which also known as multiple assignment.
E.g.  Number=200 // it assign 200 value number python get automatically the type of variable.
         Name="Sam" // this gets string type value.
        Salary=2222.20 // it get float or real type value.
following image show the types of variable declared in above examples: 

 In python two types of  Variable;
1 local variable:  these types of variables are declared inside the function and have scope only within the function.
2.Global variable : these types of variable are declared the outside of the function. python provide the "global" keyword to use global variable inside the  function. if we do not use the key word ,the function treat as a local variable .

Data types:-
Variable can hold the value in the program ,every value has a data type. But in python we do not need to defined the type of the variable while declaring it because python is dynamically typed language.
the interpreter implicitly bind the value with its type.
 For eg. check the image in example :-

Python provides various Standard data types that define the storage method on each  of them .
these are Number ,Sequence type, Booleans, Set, Dictionary .Again these types have sub types these are shown in below image:
 
These are explain below in brief:
1.Numeric data type:-
These type of data is stored numeric values. The integer ,float and complex number values belongs to a python number data types.
Python supports three types of numeric data:
     1. int :- integer value can be any number assigned or unsigned ,any length .python has no restriction on the length of integer . Eg.-200,10,-20,30.

     2. float:- it is used to  stored the real number value or floating-point number like 1.22,22.3,4.5.It is accurate up to 15 decimal number.

     3. complex :- A complex number contains an ordered pair ,xi+iy where x denote real and y represent imaginary parts . eg. 2.12j, 30.0+2j etc.
we can use the type() function to which class a variable or a value belongs.
similarly isinstance() function is used to check an object belongs to a particular class.

2. Dictionary:-
Dictionary is an unordered set of key-value pair of item. Its is an associative array or hash table where each key stores a specific value. key can hold any primitive data type, whereas value is an arbitrary Python object.
in the dictionary the item are separated with commas (,) and enclosed in the curly braces{}.
Syntax:-
dictionary={key1:value,key2:value,...}
dictionary[key]=value.
E.g.

3.Boolean type:-
Boolean type provides two built-in value true and false. these values are used to determines the given statement is true or false. it denotes by the class bool.  true register by any non zero value or "T" and false are zero or "F".
e.g
print(type(True))
print(type(False))
print(True)
it generate following output:
<class 'bool'>
<class 'bool'>
NameError :name 'false' is not defined.

4.Set:-
python set is the unordered collections of the data. It is  mutable(can modify after creation).
it has unique element . In Set , the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a built in function set() or a sequence of  element is passed in curly braces and separated by commas. It contains various types of data.
Syntax-
set={value1,value2..}
set()
Eg.

5.Sequence Type :-
     1.String:-
         Sequence of characters represented in the quotation mark("  " , '   ') is also known as string .
We can use single, double, triple quotes to define a String. String handling in python is straightforward task since python provides built in functions and operators to perform operations in the string.
Syntax:
string="string" or 'string' 
Following example illustrates the string in python and some string handling operations  in python.
Eg.

2. List:-
Python lists are similar to array in c. However, the list can contain data of different types. The items stores in the list are separated with comma(,) and enclosed within square brackets[]. We can use slice[;] operators to access the data of  the list. The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were working with the strings.
Syntax:-
list=[elements1,element2,,,,]
Given Example shows .:

3.Tuple:-
Tuple  is similar to list . Like list and array it stores different  types of data .the items of the tuple are separated with a comma (,)and enclosed in parentheses().
A tuple is a read only data data structure as we cant modify the size and value of the items of tuple.it is mutable data type.
Syntax:-
tuple=(element1,element2,....)
Eg.

 Python Literals: 
 Python Literals can be defined as data that is given in a variable or constant.
following are the types of literals:
1.String Literals: in this Literals are enclosed by quotes.
eg. 'Sam' ,"Sammy". Or name='Sam' , Name="SammY"
   again it have two types one is single line string and another is multi line string.

2.Numeric Literals:
 Numeric Literals are immutable .Numeric Literals can belong from following four types Int, Long Int, Float, Complex. Eg., 20, -3000,13.00, 5i+7.2j. Or  number=233,  A=23.23.

3.Boolean Literals:
A Boolean  literals can have only two value true or false.

4.Special Literals:
Python uses only one special literal i.e. None ,None is used to specify to that is not created . it is also used to end of list.
e.g.,
A=100
b=None
print(A)
print(b)
output: 
 100
None

5.Litetral collection:
Python provides four types of literal collection list literal, tuple literal, Dictionary Literal, set literals. 
eg. list=[101,'Sam'],Tuple=(200,'Samu'), Dictionary={'Name':'Samy','realno':10.20,'num':300},Set={'black', 'white'}.

Operators:-
Operator is a symbol  which is used to perform operation between two operands. Operators are the pillar of a program on which the logic is built in a specific programming language.
Like other languages python also provide variety of operator that are listed below:

1.Arithmetic operator(+ , -, *, / , % , // , **):-
Arithmetic operator are used to perform arithmetic operation between two operands.
+(Addition):-It is used to perform addition operation.
-(Subtraction):-It is used to subtract the second operand from the first operand.
/(Divide):-It returns the quotient after dividing the first operand by the second operand .
*(Multiplication):-It is used to multiply one operand with the other.
%(Reminder):-It returns the reminder after dividing the first operand by the second operand.
**(Exponent):-It is an exponent operator represented as it calculates the first operand to the second operand.
//(Floor):-It gives the floor value of the quotient produced by dividing the two operand.
Below program shows the all operations:-

2.Comparison operator:-
It is used to comparing the value of two operands and returns Boolean true or false accordingly.
1.==:- If the value of two operands is equal ,then the condition become true.
2.!= :- If the value of two operands is not equal, then the condition become true.
3.<=:- If the operand is less than or equal to the second operand, then the condition becomes true.
4.>=:- If the first operand is greater than or equal to the second operand, then the condition become true.
5.>:- If the first operand is greater than the second operand, then the condition becomes true.
6.<:- It the first operand is less than the second operand, then the condition becomes true.
Eg.

3.Assignment Operators:-
It is used to assign the value of the right expression to the left operand.
1.= :-It assign the value of the right expression to the left operand.
2.+= :- It increases the value of the left operand by the value of the right right operand and assigns  the  modified value back to left operand.
3.-= :-It decreases the value of the left operand by the value of the right right operand and assigns  the  modified value back to left operand.
4. *= :-It Multiplies the value of the left operand by the value of the right right operand and assigns  the  modified value back to left operand.
5. %= :-It divides the value of the left operand by the value of the right right operand and assigns  the  reminder back to left operand.
6.**= :- a**=b will be the equal to a=a**b.
7. //= :- a//=b will be equal to a=a//b.
E.g. 

Tip: guess the above output is right or wrong .

4.Bitwise Operator:-
The bitwise operator perform bit by bit operation on the values of the two operands. 

1. &(binary and):- it both bits at the same place in two operands are 1, then 1 is copied to the result                                      otherwise ,0 is copied.
2. | (binary or) :- The resulting bit will be 0 if both the bits are zero; otherwise ,the resulting bit will be 1

3. ^(binary Xor) :-The resulting bit will be 1 if both the bits are different ; otherwise ,the resulting bit                                 will be 0.
4.~(negation) :- It calculate the negation of each bit of the operand , i.e., if the bit is 0, the resulting bit                               will be 1 and vise versa .
5. <<(left shift):- The left operand value is moved left by the number of bits present in the right                                         operand.
6.>>(right shift) :- The left operand is moved right by the number of bits present in the right operand.

5.Logical operators:-
The logical operators are used primarily  in the expression evaluation to make a decision. python support following operators.
1. and :- Return true if both statements are true.
2. or :- Return true if one of the statements is true.
3.not :- Reverse the result ,returns false if the result is true.
E.g.

6.Identity operator:-
Identity operators are used to compare the objects, not if they are equal  ,but if they are actually the same object ,with the same memory location.
1.is :- returns true if both variable are the same object .
2. is not :- Returns true if both variable are not the same object.
E.g. of Is.

7.Membership operator:-
Membership operator is used to test if the sequence is presented in an object.
1.in :- Return true if a sequence with the specified value is present in the object.
2. not in :- Returns true if a sequence with the specified value is not presented in object.
e.g.

Operator precedence:-
The precedence of the operators is essential to find out since it enables us know which operator should be evaluated first . the precedence table of the operators in python is given below:-

Control Statements:-
Indentation in python:-
for the ease of programming and to achieve simplicity ,python doesn't allow the use of parentheses for block level code. in python, indentation is used to declare a block. if two statements are the same indentation level, then they are the part of the same block. 

1.Conditional Control Statement:-

1.If statement:-The if statement is used to test a specific condition, it the condition is true, a block of                              code(if-block) will be executed.
   Syntax:-
            if expression:
             statement   
           
                
2.if -else statement:-
            The if -else statement provides an else block combined with the if statement which is executed in the  false case  of the condition. if the condition is true , then the if block is executed .otherwise ,the else block is executed.

Syntax:-
 if condition:
 #block of statement
 else:
#another block of statement (else block)

3.elif Statement:-
the elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them. we can have any number of elif statement in our 
program depending upon our need.

Syntax:-
if expression 1:
#block of statement
elif expression 2:
#block of statements
elif expression3:
#block of statements
else:
#block of statement.

2.Looping control statements:-

Some advantages of loops:
1. it provides code reusability
2.using loops, we do not need to write the same code again and again.
3.using loops, we can traverse over the elements of data structure (array or linked list.)
There are the following loop statements in python.

1.for loop:-
the for loop in python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary.

Syntax:-
for iterating _ var in sequence:
statement(s)

for Loop using range() function:-
the range function is used to generate the sequence of numbers. if we pass the range (10),it will generate the number from 0 to 9.
the syntax of the range function is 

syntax: 
range(start, stop, step size)

e.g.
for i in range(10):
print(i,end=' ')
output:0123456789
  
Nested for loop:
Python allow us to nest any   number  of for loop inside a for loop.
the inner loop is executed n number of times for every iteration of the outer loop.

Syntax:-
for iterating_var1 in sequence:#outer loop.
for iterating_var2 in sequence :#inner loop.
  #block of statement
#other Statement

2.While loop:-
The python while loop allows a part of code to be executed until the given condition returns false.it is also known as pre tested loop. when we don't know the number of iterations then the while loop is most effective to use.

Syntax:
while expression
    statement

Looping control Statement:-
we can change the normal sequence of while loops execution using looping control statements.
1.continue statement:
when the continue statement is encountered ,the control transfer to the beginning of loop.

2.Break statement:-
when the break statement is encountered, it brings control out of the loop 

3.Pass Statement:-
The pass statement is used to declare the empty loop. it is also used to define empty class, function, and control statement.

Functions:--
A function can be defined as a block of organized ,reusable code that is used to perform a single, related action. Which can be called whenever required.
python allows us to divide a large program in to the basic building blocks known as a function.
The function contains the set of programming statement enclosed by {}. A function can be called multiple times to provide reusability and modularity to the python program.
Function helps programmer to break large code in to smaller parts.
It avoid the repetition of the code.

There are mainly two types of function in python:-

1. User-defined functions:-
the user defined function are those defined by the user to perform the specific task.
 
Creating function in python:-
python provides the "def" key word to define the function .

Syntax:-
            def  function_name (parameters):  
                    function_block
            return expression

Lets understand the syntax of function definition:-
* The "def" along with the function name used to defined the function.
* The identifier rules must follow the function name.
* A function accept the parameter (argument), and they can be optional.
*The function block is started with the colon (:) ,and block statement must be at the same indentation.
*The return statement sis used to return the value . a function can have only one return.

Function Calling:-
A function must be defined before the function call; otherwise ,the  interpreter gives an error.
to call function , use the function name followed by the parentheses.

E.g.

Argument in  function:-
passing argument to function with e.g.

 2.Python Built in Function:-
The python built in function are defined as the function whose functionality is predefined in python.
The python interpreter has several function that are always present for use.These function are also known as Built in function.
Following are some built in function:-
1.print():- it is used to print the statement .
2.abs():- The python abs() function is used to return the absolute value of a number.
3.all():- The python all() function accepts an iterable object(such as list, dictionary,  etc.)
4.bin():- It is used to return the binary representation of specified integer.
5.bool():- It converts a value to boolean(true or false) using the standard truth testing procedure.
6.bytes():-It is used for returning a byte object. it is an immutable version of bytearray().
7.callable():-it is something that can be called. 
8.compile():-function takes source  code as input and return a code object which can later be excuted by exec() function.
9.Sum():- It is used to get the sum of numbers of an iterable , i.e , list.
10.flaot():- IT returns a floating point number from a number or string.
and so many functions are present in python.
Classes in python :-
 
Python is object oriented programming language . Almost everything is an object, with its properties and methods.
A classes is like an object constructor, or a "blueprint" for creating object.
to create class the "class" keyword is used.
to create class object class name is used .
you can delete object by using the del keyword

_init_() function:-

To under stand the meaning of classes we have to understand the built in _init_() function.
All classes have a function called _init_(), which is always executed when the class is being initiated.
Use the this function to assign value to object properties , or other operations that are necessary to do when the object is being created.
this function is called automatically every time the class is being used to created a new object.
 
The self parameter:-

The self is parameter is a reference to the current instance of the class ,  and is used to access variables that belongs to the class. it does not have to be named self , you can call it whatever you like , but to be the first parameter of any function in the class.

E.g.

Python module:-
  A python module can be defined as a python program file which contain a python code including python function , class , or variable.
in python other words , we can say that our python code file saved with the extension (.py) is treated as the module. 
module in python provides us the flexibility to organize the code in logical way.
To use the functionality to one module into another , we have to import specific module.

Import Statement:-
we need to load the module in our python code to use its functionality. python provides two types of statements as defined below:
1. The import statement:
import statement is used to import all the functionality of one module into another.
we can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times ,it has been imported into our file.

Syntax:-
import module1, module2.......module n.

2. form import statement:-
instead of importing the whole module into the namespace , python provides the flexibility to import only the specific attributes of module.
Syntax:-
from<module-name> import<name1>.....,<name n> 

E.g.

Python exception:-
An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program.

Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error

Python provides a way to handle the exception so that the code can be executed without any interruption. If we do not handle the exception, the interpreter doesn't execute all the code that exists after the exception.
Python has many built-in exceptions that enable our program to run without interruption and give the output. These exceptions are given below:

Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common standard exceptions. A list of common exceptions that can be thrown from a standard Python program is given below.

1.ZeroDivisionError: Occurs when a number is divided by zero.
2.NameError: It occurs when a name is not found. It may be local or global.
3.IndentationError: If incorrect indentation is given.
4.IOError: It occurs when Input Output operation fails.
5.EOFError: It occurs when the end of the file is reached, and yet operations are being performed.

The try-expect statement
If the Python program contains suspicious code that may throw the exception, we must place that code in the try block. the try block must be followed with the except statement ,which contains a block of code that will be executed if there is some exception in try block.
Syntax:-

try:
#Block of code;
expect exception1:
#block of code;
.
.
.except exception n:
#block of code;




Comments

  1. Excellent post. You have shared some wonderful tips. I completely agree with you that it is important for any blogger to help their visitors. Once your visitors find value in your content, they will come back for more How to Run Python Program In Script Mode



    ReplyDelete

Post a Comment