0_python report 2[1]
0_python report 2[1]
PYTHON
1.1INTRODUCTION
Python has a reputation as a beginner-friendly language, replacing Java as the most widely used
introductory language because it handles much of the complexity for the user, allowing
beginners to focus on fully grasping programming concepts rather than minute details.
Python is used for server-side web development, software development, mathematics, and
system scripting, and is popular for Rapid Application Development and as a scripting or glue
language to tie existing components because of its high-level, built-in data structures, dynamic
typing, and dynamic binding. Program maintenance costs are reduced with Python due to the
easily learned syntax and emphasis on readability. Additionally, Python's support of modules
and packages facilitates modular programs and reuse of code. Python is an open source .
1.2 Python Use Cases
Creating web applications on a server
Building workflows that can be used in conjunction with software
Connecting to database systems
Reading and modifying files
Performing complex mathematics
Processing big data
Fast prototyping
Developing production-ready software
Professionally, Python is great for backend web development, data analysis, artificial
intelligence, and scientific computing. Developers also use Python to build productivity tools,
games, and desktop apps.
1.3 Features and Benefits of Python
Compatible with a variety of platforms including Windows, Mac, Linux,
Raspberry Pi, and others
Uses a simple syntax comparable to the English language that lets developers use
fewer lines than other programming languages
Operates on an interpreter system that allows code to be executed immediately,
fast-tracking prototyping
Can be handled in a procedural, object-orientated, or functional way
1
1.4 Python Syntax
Somewhat similar to the English language, with a mathematical influence, Python is
built for readability
Unlike other languages that use semicolons and/or parentheses to complete a
command, Python uses new lines for the same function
Defines scope (i.e., loops, functions, classes) by relying indentation, using whitespace,
rather than braces (aka curly brackets).
PythonFlexibility
Python, a dynamically typed language, is especially flexible, eliminating hard rules for building
features and offering more problem-solving flexibility with a variety of methods. It also allows
uses to compile and run programs right up to a problematic area because it uses run-time type
depending on context because Python is a dynamically typed language. And, maintaining a
Python app as it grows in size and complexity can be increasingly difficult, especially finding
and fixing errors. Users will need experience to design code or write unit tests that make
maintenance.
Python/AI
AI researchers are fans of Python. Google TensorFlow, as well as other libraries (scikit-
learn, Keras), establish a foundation for AI development because of the usability and flexibility
it offers Python users. These libraries, and their availability, are critical because they enable .
The Python Package Index (PyPI) is a repository of software for the Python programming
language. PyPI helps users find and install software developed and shared by the Python
community.
2
CHAPTER : 2
USING VARIABLE IN PYTHON
Variables are named locations that are used to store references to the object stored in
memory. When we create variables in Python, we must consider the following rules:
A variable name must start with a letter or underscore
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
Variable names are case-sensitive (date, Date and DATE are three different
variables)
Variables can be of any length
Variable names cannot be Python keywords.
2.1 Python Keywords
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
pass else import assert
break except in raise
Assigning values to variables
We use the assignment operator = to assign value to a variable.
Example valid and invalid variable names and assignments:
#Legal variable names:
name = "John"
error_404 = 404
_status_200 = "OK"
mySurname = "Doe"
SURNAME = "Doe"
surname2 = "Doe"
3
200_OK = 200
error-500 = "Server Error"
my var = "John"
$myname = "John"
Multiple Assignments
In Python, we can assign values to multiple variables in one line:
Example:
ok, redirect, server_error = 200, 300, 500
print(ok)
print(redirect)
print(server_error)
Output:
200
300
500
We can also assign the same value to multiple variables:
err_500 = err_501 = err_502 = "server_error"
print(err_500)
print(err_501)
print(err_502)
Global Variables
Variables that are defined outside of a function are known as global variables.
Global variables can be used both inside and outside of functions.
status_ok = 200
def status_code():
print("Status code is ", status_ok)
status_code()
If you create a variable with the same name inside a function, then the variable will be
local to the function. The global variable will keep its value as when it was declared.
Example:
status = 200
def status_code():
4
status = 401
print("Status code is ", status)
status_code()
print("Status code is ", status)
Output:
Status code is 401 // first print statement
Status code is 200 // second print statement
If you require to change the global variable’s value inside of a function, you have to
use the global keyword.
For example:
status = 200
def status_code():
global status
status = 401
print("Status code is ", status)
status_code()
print("Status code is ", status)
Output
Status code is 401 // first print statement
Status code is 401 // second print statement
2.2 STRING AND NUMBER MANIPULATION
A python string is a list of characters in order. A character is anything you can type on
the keyboard in one keystroke,
like a letter, a number, or a backslash. Python strings are immutable. In Python, the
string is declared using either single or double quotes, which it defines as a sequence
slicing, parsing, analyzing, etc. In many different programming languages, including
Python, provides string data type to work with such string manipulating, which uses
different functions of the string provided by string data type “str” in Python. In
Python, the string data type is used for representing textual data, where it is used in
every application that involves strings. In this article, we will discuss various
functions of the string used in string manipulation. In this topic, we are going to learn
about Python string manipulation.
5
CHAPTER : 3
PYTHON FUNCTION
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.
Defining a function: You can define functions to provide the required functionality.
Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
3.1 CALLING A FUNCTION
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result −
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
6
All parameters (arguments) in the Python language are passed by reference. It means
if you change what a parameter refers to within a function, the change also reflects
back in the calling function. For example −
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
rretur
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
3.2 FUNCTION ARGUMENT
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
7
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
When the above code is executed, it produces the following result −
Trackback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
8
#!/usr/bin/python
9
Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all non
keyword variable arguments. This tuple remains empty if no additional arguments are
specified during the function call. Following is a simple example −
#!/usr/bin/ppytho
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
The Anonymous Functions
10
These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
Lambda forms can take any number of arguments but return just one value in
the form of an expression. They cannot contain commands or multiple
expressions.
An anonymous function cannot be a direct call to print because lambda
requires an expression
Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is by passing
function stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows
−
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
The return Statement
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
All the above examples are not returning any value. You can return a value from a
function as follows −
11
#!/usr/bin/python
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought
into scope. Following is a simple example −
#!/usr/bin/python
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
12
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
3.3 RETURN STATEMENT
The return statement in python is an extremely useful statement used to return the
flow of program from the function to the function caller. The keyword return is used
to write the return statement.
Since everything in python is an object the return value can be any object such as –
numeric (int, float, double) or collections (list, tuple, dictionary) or user defined
functions and classes or packages.
The return statement has the following features -
Return statement cannot be used outside the function.
Any code written after return statement is called dead code as it will never
be executed.
Return statement can pass any value implicitly or explicitly, if no value is
given then None is returned.
Functions are core of any programming language as they allow for code
modularity thereby reducing program complexity. Functions can display
the result within itself, but it makes the program complex, hence it is best
to pass the result from all the functions to a common place.
It is in this scenario that the return statement is useful as it terminates the
currently executing function and passes control of the program to the
statement that invoked the function.
Use of return statement in Python
Functions are core of any programming language as they allow for code modularity
thereby reducing program complexity. Functions can display the result within itself,
but it makes the program complex, hence it is best to pass the result from all the
13
functions to a common place It is in this scenario that the return statement is useful as
it terminates the currently executing function and passes control of the program to the
statement that invoked the function.
Returning a function using return statement
In python, functions are first class objects which means that they can be stored in a
variable or can be passed as an argument to another function. Since functions are
objects, return statement can be used to return a function as a value from another
function. Functions that return a function or take a function as an argument are called
higher-order functions.
Example
In this example, finding_sum function contains another function – add inside it. The
finding_sum function is called first and receives the first number as the parameter. The add
function receives the second number as parameter and returns the sum of the two numbers to
finding_sum function. The finding_sum function then returns the add function as a value to
sum variable.
Returning None using return statement
Functions in python always return a value, even if the return statement is not written
explicitly. Hence, python does not have procedures, which in other programming
languages are functions without a return statement. If a return statement does not
return a result or is omitted from a function, then python will implicitly return default
value of None. Explicit calling of return None should only be considered if the
program contains multiple return statement to let other programmers know the
termination point of the function.
Example
The program below gives a perfect illustration of using return None. In this program
the check_prime() function is used to check if a list contains any prime numbers. If
the list contains prime numbers, then all the prime numbers present in the list are
printed. However, if there are no prime numbers in the list then None is returned,
since this program contains multiple return statements, hence None is called
explicitly.
Returning multiple values using return statement
The return statement in python can also be used to return multiple values from a
single function using a ‘,’ to separate the values. This feature can be especially useful
when multiple calculations need to be performed on the same dataset without
14
changing the original dataset. The result from the return statement is a tuple of the
values.
Example
In this example the built-in functions of the statistics library are used to compute the
mean, median and mode which are returned using a single return statement showing
how multiple values can be returned from a function.
Syntax of return() in Python:
def func_name():
statements....
return [expression]
If the return() statement is without any expression, then the NONE value is returned.
3.4 IF STATEMENT
There comes situations in real life when we need to make some decisions and based
on these decisions, we decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these
decisions we will execute the next block of code. Decision-making statements in
programming languages decide the direction of the flow of program execution.
In Python, if-else elif statement is used for decision making.
if statement
if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
Syntax: if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
15
# will consider only statement1 to be inside
# its block.
Flowchart of Python if statement
3.5 LOOPS AND CONTROL STATEMENTS IN PYTHON
Python programming language provides following types of loops to handle looping
requirements.
3.5.1 While Loop
Syntax :
while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces after a
programming construct are
considered to be part of a single block of code. Python uses indentation as its method
of grouping statements
3.5.2 For in Loop
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop
which is similar to for each
loop in other languages.
Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over iterators and a range.
3.5.3 Nested Loops
Python programming language allows to use one loop inside another loop. Following
section shows few examples to
illustrate the concept.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as
16
follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other
type of loop. For example a for
loop can be inside a while loop or vice versa.
3.5.4 Loop Control Statements
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
3.5.4.1 Continue Statement
It returns the control to the beginning of the loop.
3.5.4.2 Break Statement
It brings control out of the loop
3.5.4.3 Pass Statement
We use pass statement to write empty loops. Pass is also used for empty control
statement, function and classes.
17
CHAPTER : 4
PROJECT SCREENSHOTS
18
Figure: 4.1
19
Figure: 4.2
20
FUTURE SCOPE
Why Python Programming Language Has Bright Future?
Python has been voted as most favorite programming language beating C, C++ and
java programming. Python programming is open source programming language and
used to develop almost every kind of application. Python is being used worldwide as a
wide range of application development and system development programming
language. Big brands and search engine giants are using python programming to make
their task easier. Google, Yahoo, Quora, Facebook are using python programming to
solve their complex programming problems. Python programming is versatile, robust
and comprehensive. Python is high-level programming language and easy to learn as
well as it reduces the coding effort compare to other programming languages. Python
programming is used to write test scripts and tests mobile devices performance. It is
one of the most versatile languages these days. Python programmers are most
demandable in the IT industry these days and get paid more compared to another
language programmer
21
CONCLUSION
Programming language can be a key in your hand for your perfect dream job in the
software industry. In today’s market, Python has been declared as the most used
and most demanding programming language of all. As the language is getting
dominant in all major fields: Ranging from software development to machine learning
and data analytics, Python has been declared as the language of the year 2018. Hence
It currently occupies 37 percent of Programming language market.
22
REFERENCES
[1] https://www.python.org/doc/essays/blurb/
[2] https://pythonprogramming.net/c
[3] ://www.smartherd.com/python-for-beginners-conclusion-and-resources/
23