You are on page 1of 20

PYTHON ASSIGNMENT

What are the key features of Python?


Python is an object-oriented programming language that is designed in  C. By nature, it is a high-level
programming language that allows for the creation of both simple as well as complex operations.
Along with this Python comes inbuilt with a wide array of modules as well as libraries which allows it
to support many different programming languages like  Java, C,  C++, and JSON.

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.

Open Source and Free


Python is an open-source programming language which means that anyone can create and
contribute to its development. Python has an online forum where thousands of coders gather daily to
improve this language further. Along with this  Python  is free to download and use in any operating
system, be it Windows, Mac or Linux.

Support for GUI


GUI or Graphical User Interface is one of the key aspects of any programming language because it
has the ability to add flair to code and make the results more visual. Python has support for a wide
array of GUIs which can easily be imported to the interpreter, thus making this one of the most
favorite languages for developers.
Object-Oriented Approach
One of the key aspects of Python is its  object-oriented approach. This basically means that Python
recognizes the concept of class and object encapsulation thus allowing programs to be efficient in
the long run.

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.

Extensive Array of Library


Out of the box, Python comes inbuilt with a large number of  libraries  that can be imported at any
instance and be used in a specific program. The presence of libraries also makes sure that you don’t
need to write all the code yourself and can import the same from those that already exist in the
libraries.

What are Keywords in Python?


Python Keywords
Keywords are the reserved words in Python.

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.

In Python, keywords are case sensitive.

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.

False Await else import pass

None Break except in raise

True Class finally is return

And Continue for lambda try

As Def from nonlocal while

assert Del global not with

Async Elif if or yield

What are Literals in Python and explain about different Literals?


A  literal  is a succinct and easily visible way to write a value. Literals represent the possible choices
in  primitive types  for that language. Some of the choices of  types  of literals are often integers,
floating point, Booleans and character strings.  Python  support the following literals:

String literals     ::    "halo" , '12345'

Int literals     ::    0,1,2,-1,-2

Long literals     ::    89675L

Float literals     ::    3.14

Complex literals     ::    12j

Boolean literals     ::    True or False

Special literals     ::    None

Unicode literals     ::    u"hello"

List literals     ::    [], [5,6,7]

Tuple literals     ::    (), (9,),(8,9,0)

Dict literals     ::    {}, {'x':1}


Set literals     ::    {8,9,10}

How can you concatenate two tuples?


Method #1 : Using  + operator
This is the most Pythonic and recommended method to perform this particular task. In this, we add
two tuples and return the concatenated tuple. No previous tuple is changed in this process.

  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

# Python3 code to demonstrate working of

# Ways to concatenate tuples

# using + operator

  

# initialize tuples

test_tup1 = (1, 3, 5)

test_tup2 = (4, 6)

  

# printing original tuples

print("The original tuple 1 : " + str(test_tup1))

print("The original tuple 2 : " + str(test_tup2))

  

# Ways to concatenate tuples

# using + operator

res = test_tup1 + test_tup2

  

# printing result

print("The tuple after concatenation is : " + str(res))

Output :
The original tuple 1 : (1, 3, 5)

The original tuple 2 : (4, 6)

The tuple after concatenation is : (1, 3, 5, 4, 6)

Method #2 : Using  sum()


This is yet another way in which this task can be performed. In this, we add the tuples to one other
using sum function.

# Python3 code to demonstrate working of

# Ways to concatenate tuples

# using sum()

  

# initialize tuples

test_tup1 = (1, 3, 5)

test_tup2 = (4, 6)

  

# printing original tuples

print("The original tuple 1 : " + str(test_tup1))

print("The original tuple 2 : " + str(test_tup2))

  

# Ways to concatenate tuples

# using sum()

res = sum((test_tup1, test_tup2), ())

  

# printing result

print("The tuple after concatenation is : " + str(res))

Output :

The original tuple 1 : (1, 3, 5)

The original tuple 2 : (4, 6)

The tuple after concatenation is : (1, 3, 5, 4, 6)


What are functions in Python?
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.

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

def functionname( parameters ):

"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.

def printme( str ):

"This prints a passed string into this function"

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

# 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

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

return

# 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.

#!/usr/bin/python

# Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

mylist = [1,2,3,4]; # This would assig new reference in mylist

print "Values inside the function: ", mylist

return

# Now you can call changeme function

mylist = [10,20,30];

changeme( mylist );

print "Values outside the function: ", 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 −

Values inside the function: [1, 2, 3, 4]

Values outside the function: [10, 20, 30]

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

# 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 −

Traceback (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.

#!/usr/bin/python

# Function definition is here

def printinfo( name, age ):

"This prints a passed info into this function"

print "Name: ", name

print "Age ", age

return;

# Now you can call printinfo function

printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

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

# Function definition is here

def printinfo( name, age = 35 ):

"This prints a passed info into this function"

print "Name: ", name


print "Age ", age

return;

# Now you can call printinfo function

printinfo( age=50, name="miki" )

printinfo( name="miki" )

When the above code is executed, it produces the following result −

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.

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 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

# 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

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 −

Live Demo

#!/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

#!/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

Live Demo

#!/usr/bin/python

total = 0; # This is global variable.

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

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

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.”

Here’s a closer look at some of the common ways Python is used.

Data analysis and machine learning


Python has become a staple in data science, allowing  data analysts  and other professionals to use
the language to conduct complex statistical calculations, create data visualizations, build machine
learning algorithms, manipulate and analyze data, and complete other data-related tasks.

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.

Learn Python for data analysis


Start building the job-ready skills you’ll need as a data analyst, including Python, SQL, and Excel, with
the  IBM Data Analyst Professional Certificate  on Coursera. You can finish in less than six months with
a credential from an industry leader.

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.

Learn Python for development

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.

Learn Python for automation


Boost your Python automation credentials with the  Google IT Automation with Python Professional
Certificate.

Software testing and prototyping


In software development, Python can aid in tasks like build control, bug tracking, and testing. With
Python, software developers can automate testing for new products or features. Some Python tools
used for software testing include Green and Requestium.

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:

Keep track of stock market or crypto prices


Send yourself a text reminder to carry an umbrella anytime it’s raining

Update your grocery shopping list

Renaming large batches of files


Converting text files to spreadsheets

Randomly assign chores to family members

Fill out online forms automatically

What is the purpose break statement in python?


Break Statement
In Python, the  break  statement provides you with the opportunity to exit out of a loop when an
external condition is triggered. You’ll put the  break  statement within the block of code under your
loop statement, usually after a  conditional  if  statement.

Let’s look at an example that uses the  break  statement in a  for  loop:

number = 0

for number in range(10):

number = number + 1

if number == 5:

break # break here

print('Number is ' + str(number))

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.

When we run this code, our output will be the following:


Output

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  break  statement causes a program to break out of a loop.

What is the purpose continue statement in python?


Continue Statement
The  continue  statement gives you the option to skip over the part of a loop where an external
condition is triggered, but to go on to complete the rest of the loop. That is, the current iteration of
the loop will be disrupted, but the program will return to the top of the loop.

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

for number in range(10):

number = number + 1

if number == 5:

continue # continue here

print('Number is ' + str(number))

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.

What is the purpose pass statement in python?


Pass Statement
When an external condition is triggered, the  pass  statement allows you to handle the condition
without the loop being impacted in any way; all of the code will continue to be read unless
a  break  or other statement occurs.

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:

pass # pass here

print('Number is ' + str(number))

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.

We’ll run the program and take a look at the output:

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.

You might also like