Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

scope in python

Uploaded by

Barvin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

scope in python

Uploaded by

Barvin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

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.

The letters in the acronym LEGB stand for Local, Enclosing,


Global, and Built-in scopes.

In programming, the scope of a name defines the area of a program


in which you can unambiguously access that name, such as
variables, functions, objects, and so on. A name will only be visible
to and accessible by the code in its scope. Several programming
languages take advantage of scope for avoiding name collisions and
unpredictable behaviors. Most commonly, you’ll distinguish two
general scopes:

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.

Some languages like Python use scope to avoid this kind of


problem. When you use a language that implements scope, there’s
no way for you to access all the variables in a program at all
locations in that program. In this case, your ability to access a given
name will depend on where you’ve defined that name.

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.

Python uses the location of the name assignment or definition to


associate it with a particular scope. In other words, where you
assign or define a name in your code determines the scope or
visibility of that name.
For example, if you assign a value to a name inside a function, then
that name will have a local Python scope. In contrast, if you
assign a value to a name outside of all functions—say, at the top
level of a module—then that name will have a global Python
scope.

Using the LEGB Rule for Python Scope


Python resolves names using the so-called LEGB rule, which is
named after the Python scope for names. The letters in LEGB stand
for Local, Enclosing, Global, and Built-in. Here’s a quick overview of
what these terms mean:

 Local (or function) scope is the code block or body of any


Python function or lambda expression. This Python scope
contains the names that you define inside the function. These
names will only be visible from the code of the function. It’s
created at function call, not at function definition, so you’ll
have as many different local scopes as function calls. This is
true even if you call the same function multiple times,
or recursively. Each call will result in a new local scope being
created.
 Enclosing (or nonlocal) scope is a special scope that only
exists for nested functions. If the local scope is an inner or
nested function, then the enclosing scope is the scope of the
outer or enclosing function. This scope contains the names that
you define in the enclosing function. The names in the
enclosing scope are visible from the code of the inner and
enclosing functions.
 Global (or module) scope is the top-most scope in a Python
program, script, or module. This Python scope contains all of
the names that you define at the top level of a program or a
module. Names in this Python scope are visible from
everywhere in your code.
 Built-in scope is a special Python scope that’s created or
loaded whenever you run a script or open an interactive
session. This scope contains names such as keywords,
functions, exceptions, and other attributes that are built into
Python. Names in this Python scope are also available from
everywhere in your code. It’s automatically loaded by Python
when you run a program or script.

Example :
Local Scope

def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function


As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

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

Explicit Type Conversion in Python


In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of
data loss since we are forcing an expression to be changed in some specific
data type. Various forms of explicit type conversion are explained below:

Converting integer to float


int(a, base): This function converts any data type to an integer. ‘Base’
specifies the base in which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-
point number.
 Python3

# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")

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.

# Coercing an int to a float.

x_int = 19
x_float = float(x_int)

print(x_float)
print(type(x_float))
19.0
<class 'float'>

# Coercing a float to an int.

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.

Python did not coerce the integer into a floating-point number; we


don't have type coercion in Python. Instead, Python delegated to the integer
and floating point numbers and asked those objects to add themselves
together.

Whenever Python sees x + y, it calls the __add__ method on x passing y to it:

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

When Python sees this special NotImplemented value, it then attempts to


ask y whether it knows how to add itself to x. To do this Python call
the __radd__ method on y, passing it x:

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

Python Objects Don't Support Type Coercion


A counterexample of this is strings.

What happens if we try to use the + operator between a string and a number
in Python?

>>> name = "Trey"


>>> x
2
>>> name + x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Many programming languages would make the string Trey2 above: they
would concatenate that string and that number, by coercing the number into
the string. In Python, we get an error instead (see TypeError: can only
concatenate str (not "int") to str for more on that specific error).

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.

So to actually accomplish what we're looking for, we need to explicitly


convert the number to a string:

>>> name + str(x)


'Trey2'
We've made a new string out of that number 2, and we're concatenating it to
our string name to get another string.

Passing function as an argument in Python


A function can take multiple arguments, these arguments can be objects,
variables(of same or different data types) and functions. Python functions
are first class objects. In the example below, a function is assigned to a
variable. This assignment doesn’t call the function. It takes the function object
referenced by shout and creates a second name pointing to it, yell.

# Python program to illustrate functions


# can be treated as objects
def shout(text):
return text.upper()

print(shout('Hello'))

yell = shout

print(yell('Hello'))
Output:
HELLO
HELLO

Higher Order Functions


Because functions are objects we can pass them as arguments to other
functions. Functions that can accept other functions as arguments are also
called higher-order functions. In the example below, a function greet is
created which takes a function as an argument.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return text.upper()

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.

Python Lambda Function Example


In the example, we defined a lambda function(upper) to convert a string to its
upper case using upper().
This code defines a lambda function named upper that takes a string as its
argument and converts it to uppercase using the upper() method. It then
applies this lambda function to the string ‘GeeksforGeeks’ and prints the result
Example :
str1 = 'GeeksforGeeks'
upper = lambda string: string.upper()
print(upper(str1))
Output:
GEEKSFORGEEKS
Use of Lambda Function in Python
Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function
Here, the ‘format_numric’ calls the lambda function, and the num is passed as
a parameter to perform operations.
 Python3

format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"

print("Int formatting:", format_numeric(1000000))


print("float formatting:", format_numeric(999999.789541235))

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

As we can see in the above example, both the cube() function


and lambda_cube() function behave the same and as intended. Let’s
analyze the above example a bit more:

With lambda function Without lambda function

Supports single-line sometimes Supports any number of lines inside a


statements that return some value. function block

Good for performing short Good for any cases that require
operations/data manipulations. multiple lines of code.

Using the lambda function can


We can use comments and function
sometime reduce the readability of
descriptions for easy readability.
code.

Using lambda() Function with map()


The map() function in Python takes in a function and a list as an argument. The
function is called with a lambda function and a list and a new list is returned
which contains all the lambda-modified items returned by that function for each
item. Example:
Multiply all elements of a list by 2 using lambda and map() function
The code doubles each element in a list using a lambda function and
the ‘map' function. It then prints the new list with the doubled elements. The
output displays each element from the original list, multiplied by 2.
 Python3
 li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

 final_list = list(map(lambda x: x*2, li))
 print(final_list)
 Output:
 [10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Transform all elements of a list to upper case using lambda and
map() function
The code converts a list of animal names to uppercase using a lambda function
and the ‘map' function. It then prints the list with the animal names in
uppercase. The output displays the animal names in all uppercase letters.
 Python3

animals = ['dog', 'cat', 'parrot', 'rabbit']


uppered_animals = list(map(lambda animal: animal.upper(), animals))

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

# A simple module, calc.py


def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)

Import module in Python


We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path.
Note: A search path is a list of directories that the interpreter searches for
importing a module.
For example, to import the module calc.py, we need to put the following
command at the top of the script.
Syntax to Import Module in Python
import module
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.
Importing modules in Python Example
Now, we are importing the calc that we created earlier to perform add
operation.
 Python3
 # importing module calc.py
 import calc

 print(calc.add(10, 2))
 Output:
 12
Python Import From Module
Python’s from statement lets you import specific attributes from a module
without importing the module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math
module.
 Python3

# importing sqrt() and factorial from the

# module math

from math import sqrt, factorial

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

Python sys Module


The sys module in Python provides various functions and variables that are
used to manipulate different parts of the Python runtime environment. It allows
operating on the interpreter as it provides access to the variables and functions
that interact strongly with the interpreter. Let’s consider the below example.
Sys Module in Python
Python sys.version
In this example, sys.version is used which returns a string containing the
version of Python Interpreter with some additional information. This shows how
the sys module interacts with the interpreter. Let us dive into the article to get
more information about the sys module.
 Python3
 import sys
 print(sys.version)
Output:
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
Input and Output using Python Sys
The sys modules provide variables for better control over input or output. We
can even redirect the input and output to other devices. This can be done using
three variables –
 stdin
 stdout
 stderr
Read from stdin in Python
stdin: It can be used to get input from the command line directly. It is used for
standard input. It internally calls the input() method. It, also, automatically adds
‘\n’ after each sentence.
Example:
This code reads lines from the standard input until the user enters ‘q’. For each
line, it prints “Input : ” followed by the line. Finally, it prints “Exit”.
 Python3
 import sys
 for line in sys.stdin:
 if 'q' == line.rstrip():
 break
 print(f'Input : {line}')

 print("Exit")
output :

Python sys.stdout Method


stdout: A built-in file object that is analogous to the interpreter’s standard
output stream in Python. stdout is used to display output directly to the screen
console. Output can be of any form, it can be output from a print statement, an
expression statement, and even a prompt direct for input. By default, streams
are in text mode. In fact, wherever a print function is called within the code, it is
first written to sys.stdout and then finally on to the screen.
Example:
This code will print the string “Geeks” to the standard output.
The sys.stdout object represents the standard output stream, and
the write() method writes the specified string to the stream.
 Python3

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:

Python math Module


Python has a built-in module that you can use for mathematical tasks.

The math module has a set of methods and constants.

Math Methods
Method Description

math.acos() Returns the arc cosine of a number

Math Methods
Method Description

math.acos() Returns the arc cosine of a number

math.asin() Returns the arc sine of a number

math.atan() Returns the arc tangent of a number in radians

math.ceil() Rounds a number up to the nearest integer

math.cos() Returns the cosine of a number

math.degrees() Converts an angle from radians to degrees

math.dist() Returns the Euclidean distance between two points (p


and q), where p and q are the coordinates of that point

math.erf() Returns the error function of a number

math.exp() Returns E raised to the power of x

math.fabs() Returns the absolute value of a number

math.factorial() Returns the factorial of a number

math.floor() Rounds a number down to the nearest integer

math.fmod() Returns the remainder of x/y

math.frexp() Returns the mantissa and the exponent, of a specified


number

math.fsum() Returns the sum of all items in any iterable (tuples,


arrays, lists, etc.)

math.gcd() Returns the greatest common divisor of two integers

math.isfinite() Checks whether a number is finite or not

math.isinf() Checks whether a number is infinite or not

math.isqrt() Rounds a square root number downwards to the


nearest integer
math.log() Returns the natural logarithm of a number, or the
logarithm of number to base

math.log10() Returns the base-10 logarithm of x

math.pow() Returns the value of x to the power of y

math.radians() Converts a degree value into radians

math.remainder() Returns the closest value that can make numerator


completely divisible by the denominator

math.sin() Returns the sine of a number

math.sqrt() Returns the square root of a number

math.tan() Returns the tangent of a number

math.trunc() Returns the truncated integer parts of a number

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.

ExampleGet your own Python Server


Import the datetime module and display the current date:

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

Functions of the Python time module


Let us now into the time functions of this module.

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)

Here n is the number of seconds.

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.

Local time Function


This function returns struct_time object which contains a tuple having
few attributes. The struct_time class is the same which we have
obtained in one of the above functions. It takes the number of
seconds since epoch as the argument. Take a look at the example
given below.

Syntax:

time.localtime(n)

Current time function


The return value of this function is the current year, date and time
along with the day. This also takes the number of seconds since
epoch as the argument.

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.

Note: If no argument is present it calculates the time till present.

Help function in Python


In Python, the help() function is a built-in function that provides information
about modules, classes, functions, and modules. In this article, we will learn
about help function in Python.
help() function in Python Syntax
Syntax: help([object])
Parameters (Optional) : Any object for which we want some help or the
information.
If the help function is passed without an argument, then the interactive help
utility starts up on the console.
What is Help function in Python?
The Python help function is used to display the documentation of modules,
functions, classes, keywords, etc. It provides information about modules,
classes, functions, and methods. It is a useful tool for getting documentation
and assistance on various aspects of Python.
Python help() function Examples
Simple help() Program
In this example, we are using help() without any object to access
documentation in Python.
 Python3
help()

Output
Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely


check out
the tutorial on the Internet at
https://docs.python.org/3.7/tutorial/.

Enter the name ...


Help with Print Function in Python
Let us check the documentation of the print function in the Python console.
 Python3

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.

Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C,


Objective-C and Javascript for Platform compatibility.

Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding
the import module statement:

import matplotlib

Now Matplotlib is imported and ready to use:


Checking Matplotlib Version
The version string is stored under __version__ attribute.

ExampleGet your own Python Server


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:

import matplotlib.pyplot as plt

Now the Pyplot package can be referred to as plt.

ExampleGet your own Python Server


Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()

Result:
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

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.

ExampleGet your own Python Server


Draw a line in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()

Result:

Try it Yourself »

The x-axis is the horizontal axis.

Plotting Without Line


To plot only the markers, you can use shortcut string notation parameter 'o', which means
'rings'.

Example
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')


plt.show()

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

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 2, 6, 8])


ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()

Result:

Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the
plotted line:

ExampleGet your own Python Server


Use a dotted line:

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linestyle = 'dotted')


plt.show()
Result:

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:

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, color = 'r')


plt.show()

Result:
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:

ExampleGet your own Python Server


Draw 4 bars:

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

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.

You might also like