scope in python
scope in python
The concept of scope rules how variables and names are looked up
in your code. It determines the visibility of a variable within the
code. The scope of a name or variable depends on the place in your
code where you create that variable. The Python scope concept is
generally presented using a rule known as the LEGB rule.
1. Global scope: The names that you define in this scope are
available to all your code.
2. Local scope: The names that you define in this scope are only
available or visible to the code within the scope.
he names in your programs will have the scope of the block of code
in which you define them. When you can access the value of a given
name from someplace in your code, you’ll say that the name is in
scope. If you can’t access the name, then you’ll say that the name
is out of scope.
Example :
Local Scope
def myfunc():
x = 300
print(x)
myfunc()
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming. This article
is aimed at providing information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion
Type Conversion in Python
The act of changing an object’s data type is known as type conversion. The
Python interpreter automatically performs Implicit Type Conversion. Python
prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit
type conversion, sometimes referred to as type casting. When type casting,
data loss could happen if the object is forced to conform to a particular data
type.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
To get a more clear view of the topic see the below examples
Example
As we can see the data type of ‘z’ got automatically changed to the “float” type
while one variable x is of integer type while the other variable y is of float type.
The reason for the float value not being converted into an integer instead is due
to type promotion that allows performing operations by converting data into a
wider-sized data type without any loss of information. This is a simple case of
Implicit type conversion in Python.
Python3
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z =x +y
print(z)
print("z is of type:",type(z))
# initializing string
s = "10010"
print (e)
Type Coercion
There are occasions when we would like to convert a variable from one data type to
another. This is referred to as type coercion. We can coerce a variable to another date
type by passing it to a function whose name is identical to the desired data type. For
instance, if we want to convert a variable x to an integer, we would use the
command int(x). If we want to convert a variable y to a float, we would wuse float(y).
We will study coercion more later, but for now, let’s see what happens when we coerce ints
to floats and vice-versa.
x_int = 19
x_float = float(x_int)
print(x_float)
print(type(x_float))
19.0
<class 'float'>
y_float = 6.8
y_int = int(y_float)
print(y_int)
print(type(y_int))
6
<class 'int'>
Notice that we we coerce a float to an int, the Python does not round the float to the
nearest integer. Instead, it truncates (or chops off) the decimal portion of the number. In
other words, when performing float-to-int coercion, Python will ALWAYS round the number
DOWN to the next lowest integer, regardless of the value of the decimal portion.
>>> x.__add__(y)
NotImplemented
In this case Python got NotImplemented back because integers don't know how
to add themselves to floating-point numbers. This
special NotImplemented value was returned by the__add__ method of the
integer object to let Python know that x (an int) doesn't know how to support
the + operator with y (a float).
>>> y.__radd__(x)
5.5
This adds the floating-point number to the integer from the right-hand side of
the plus sign (r is for "right" in __radd__) and returns 5.5.
So no type coercion was done here, instead, one of these types of objects
knows how to operate with the other type of object when used with
the plus operator.
What happens if we try to use the + operator between a string and a number
in Python?
The reason is that strings in Python don't know how to use the plus operator
with numbers and numbers in Python don't know how to use the plus
operator with strings, which means our code doesn't work.
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output:
HELLO
HELLO
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
Python Lambda
Python Lambda Functions are anonymous functions means that the function
is without a name. As we already know the def keyword is used to define a
normal function in Python. Similarly, the lambda keyword is used to define an
anonymous function in Python.
Python Lambda Function Syntax
Syntax: lambda arguments : expression
This function can have any number of arguments but only one expression,
which is evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically
restricted to a single expression.
It has various uses in particular fields of programming, besides other types
of expressions in functions.
Output:
Int formatting: 1.000000e+06
float formatting: 999,999.79
Difference Between Lambda functions and def defined function
The code defines a cube function using both the ‘def' keyword and a lambda
function. It calculates the cube of a given number (5 in this case) using both
approaches and prints the results. The output is 125 for both the ‘def' and
lambda functions, demonstrating that they achieve the same cube calculation.
Python3
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print("Using function defined with `def` keyword, cube:", cube(5))
print("Using lambda function, cube:", lambda_cube(5))
Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125
Good for performing short Good for any cases that require
operations/data manipulations. multiple lines of code.
print(uppered_animals)
Output:
['DOG', 'CAT', 'PARROT', 'RABBIT']
Python Modules
Python Module is a file that contains built-in functions, classes,its and
variables. There are many Python modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create
our own simple module, Import Python modules, From statements in Python,
we can use the alias to rename the module, etc.
What is Python Module
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
runnable code.
Grouping related code into a module makes the code easier to understand and
use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file
with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
Python3
return (x+y)
return (x-y)
# module math
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all the names
from a module to a current namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly what
you will be needing from the module, it is not recommended to use *, else do
so.
Python3
# importing sqrt() and factorial from the
# module math
from math import *
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Python3
# importing sqrt() and factorial from the
# module math
import math as mt
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))
Output
4.0
720
import sys
sys.stdout.write('Geeks')
Output
Geeks
stderr function in Python
stderr: Whenever an exception occurs in Python it is written to sys.stderr.
Example:
This code will print the string “Hello World” to the standard error stream.
The sys.stderr object represents the standard error stream, and
the print() function writes the specified strings to the stream.
Python3
import sys
def print_to_stderr(*a):
print(*a, file = sys.stderr)
print_to_stderr("Hello World")
Output:
Math Methods
Method Description
Math Methods
Method Description
Python Dates
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
import datetime
x = datetime.datetime.now()
print(x)
How to use the Python time module?
Python time module is an in-built module therefore it comes pre-
installed with the Python package. In order to use the time module we
need to only import this module.
Syntax:
import time
1. Sleep function
This function helps the program to wait when the code is getting
executed. Number of seconds of wait is added as an argument.
Syntax:
time.sleep(n)
In the example given above, the code waits for 2 seconds after
printing Hello.
Time Function
The code given below is used to derive the current time since epoch.
This function returns the time in number of seconds. Number of
seconds is returned as a floating point number.
Syntax:
time.time()
The time before epoch can also be represented with a negative sign.
Syntax:
time.localtime(n)
Syntax:
time.ctime (n)
Until now we have seen how we get the struct_time object. Now let us
learn how to do the other way around. We will make use of a time
tuple which is a named tuple.
Output
Welcome to Python 3.7's help utility!
help(print)
Output
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current
sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a
newline.
flush: whether to forcibly flush the stream.
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a
visualization utility.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding
the import module statement:
import matplotlib
print(matplotlib.__version__)
Try it Yourself »
Note: two underscore characters are used in __version__.
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:
plt.plot(xpoints, ypoints)
plt.show()
Result:
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10]
to the plot function.
plt.plot(xpoints, ypoints)
plt.show()
Result:
Try it Yourself »
Example
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):
Result:
Multiple Points
You can plot as many points as you like, just make sure you have the same
number of points in both axis.
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to
position (8, 10):
Result:
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the
plotted line:
Line Color
You can use the keyword argument color or the shorter c to set the color of the line:
Example
Set the line color to red:
Result:
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
plt.bar(x,y)
plt.show()
Result:
Try it Yourself »
The bar() function takes arguments that describes the layout of the bars.
The categories and their values represented by the first and second argument as arrays.