Introduction of Python

Python is an open-source programming language that is popular for general software development and scripting, web development and data science. Since Python is a general-purpose language, the base language does not include many of the data structures and functions necessary for data analysis. Python does, however, have an extensive selection of addon packages that give it great flexibility and a robust library of data-oriented addons make it one of the most popular languages for data science.

Installation.

We are using a JupyterNotebook. This is a best compiler for beginners and easy to use.

Installing Jupyter
Get up and running on your computer

This page uses instructions with pipthe recommended installation tool for Python. If you require environment management as opposed to just installation.

JupyterLab

Install Jupyter Lab with pip:

				
					pip install jupyterlab
				
			

Note: If you install Jupyter Lab with conda or mamba, we recommend using the conda-forge channel.

Once installed, launch JupyterLab with:

				
					jupyterlab
				
			

Jupyter Notebook

Install the classic jupyter notebook with :

				
					pip install notebook
				
			

To run the notebook:

				
					jupyter notebook
				
			

Install Python Package.

To install a custom python package, you should check the instructions from the documentation website. Often packages that does not come from repository will involve more complicated install procedures Most packages would be easy as one command line, which involves the pip executable. A sample command would be.

				
					pip install numpy
				
			

If you have a Windows 10 (or above), keep in mind that Anaconda has its separate command prompt. So, make sure you use the above command in the Anaconda Prompt.

Printing to the Console in Python.

Print () function

				
					print ("Hello World!")
				
			

Output:

				
					Run Output:Hello World !
				
			

Note: “ “ for String (Means its shows the beginning & End of text “HELLO WORLD”

& if you forgot to add “ “ then its show Error

For Example:

print (” Hello World!) >>>>>RUN

File “main.py”, lines

print (”Hello World!);/ 0.

Syntax Error: EOL while scanning string literal.

				
					File"main.py",line 1
print (Hello World!)
SyntaxError:EOL while scanning string literal
				
			

Python Functions

Now you’ll learn about functions, what a function is, the syntax, components, and types of functions. Also, you’ll learn to create a function in Python.

What is a function in Python?

In Python, a function is a block of organized, reusable (DRY- Don’t Repeat Yourself) code with a name that is used to perform a single, specific task. It can take arguments and returns the value.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Types of Functions.

				
					import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
x, y, z = np.random.rand(3, 100) * 10
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
plt.show()

				
			

Python support two types of functions

       1.Built-in function.

      2.User-defined function.

  1. Built-in function.

The functions which are come along with Python itself are called a built-in function or predefined function. Some of them are: 

 

  1. range ( );
  2. input ( );
  3. type ( );
  4. id ( );
  5. eval ( );

Range Function in Python.

Example: range( ) Function generates the immutable sequence of numbers starting from the given start integer to the stop integer.

				
					>>> for i in range(1,10):
>>>   print (i,end=' ')
				
			

                                  Output:

				
					1 2 3 4 5 6 7 8 9
				
			

Input Function in Python

Example: Input( ) The python input Function is used to derive input from the user. The function reads the line of input, and converts the input into a String, and returns the output.

				
					name=input("Enter your name")
				
			

Run Output : “Enter your name”  MasterTech.

				
					Print('Hello',name)
				
			

Run Output :  Hello MasterTech.

Type Function in Python

Example: type( ) is a built-in function that returns the type of the objects/data elements stored in any data type or returns a new type object depending on the arguments passed to the function.

 

The syntax is as follows –

				
					type(object)
type(name,bases,dict)
				
			

where,

name = name of the class, which becomes ___name___ attribute

bases = tuple from which current class is derived, becomes ___bases___ attribute

dict = a dictionary which specifies the namespaces for the class, later becomes ___dict___ attribute

The first method accepts a single parameter in the function. While the second method accepts 3 parameters in it.

If you pass a single argument to the type(object) function, it will return the type of the object. When you pass 3 arguments to the type(name, bases, dict) function, it creates a class dynamically and returns a new type object

Python type() with Single Parameter

We have already seen the syntax for passing a single argument to the type() function. Let us look at a few examples to understand this type() form.

				
					a=10
b=10.5
c=True
d=1+5j
print(type(a))
print(type(b))
print(type(c))
print(type(d))
				
			

Output:

				
					<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>
				
			

Python Type() with 3 Parameters

This form of type() function returns a new type object. The 3 arguments passed to the function are name, bases, and dict. Let us understand by looking at an example.

Example –

				
					# New class (has no base) class with the
#dynamic class initialization of type ()
new=type('New ,(object,),
       dict(varl='GeeksforGeeks',b=2009))
       
# Print type() which returns class'type'

print(type(new))
print(vars(new))

#Base class ,incorporated
#in our new class
class test:
   a="Geekesforgeeks"
   b=2009
     
     #Dynamically initialize Newer class
     #It will derive from the base class test newer=type('Newer',(test,),
      dict(a='Geeks',b=2018))
      
print(type(newer))
print(vars(newer))


				
			

output:

				
					<class 'type'>
{'var1':'GeeksforGeeks''b':2009,'--module--':'--main--','--dict--':<attribute'--dict--'of'New'objects>,'--weakref--'<attribute'--weakref--'of'New'objects>,'--doc--':None}
<class'type'>
    {'a':'Geeks;'b':2018,'--module--':'--main--;'--doc--':None}
</class></attribute></attribute>
				
			

Id Function in Python

Example: id( ) Function accepts a single parameter and returns a unique identity (integer value) of that object.

Syntax –

				
					id(object)
				
			

where,

object = int, float, string, tuple, list, class, function, etc.

Note – The Python id() function only takes a single parameter object.

How Id () Works?

Python can utilize an object’s id to cache the values of its variables. This approach for accessing cached items via id() improves Python performance. As a result, many variables may refer to the same object and have the same id() value if their values are the same.

Basic Example-

				
					#Python program to illustrate id()function
a=10
b=11
c=130.56
text='Hello'

print('ID of a =',id(a))
print('id of b =',id(b))
print('ID of c =',id(text))
				
			

Output –

				
					ID of a =9781088
ID of b =9781120
ID of c =139832028993808
ID of text =139894857394352
				
			

Evaluate Function in Python

Example: Python eval( ) is a built-in function that allows us to evaluate the Python expression as a ‘string’ and return the value as an integer. Programmers can use the Python eval() function to dynamically evaluate expressions passed as a string argument to the built-in function. When a string is passed to Python eval(), it is parsed, compiled to bytecode, and then evaluated as a Python expression. The Python eval() function is typically employed in situations or applications that require the evaluation of mathematical expressions.

Syntax

The syntax of the eval function is as shown below:

				
					 eval(expression,[globals[,locals]])
				
			

Python eval () Parameters

  • The eval() function accepts 3 values as its parameters. This Python built-in function accepts its first input named expression, which contains the expression to be evaluated. Python eval() then accepts two additional optional parameters.
  • expression= input parsed as a string and evaluated as a Python expression
  • globals(optional) = must be represented as a dictionary to specify available global variables and methods
  • locals(optional) = mapped object to specify available local variables and methods
  • Note– The current global and local namespaces are utilized if both global and locals parameters are missing

Return Value From eval()

The eval() method returns the result of the expression’s evaluation. In most cases, the return type will be an integer.

Example 1:-

				
					#python program to illustrate eval()function
print(eval('10== 10'))
print(eval('2 ** 2'))
Print(eval("'pyt' + hon'"))
print(eval("'He' *5"))
x = 10 + 59 -23 * 5
print('value of x is:', eval('x'))
print('sum of list is:',eval('sum([2,4,6,8])'))


				
			

Output :-

				
					True
4
python
HeHeHeHeHe
Value of x is: -46
Sum of list is: 20
				
			

Example 2:-

				
					 return 4*l

# Area of Square
def calcArea(l):
    return l*l

print('Two functions declared are:')
print('1. calcPerimeter(l)')
print('2. calcArea(l)')
fnc = input('Type a function: ')

for l in range(1, 6):
    if (fnc == 'calcPerimeter(l)'):
        print('If length is:', l, ', Perimeter of Square = ', eval(fnc))
    elif (fnc == 'calcArea(l)'):
        print('If length is: ', l, ', Area of Square = ', eval(fnc))
    else:
        print('Wrong Function')
        break

				
			

Output:-

				
					two functions declared are:
calcperimeter(1)
calcarea(1)
type a function :calcperimeter(1)
if length is : 1 , perimeter of square = 4
if length is : 2 , perimeter of square = 8
if length is : 3 , perimeter of square = 12
if length is : 4 , perimeter of square = 16
if length is : 5 , perimeter of square = 20
				
			

Warnings when using eval()

Let us assume we have imported an ‘os’ module while working on a Unix system such as MacOS, Linux, etc. Now, this ‘os’ module provides a flexible way to exploit operating system features such as reading and writing files. If you allow users to enter a value using eval(input()), the user can use the command: os.system(‘rm -rf *’) to modify, alter or even remove all files of the OS. Furthermore, you should never directly send an untrusted source to eval(). Because it is quite simple for a rogue user to cause havoc to the system.

One solution to avoid this problem is to use the dir() method. You may view all of the variables and methods that are available. It’s a good idea to double-check the variables and methods that the user has access to.

				
					from math import *
print(eval(‘dir()’))

				
			

Output:-

				
					['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', 
'__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 
'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 
'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 
'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 
'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

				
			

Restricting the use of Available Methods and Variables in eval()

Another solution is to limit eval() to only the functions and variables that we want to use and expose. This is when global and local parameters come into play. Limiting the use of eval() by passing globals and locals dictionaries makes the code more secure, especially when providing user input to the eval() method.

1.  When both the globals and the locals parameters are ignored

As we have discussed in the above example, the expression is executed in the current scope.

				
					print(eval(‘dir()’))
				
			

2.   Passing globals parameter & locals parameter omitted

In this case, if the locals dictionary parameter is not specified, then it automatically defaults to the globals dictionary. It means the global variables and methods will be used for both the globals and locals variables.

Note – In Python, you may check the current global and local dictionaries using the built-in functions globals() and locals().

				
					from math import *
def square_root(n):
   return sqrt(n)

print(globals())

				
			

Output:-

				
					{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 
'acos': , 'acosh': , 'asin': , 'asinh': , 'atan': , 'atan2': , 'atanh': , 
'ceil': , 'copysign': , 'cos': , 'cosh': , 'degrees': , 'dist': , 'erf': , 
'erfc': , 'exp': , 'expm1': , 'fabs': , 'factorial': , 'floor': , 'fmod': , 
'frexp': , 'fsum': , 'gamma': , 'gcd': , 'hypot': , 'isclose': , 'isfinite': , 
'isinf': , 'isnan': , 'isqrt': , 'ldexp': , 'lgamma': , 'log': , 'log1p': , 
'log10': , 'log2': , 'modf': , 'pow': , 'radians': , 'remainder': , 'sin': , 
'sinh': , 'sqrt': , 'tan': , 'tanh': , 'trunc': , 'prod': , 'perm': , 'comb': ,
'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 

				
			

3.   Passing empty dictionary as a globals parameter

Let’s explore what happens if we pass the globals value as an empty dictionary to the eval() function.

Example:-

				
					from math import *
print(eval('dir()', {}))
print(‘’)

# This will raise an exception
print(eval('sqrt(36)', {}))

				
			

Output:-

				
					['__builtins__']

Traceback (most recent call last):
File "", line 5, in 
print(eval('sqrt(36)', {}))
File "", line 1, in 
NameError: name 'sqrt' is not defined

				
			

Explanation:-

In the first print statement, we have passed an empty dictionary as globals parameter. This will only return __builtins__ that denotes only this module will be available for the ‘expression’.

Even though we have imported the math module, you may notice that the ‘expression’ parameter cannot access the sqrt function of the math module, because the globals argument value assigned is an empty dictionary.