Professional Documents
Culture Documents
Features of Python
As a programming language, the features of Python brought to the table are many. Some of the
most significant features of Python are:
Easy to code
Python is a very developer-friendly language which means that anyone and everyone can learn to
code it in a couple of hours or days. As compared to other object-oriented programming languages
like Java, C, C++, and C#, Python is one of the easiest to learn.
High-Level Language
Python has been designed to be a high-level programming language, which means that when you
code in Python you don’t need to be aware of the coding structure, architecture as well as memory
management.
Integrated by Nature
Python is an integrated language by nature. This means that the python interpreter executes codes
one line at a time. Unlike other object-oriented programming languages, we don’t need to compile
Python code thus making the debugging process much easier and efficient. Another advantage of
this is, that upon execution the Python code is immediately converted into an intermediate form also
known as byte-code which makes it easier to execute and also saves runtime in the long run.
Highly Portable
Suppose you are running Python on Windows and you need to shift the same to either a Mac or a
Linux system, then you can easily achieve the same in Python without having to worry about
changing the code. This is not possible in other programming languages, thus making Python one of
the most portable languages available in the industry.
Highly Dynamic
As mentioned in an earlier paragraph, Python is one of the most dynamic languages available in the
industry today. What this basically means is that the type of a variable is decided at the run time and
not in advance. Due to the presence of this feature, we do not need to specify the type of the variable
during coding, thus saving time and increasing efficiency.
We cannot use a keyword as a variable name, function name or any other identifier. They are used
to define the syntax and structure of the Python language.
There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.
All the keywords except True, False and None are in lowercase and they must be written as they
are. The list of all the keywords is given below.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and
learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python
DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic
Level Course
# using + operator
# initialize tuples
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# using + operator
# printing result
Output :
The original tuple 1 : (1, 3, 5)
# using sum()
# initialize tuples
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# using sum()
# printing result
Output :
As you already know, Python gives you many built-in functions like print(), etc. but you can also
create your own functions. These functions are called user-defined functions.
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.
Syntax
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
print str
return
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.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme() function −
Live Demo
#!/usr/bin/python
print str
return;
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
mylist.append([1,2,3,4]);
return
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 −
There is one more example where argument is being passed by reference and the reference is being
overwritten inside the called function.
#!/usr/bin/python
return
mylist = [10,20,30];
changeme( mylist );
The parameter mylist is local to the function changeme. Changing mylist within the function does
not affect mylist. The function accomplishes nothing and finally this would produce the following
result −
Function Arguments
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
#!/usr/bin/python
print str
return;
printme()
printme();
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
print str
return;
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python
return;
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it prints
default age if it is not passed −
#!/usr/bin/python
return;
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
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.
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call. Following is a simple example −
Live Demo
#!/usr/bin/python
print arg1
return;
printinfo( 10 )
Output is:
10
Output is:
70
60
50
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 −
Live Demo
#!/usr/bin/python
Value of total : 30
Value of total : 40
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
−
#!/usr/bin/python
return total;
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
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
−
Live Demo
#!/usr/bin/python
return total;
sum( 10, 20 );
What is the basic difference between Python version 2 and Python version 3?
What is Python Used For?
Python is commonly used for developing websites and software, task automation, data analysis, and
data visualization. Since it’s relatively easy to learn, Python has been adopted by many non-
programmers such as accountants and scientists, for a variety of everyday tasks, like organizing
finances.
“Writing programs is a very creative and rewarding activity,” says University of Michigan and
Coursera instructor Charles R Severance in his book Python for Everybody. “You can write programs
for many reasons, ranging from making your living to solving a difficult data analysis problem to
having fun to helping someone else solve a problem.”
Python can build a wide range of different data visualizations, like line and bar graphs, pie charts,
histograms, and 3D plots. Python also has a number of libraries that enable coders to write programs
for data analysis and machine learning more quickly and efficiently, like TensorFlow and Keras.
Web development
Python is often used to develop the back end of a website or application—the parts that a user
doesn’t see. Python’s role in web development can include sending data to and from servers,
processing data and communicating with databases, URL routing, and ensuring security. Python
offers several frameworks for web development. Commonly used ones include Django and Flask.
Some web development jobs that use Python include back end engineers, full stack engineers,
Python developers, software engineers, and DevOps engineers.
Start building and deploying web applications with the Django for Everybody Specialization from the
University of Michigan on Coursera.
Automation or scripting
If you find yourself performing a task over and over again, you could work more efficiently by
automating it with Python. Writing code used to build these automated processes is called scripting.
In the coding world, automation can be used to check for errors across multiple files, convert files,
execute simple math, and remove duplicates in data.
Python can even be used by relative beginners to automate simple tasks on the computer—such as
renaming files, finding and downloading online content or sending emails or texts at desired
intervals.
Everyday tasks
Python isn't only for programmers and data scientists. Learning Python can open new possibilities for
those in less data-heavy professions, like journalists, small business owners, or social media
marketers. Python can also enable non-programmer to simplify certain tasks in their lives. Here are
just a few of the tasks you could automate with Python:
Let’s look at an example that uses the break statement in a for loop:
number = 0
number = number + 1
if number == 5:
print('Out of loop')
In this small program, the variable number is initialized at 0. Then a for statement constructs the
loop as long as the variable number is less than 10.
Within the for loop, the number increases incrementally by 1 with each pass because of the
line number = number + 1.
Then, there is an if statement that presents the condition that if the variable number is equivalent
to the integer 5, then the loop will break.
Within the loop is also a print() statement that will execute with each iteration of the for loop until
the loop breaks, since it is after the break statement.
To see when we are out of the loop, we have included a final print() statement outside of
the for loop.
Number is 1
Number is 2
Number is 3
Number is 4
Out of loop
This shows that once the integer number is evaluated as equivalent to 5, the loop breaks, as the
program is told to do so with the break statement.
The continue statement will be within the block of code under the loop statement, usually after a
conditional if statement.
Using the same for loop program as in the Break Statement section above, we’ll use
a continue statement rather than a break statement:
number = 0
number = number + 1
if number == 5:
print('Out of loop')
The difference in using the continue statement rather than a break statement is that our code will
continue despite the disruption when the variable number is evaluated as equivalent to 5. Let’s look
at our output:
Output
Number is 1
Number is 2
Number is 3
Number is 4
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop
Here we see that the line Number is 5 never occurs in the output, but the loop continues after that
point to print lines for the numbers 6-10 before leaving the loop.
You can use the continue statement to avoid deeply nested conditional code, or to optimize a loop by
eliminating frequently occurring cases that you would like to reject.
The continue statement causes a program to skip certain factors that come up within a loop, but
then continue through the rest of the loop.
As with the other statements, the pass statement will be within the block of code under the loop
statement, typically after a conditional if statement.
Using the same code block as above, let’s replace the break or continue statement with
a pass statement:
number = 0
for number in range(10):
number = number + 1
if number == 5:
print('Out of loop')
The pass statement occurring after the if conditional statement is telling the program to continue to
run the loop and ignore the fact that the variable number evaluates as equivalent to 5 during one of
its iterations.
Output
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop
By using the pass statement in this program, we notice that the program runs exactly as it would if
there were no conditional statement in the program. The pass statement tells the program to
disregard that condition and continue to run the program as usual.
The pass statement can create minimal classes, or act as a placeholder when working on new code
and thinking on an algorithmic level before hammering out details.