Basics of Python Programming

Features of Python

Python provides number of features as follows,
  • Easy to Learn and Use - Python is easy to learn and use. It is user and developer - friendly programming language.
  • Expressive Language - Python language is understandable and readable.
  • Interpreted Language - Python is an interpreted language. Due to interpreter code is executed line by line at a time.
  • Cross-platform Language - Python work with different platforms, we can say that Python is a platform independent / portable programming language.
  • Free and Open Source - Python language distribution is freely available it means that the source-code freely available for further development.
  • Object-Oriented Language - Python is object oriented language and all concept related to object orientated  supported by python.
  • Large Standard Library - IPython having large number of library and it provides rich functions and packages for application development in easy way.
  • GUI Programming Support - Graphical user interfaces such as Web Application (Django/Flask), Desktop Application (Tkinter) and Game Application can be developed using Python.
  • Integrated It can be easily combined with languages like C, C++, java and many more languages for developing integrated cross platform application.
History and Future of Python
  • Python development started by late 1980s.
  • The actual implementation of Python was started by Guido Van Rossum at CWI in Netherland in the December 1989. Guido Van Rossum published the code in February 1991,
  • Python 1.0 was released in 1994, with some features like: filter, lambda, map, and reduce.
  • Python 2.0 came with new features like: list comprehensions, garbage collection.
  • Python 3.0 was released on 3rd December, 2008,
  • ABC and Modula-3 programming language was a predecessor of Python language.
  • Python is influenced by following programming languages:
    • ABC language.
    • Modula-3
Future of Python

Now a days, Python is general purpose programming language which is used for various application development. Here, some identifying applications where python is used.
  • Web Applications - Python is used to develop web applications, for web application development various libraries are used. Python work with various frameworks such as Django and Flask to design and develop web based applications.
  • Desktop GUI Applications - Python having Tk library to develop desktop based application. Now a days, KIVY is more popular for writing mobile application.
  • Software Development - Python works as support language and it is used for building testing, security and game applications etc.
  • Scientific and Numeric - Python is widely used in machine learning application. There are various libraries such as SciPy, Pandas, matplotlib is available for data analytics etc.
  • Business Applications - Using Python, it is very easy for us to build Business applications like CRM and ERP.
  • Console Based Application - IPython is best example for console based application.
  • Audio or Video based Applications - Python used to develop multimedia applications such as object detection, audio detection and many more.
  • Enterprise Applications - Python help to create Enterprise base applications, OPENERP is best example of Enterprise base applications
  • Applications for Images - Using Python we can build image recognition application. For medical image analysis python is mostly used.
Writing and executing python program

Installation of Python
  • Download the current production version of Python (3.8) from the Python official site. Double click on the file that you just downloaded.
  • Accept the default options given to you until you get to the Finish button. Your installation is complete.
Setting up the Environment
  • Starting at My Computer go to the following directory C:\Python38. In that folder you should see all the Python files. 
  • Copy that address starting with C: and ending with 38 and close that window.
  • Click on Start. Right Click on My Computer.
  • Click on Properties. Click on Advanced System Settings or Advanced.
  • Click on Environment Variables.
  • Under System Variables search for the variable Path.
  • Select Path by clicking on it. Click on Edit.
  • Scroll all the way to the right of the field called Variable value using the right arrow.
  • Add a semi-colon (;) to the end and paste the path (to the Python folder) that you previously copied. 
Variable  
  • Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.
  • In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough to get variable type.
  • Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore.
  • It is recommended to use lowercase letters for variable name. SPPU and Sppu both are two different variables.
Identifier Naming
  • Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to name an identifier are given below.
  • The first character of the variable must be an alphabet or underscore ( _).
  • All the characters except the first character may be an alphabet of lower-case (az), upper-case (A-Z), underscore or digit (0-9).
  • Identifier name must not contain any white-space, or special character (! , @, #, %, ^, &, *).
  • Identifier name must not be similar to any keyword defined in the language.
  • Identifier names are case sensitive for example my name, and MyName is not the same.
  • Examples of valid identifiers: a123, _n, n_9, etc.
  • Examples of invalid identifiers: 1a, n%4, n 9, etc.  
Declaring Variable and Assigning Values
  • Python does not bound us to declare variable before using in the application. It allows us to create variable at required time.
  • We don't need to declare explicitly variable in Python. When we assign any value to the variable that variable is declared automatically.
  • The equal (=) operator is used to assign value to a variable.  
Example – Assign the value to a variable.

#Assigning the value to variable
a = 10
b = 20
c = a + b
print ("Value of A is :", a)
print ("Value of B is :", b)
print ("Value of C is :", c)

Output

Value of A is : 10
Value of B is : 20
Value of C is : 30

Multiple Assignment
  • Python allows us to assign a value to multiple variables in a single statement which is also known as multiple assignment.
  • We can apply multiple assignments in two ways either by assigning a single value to multiple variables or assigning multiple values to multiple variables. Let’s see given examples.  
Example – Multiple Assignment

# Assigning the value to variable (Multiple Assignment)
a, b, c= 10, 20, 30

print ("Value of A is :", a)
print ("Value of B is :", b)
print ("Value of C is :", c)

Output

Value of A is : 10
Value of B is : 20
Value of C is : 30

Python Data Types  
  • Variables can hold values of different data types. Python is a dynamically typed language hence we need not define the type of the variable while declaring it. The interpreter implicitly binds the value with its type. 
  • Python enables us to check the type of the variable used in the program. Python provides us the type () function which returns the type of the variable passed. 
  • Consider the following example to define the values of different data types and checking its type.
Example : type()

# Finding out the data type of variable

a = 10 # Integer Data
b = "Hello World" # String Data
c = 100.45 # Float Data

print(type(a))
print(type(b))
print(type(c))

Output

<class 'int'>
<class 'str'>
<class 'float'>

Standard data types

  • A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id must be stored as an integer.
  • Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below.
  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary  
Numbers
  • Number stores numeric values. Python creates Number objects when a number is assigned to a variable. For example;   a = 10, b = 20 #a and b are number objects
  • Python supports 4 types of numeric data.
  1. int (signed integers like 10, 2, 29, etc.)
  2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
  3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
  4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
  • Python allows us to use a lower-case L to be used with long integers. However, we must always use an upper-case L to avoid confusion.
  • A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts respectively).  
String

  • The string can be defined as the sequence of characters represented in the quotation marks. In python, we can use single, double, or triple quotes to define a string.
  • String handling in python is a straightforward task since there are various inbuilt functions and operators provided.
  • In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+" python" returns "hello python". 
  • The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ". 
  • The following example illustrates the string handling in python.  
Example : String Variable Operation

str1 = 'hello world' #string str1
str2 = 'have a nice day' #string str2
print ("First String is :", str1)
print ("Second String is :", str2)
print ("Printing first three character using slice operator : ",str1[0:3])
print ("Printing 5th character of the string : ",str1[5])
print ("Printing the string three time : ",str1*3)
print ("Printing the concatenation of str1 and str2 : ",str1 + str2)

Output

First String is : hello world
Second String is : have a nice day
Printing first three character using slice operator : hel
Printing 5th character of the string :
Printing the string three time : hello worldhello worldhello world
Printing the concatenation of str1 and str2 : hello worldhave a nice day

List
  • Lists are similar to arrays in C. However; the list can contain data of different types.
  • The items stored in the list are separated with a 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.
  • Consider the following example.  
Example : List Operations

list1 = [1, "hello", "World", 3]
print ("Print complete list :", list1)
print ("Print the element of a 3rd position :", list1[3:])
print ("Print First Three Elements :", list1[0:2])
print ("Print list two time (concatenation): ",list1 + list1)
print ("Multiple of a list three times :", list1 * 3)

Output

Print complete list : [1, 'hello', 'World', 3]
Print the element of a 3rd position : [3]
Print First Three Elements : [1, 'hello']
Print list two time (concatenation): [1, 'hello', 'World', 3, 1, 'hello', 'World', 3]
Multiple of a list three times : [1, 'hello', 'World', 3, 1, 'hello', 'World', 3, 1, 'hello', 'World', 3]

Tuple
  • A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types. 
  • The items of the tuple are separated with a comma (,) and enclosed in parentheses (). 
  • A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple. 
  • Let's see a simple example of the tuple.  
Example : Tuple Operations

tuple1 = (1, "hello", "World", 3)
print ("Print complete tuple :", tuple1)
print ("Print the element of a 3rd position :", tuple1[3:])
print ("Print First Three Elements :", tuple1[0:2])
print ("Print list two time (concatenation): ",tuple1 + tuple1)
print ("Multiple of a list three times :", tuple1 * 3)

Output

Print complete tuple : (1, 'hello', 'World', 3)
Print the element of a 3rd position : (3,)
Print First Three Elements : (1, 'hello')
Print list two time (concatination): (1, 'hello', 'World', 3, 1, 'hello', 'World', 3)
Multiple of a list three times : (1, 'hello', 'World', 3, 1, 'hello', 'World', 3, 1, 'hello', 'W orld', 3)

Dictionary
  • Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash table where each key stores a specific value. Key can hold any primitive data type whereas value is an arbitrary Python object.
  • The items in the dictionary are separated with the comma and enclosed in the curly braces {}.
  • Consider the following example.
Example : Dictionary Operations 

dict1 = {101:'Sumit', 102:'Ashwini', 103:'Kalyan', 104:'Vinod'};
print("First Person is :", dict1[101])
print("Second Person is : ",dict1[102])
print("Third Person is : ",dict1[103])
print("Fouth Person is : ",dict1[104])
print ("List of All Person is : ", dict1)
print ("ID's of All Person is : ", dict1.keys())8. print ("Name of All Person is : ", dict1.values())

Output

First Person is : Sumit
Second Person is : Ashwini
Third Person is : Kalyan
Fouth Person is : Vinod
List of All Person is : {101: 'Sumit', 102: 'Ashwini', 103: 'Kalyan', 104: 'Vinod'}
ID's of All Person is : dict_keys([101, 102, 103, 104])
Name of All Person is : dict_values(['Sumit', 'Ashwini', 'Kalyan', 'Vinod'])

Python Keywords 
  • Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter. 
  • Each keyword have a special meaning and a specific operation. These keywords can't be used as variable. 
  • Write a following code to get all keyword details.
Example : Getting Keywords in Python

import keyword
print(keyword.kwlist)

Output

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Taking input in Python  
  • Developers often have a need to interact with users, either to get data or to provide some sort of result. 
  • Most programs today use a dialog box as a way of asking the user to provide some type of input. 
  • While Python provides us with two inbuilt functions to read the input from the keyboard.
  1. raw_input ( prompt )
  2. input ( prompt )
raw_input ( )

This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store.  

Example

# Python program showing a use of raw_input()
data = raw_input("Enter your name : ")
print (data)
# Note : Working in Python 2X

Output

Enter your name : Sumit
Sumit

Here, data is a variable which will get the string value, typed by user during the execution of program. 

input ( )

This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python.

Example

# Python program showing a use of raw_input()
data = input("Enter your name : ")
print (data)

Output

Enter your name : Sumit
Sumit 

How the input function works in Python
  • When input() function executes program flow will be stopped until the user has given an input. 
  • The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional.
  • Whatever you enter as input, input function convert it into a string. If you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting. 
Constant in Python  

In Python, constants are usually declared and assigned on a module. Here, the module means a new file containing variables, functions etc which is imported to main file.  

Example : Constant in Python

# Find out the value of PI
import math
print("The Value of PI is :", math.pi)

Output

The Value of PI is : 3.141592653589793

In the above program, we create a python module file. Then, we assign the constant value to PI  After that, Finally, we print the constant value. In reality, we don't use constants in Python. The global or constants module is used throughout the Python programs.  

Python Comments  
  • Comments are very important while writing a program. It describes what's going on inside a program so that a person looking at the source code does not have a hard time figuring it out. 
  • You might forget the key details of the program you just wrote in a month's time.
  • So taking time to explain these concepts in form of comments is always fruitful. 
  • In Python, we use the hash (#) symbol to start writing a comment. 
  • It extends up to the newline character. Comments are for programmers for better understanding of a program. Python Interpreter ignores comment.
#This is a comment
#print out Hello
print('Hello')

Multi-line comments
  • If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
  •  Another way of doing this is to use triple quotes, either ''' or """.
  • These triple quotes are generally used for multi-line strings. But they can be used as multi-line comment as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of  multi-line comments"""

Python Indentation
  • Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation.
  • A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. 
  • Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.
Example :  Use of Indentation Program

n = int(input("Enter the value of n :"))
i = 0
print ("All Even number from 0 to n is :")
for i in range(n):
if(i % 2 == 0):
print (i)
Output

Enter the value of n :10
All Even number from 0 to n is :
0
2
4
6
8
 
Python Statement 

Instructions that a Python interpreter can execute are called statements. For example, a = 10 is an assignment statement. If statement, for statement, while statement etc. are other kinds of statements which will be discussed later.

Multi-line statement

In Python, end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\). For example:

number = 10 + 20 + 30 + \
40 + 50 + 60 + 
\70 + 80 + 90

This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as 

number = (10+ 20 + 30 +
40 + 50 + 60 +
70 + 80 + 90)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:

games = ['Cricket',
'Football',
'Holly ball ']

We could also put multiple statements in a single line using semicolons, as follows

a = 10; b = 20; c = 30;

Basic Operators in Python

Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, division and etc.


Example : Arithmetic Operators

n1 = int(input("Enter First Number :"))
n2 = int(input("Enter Second Number :"))

# Addition of numbers
add = n1 + n27. 
# Subtraction of numbers
sub = n1 - n2
# Multiplication of number
mul = n1 * n2
# Division(float) of number
div1 = n1 / n2
# Division(floor) of number
div2 = n1 // n2
# Modulo of both number
mod = n1 % n2

# print results
print("Addition of numbers :", add)
print("Subtraction of numbers :",sub)
print("Multiplication of number :",mul)
print("Division(float) of number :", div1)
print("Division(floor) of number :", div2)
print("Modulo of both number :", mod)

Output

Enter First Number :5
Enter Second Number :2
Addition of numbers : 7
Subtraction of numbers : 3
Multiplication of number : 10
Division(float) of number : 2.5
Division(floor) of number : 2
Modulo of both number : 1

Relational Operators

Relational operators compares the values. It either returns True or False according to the condition. 

 
Examples : Relational Operators

a = 10
b = 20
print ("The Value of 'a' is :", a)
print ("The Value of 'b' is :", b)

# a > b is False
print("Print Result of 'a > b' : ",a > b)

# a < b is True
print("Print Result of 'a < b' : ",a < b)

# a == b is False
print("Print Result of 'a == b' : ",a == b)

# a != b is True
print("Print Result of 'a != b' : ",a != b)

# a >= b is False
print("Print Result of 'a >= b' : ",a >= b)

# a <= b is True
print("Print Result of 'a <= b' : ",a <= b)

Output

The Value of 'a' is : 10
The Value of 'b' is : 20
Print Result of 'a > b' : False
Print Result of 'a < b' : True
Print Result of 'a == b' : False
Print Result of 'a != b' : True
Print Result of 'a >= b' : False
Print Result of 'a <= b' : True

Logical operators

Logical operators perform Logical AND, Logical OR and Logical NOT operations.  


# Examples : Logical Operators

a = True
b = False

print ("The Value of 'a' is :", a)
print ("The Value of 'b' is :", b)

# Print a and b is False
print("Print Result of 'a and b' : ", a and b)

# Print a or b is True
print("Print Result of 'a or b' : ",a or b)

# Print not a is False and a is True
print("Print Result of 'not a ' : ", not a)
print("Print Result of 'not b ' : ", not b)

Output

The Value of 'a' is : True
The Value of 'b' is : False
Print Result of 'a and b' : False
Print Result of 'a or b' : True
Print Result of 'not a ' : False
Print Result of 'not b ' : True

Bitwise operators

Bitwise operators acts on bits and performs bit by bit operations.  


Examples : Bitwise operators

a = 9
b = 5

print ("The Value of 'a' is :", a)
print ("The Value of 'b' is :", b)

# Print bitwise AND operation

print("Print Result of 'a & b' : ",a & b)11.
# Print bitwise OR operation
print("Print Result of 'a | b' : ",a | b)

# Print bitwise NOT operation
print("Print Result of '~a' : ",~a)

# print bitwise XOR operation
print("Print Result of 'a ^ b' : ",a ^ b)

# print bitwise right shift operation
print("Print Result of 'a >> b' : ",a >> 2)

# print bitwise left shift operation
print("Print Result of 'a << b' : ",a << 2)

Output

The Value of 'a' is : 9
The Value of 'b' is : 5
Print Result of 'a & b' : 1
Print Result of 'a | b' : 13
Print Result of '~a' : -10
Print Result of 'a ^ b' : 12
Print Result of 'a >> b' : 2
Print Result of 'a << b' : 36

Assignment operators

Assignment operators are used to assign values to the variables.  



Special operators

There are some special type of operator’s like

Identity operators 

is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

is True if the operands are identical
is not True if the operands are not identical

Example : Identity operators

a1 = 35
b1 = 35

a2 = 'PythonProgramming'
b2 = 'PythonProgramming'

a3 = [10,20,30,40]
b3 = [10,20,30,40]

print ("The Value of 'a1' is :", a1)
print ("The Value of 'b1' is :", b1)
print ("The Value of 'a2' is :", a2)
print ("The Value of 'b2' is :", b2)
print ("The Value of 'a3' is :", a3)
print ("The Value of 'b3' is :", b3)
print("Print Result of 'a1 is not b1' :", a1 is not b1)
print("Print Result of 'a2 is b2' :",a2 is b2)
print("Print Result of 'a3 is b3' :", a3 is b3)

Output

The Value of 'a1' is : 35
The Value of 'b1' is : 35
The Value of 'a2' is : PythonProgramming
The Value of 'b2' is : PythonProgramming
The Value of 'a3' is : [10, 20, 30, 40]
The Value of 'b3' is : [10, 20, 30, 40]
Print Result of 'a1 is not b1' : False
Print Result of 'a2 is b2' : True
Print Result of 'a3 is b3' : False 

Note: a3 and b3 are list. They are equal but not identical. It is because interpreter locates them separately in memory although they are equal.  

Membership operators

in
and not in are the membership operators; used to test whether a value or variable is in a sequence.

in True if value is found in the sequence
not in True if value is not found in the sequence

Examples : Membership operator

a = 'Python Programming'
b = {2:'x',6:'y'}

print ("The Value of 'a1' is :", a)
print ("The Value of 'b1' is :", b)

print("Print Result of ''y' in a' :", 'y' in a)
print("Print Result of ''Python' not in a' :", 'python' not in a)
print("Print Result of ''python' not in a' :", 'python' not in a)
print("Print Result of ''2' in b' :", '2' in b)
print("Print Result of ''x' in b' :", 'x' in b)

Output

The Value of 'a1' is : Python Programming
The Value of 'b1' is : {2: 'x', 6: 'y'}
Print Result of ''y' in a' : True
Print Result of ''Python' not in a' : True
Print Result of ''python' not in a' : True
Print Result of ''2' in b' : False
Print Result of ''x' in b' : False 

Comments

Popular posts from this blog

Lab Assignment (Programming and Problem Solving) SPPU BE First Year.

Examples of Flowchart and Pseudo Code

Unit 4