0% found this document useful (0 votes)
4 views41 pages

Introduction to Python Programming

The document presents an introduction to Python, describing its syntax, variable types, input and output of data, lists, dictionaries, control flow, functions, classes, files, and libraries. The main variable types in Python are integers, floats, booleans, and strings. Lists and dictionaries can store multiple values and are accessed by their indices. Control flow includes structures such as if/elif/else and for/while. Functions and classes organize the code into

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views41 pages

Introduction to Python Programming

The document presents an introduction to Python, describing its syntax, variable types, input and output of data, lists, dictionaries, control flow, functions, classes, files, and libraries. The main variable types in Python are integers, floats, booleans, and strings. Lists and dictionaries can store multiple values and are accessed by their indices. Control flow includes structures such as if/elif/else and for/while. Functions and classes organize the code into

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Summary

1. Introduction 5
1.1. Syntax ........................................................................................ 5
1.2. Indentationo.................................................................................. 5
1.3. Comments ............................................................................... 6
1.4. Operations 6
2. Types Basics of variables.................................................. 7
2.1. Int 7
2.2. Float 7
2.3. Bool 8
2.3.1. Operations with booleans.................................................... 8
2.4. String .......................................................................................... 9
2.4.1. Indices ................................................................................ 10
2.4.2. Operations with strings........................................................ 10
2.4.3. Methods ............................................................................. 10
2.5. How print variables inside a stringg......................... 11
3. Entrance and data output.................................................................. 11
4. Lists The Dictionaries ........................................................................... 12
4.1. List .......................................................................................... 12
4.1.1. How call the elements of the list by their indices .......... 13
4.1.2. Operations with lists .......................................................... 13
4.1.3. Methods ............................................................................. 13
4.2. Dictionary 15
4.2.1. Accessing and creating keys and content ........................... 15
4.2.2. Methods ............................................................................. 16
5. Control of Flow ............................................................................. 17
5.1. If, Elif and Else............................................................................... 17

2
Federal Fluminense University
Introduction to Python
PET-Electric UFF
5.1.1. Difference between elif and else ................................................ 18
6. Control of Repetitiono.19
6.1. For 19
6.1.1. For ... Else ........................................................................... 20
6.2. While 21
6.2.1. While ... Else ....................................................................... 22
7. Functions ............................................................................................ 22
7.1. Syntax ...................................................................................... 22
7.2. Functions already defined in Python
8. Classes 23
8.1. Syntax ...................................................................................... 24
8.2. Objects ..................................................................................... 24
8.3. Constructor 25
8.4. Attribute .................................................................................... 25
8.5. Methods ................................................................................... 26
8.6. Inheritance .................................................................................... 27
8.7. Overlap of Methods ........................................................ 28
9. Arquivos ........................................................................................... 29
9.1. Open/Close ............................................................ 29
9.2. Modes 29
9.3. Modifiers in ways .......................................................... 30
9.4. Functions applied to files .................................................... 30
9.5. With, as..................................................................................... 30
10. Commands useful Python ............................................................. 31
10.1. Try / Except............................................................................... 31
[Link] with the use of "” ............................................................... 31
10.3. Understanding of lists.32
10.4. Step list slicing...................................................... 32
10.5. Functions Lambda ....................................................................... 33

3
Federal Fluminense University
Introduction to Python
UFF Electric PET
11. Libraries 34
11.1. Math ......................................................................................... 34
11.2. Random .................................................................................... 36
11.3. Datetimee................................................................................... 37
11.4. Numpy 38
11.4.1. Accessing elements ...................................................... 40
11.4.2. Operations between arrays ................................................... 41

4
Fluminense Federal University
Introduction to Python
PET-Electric UFF
1. Introduction
Python is an interpreted programming language,
object-oriented. It became extremely popular due to its
simple syntax and its easy readability, in addition to its excellent portability.
Due to its popularity, Python already has numerous frameworks and libraries.
very useful, making it a very powerful language.

1.1. Syntax
Variables in Python, unlike other languages,
programming, they do not need to have their type declared. That is, it is not
it is necessary to inform the program in advance if the variable receives a
integer value, real, logical, etc., just initialize the variable directly with the value.

1.2. Indentation
When we write a program in Python, we must
it must be correctly indented. While in other
In programming languages, we aim to indent the code to make it more readable, in
Python we are forced to do it, since the program will not work
without the indentation.

5
Federal Fluminense University
Introduction to Python
PET-Electric UFF
1.3. Comentários
Comments are snippets of code that will not be interpreted.
They serve to comment on what each piece of code does, so that
others can understand. In Python, comments are made with
following form:
‘#’ : Para comentários em linha única
‘ “”” (text) “”” ‘ : For text blocks.

1.4. Operations
Simple arithmetic operations can be done in Python in a way
natural, using the signs we are used to (+, -, /, *). In addition,
there is '%' and '**' which represent the remainder of division and exponentiation,
respectively. The priority of operations is the natural one of mathematics.
However, the more parentheses are used, the better it is to avoid
mistakes may be made.

6
Fluminense Federal University
Introduction to Python
PET-Electric UFF
2. Basic types of variables
Among the various types of variables that exist in Python, there are
4 main types that help form all the others. They are: int, float,
bool and string.

[Link]
Int are the variables that store integer values. With them themselves
variables can perform the simple arithmetic operations mentioned earlier,
however, if all the variables are of type int, the answer will also be
an int type.

[Link]
The float type variables store values with decimal places, when
the opposite of the int type. However, the same calculations can be done even
between the two types. The response priority is always of the float type.
Remembering that instead of ',' one should use '.'.

7
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link]
They are types of variables that store logical values such as true.
it's false (in Python, 'True' and 'False').

Verifications are also conducted on other variables, such as for


example, "could a certain variable have the value2?". This type of
The question is asked using ' == '. The answer will always be of the bool type.
or boolean.

2.3.1. Operations with Booleans

Operations with booleans are a bit different from


operations with other variables. In this case, logical operations are performed
with the use of the commands 'and', 'or' and 'not'. The logic is the same as
table below.

8
Fluminense Federal University
Introduction to Python
UFF Electric PET
[Link]
String is a type of variable that handles a sequence of
characters, whether numbers or letters. To define a string, just
associate a variable with any sequence of characters between quotes
double quotes (") or single quotes (')

When defining a string using single quotes, you need to be careful.


when using another single quote within the same string, as the
the program will really interpret only what is in the first pair of
quotes. If you want to fix the problem, you should use double quotes or
add a backslash (\) before the quotes.

9
Fluminense Federal University
Introduction to Python
PET-Electric UFF
2.4.1. Indices

Every string is indexed, meaning all the characters contained in a


strings have a position, the first character has index 0, the second
it has index 1, and so on. To call the characters of a string
by its index, just add your index in brackets.

2.4.2. Operations with strings

Apesar de parecer estranho, algumas operações com strings podem


to be done with the '+' (also called concatenation), as well as
like "*".

2.4.3. Methods

LEN (): Returns the length of the string

LOWER(): Returns the string in lowercase


.UPPER(): Returns the string in uppercase
STR() : Transforms any variable into a string

10
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link] to print variables inside a string
In Python, there is an excellent formatting tool when one
use print to display some information on the screen with variables that it is
the use of the following characters: %s, %d, %f. These characters represent,
respectively, a string, an integer, and a float.

3. Input and output of data


In many cases, it is necessary for the program to receive and manipulate
user data. In Python, there are two ways to read data, either
using the raw_input() or input() command. In raw_input everything that is
written by the user will be transformed into a string. The input only accepts
input of numerical data, which will be transformed into some type already
known variable. To write a string with the input command is
the use of quotes is necessary, which is not the case for raw_input.

11
Fluminense Federal University
Introduction to Python
UFF Electric PET
To print the data, the print command is used, as follows
demonstrated below:

>>> a = 12
>>>printa
12
Python Mini Course
Mini course in Python

4. Lists and Dictionaries


[Link]
It is a set of ordered values, where each element is
identified by an index, where in the Python language the first
the first element is identified by index 0, the second by index 1, and so on
subsequently. The elements can be of type int, float or even
string.
Among the various ways to create a list, the simplest of them
is to wrap its elements using brackets.

Note: In the example, the variable lista2 is extremely similar to


a vector. A list is the simplest way to represent a vector, and
12
Federal Fluminense University
Introduction to Python
PET-Electric UFF
it can also be used to represent a matrix. However, there are
better ways, like the 'Numpy' library.

4.1.1. How to call the list elements by their indices

To access a specific element of a list, the following is done


same principle of a string. If there are n elements, their positions
will be defined from 0 to n-1. Therefore, to access an element q, where
if q<n, the following command must be executed: list_name[q-1].

4.1.2. Operations with lists

The same operations with strings can be done with lists. So


You can add lists or even multiply them by an integer.

4.1.3. Methods

.APPEND(): Adds a specified element to the mentioned list.

13
Fluminense Federal University
Introduction to Python
Electric PET UFF
.INDEX(): Displays the index of the first occurrence of a certain
element.

.INSERT(): Inserts an element at a chosen index


programmer.

DEL: Removes the element from an index chosen by the programmer.

.SORT(): Sorts a given list.

REMOVE(): Remove the first occurrence of a given


element.

14
Fluminense Federal University
Introduction to Python
PET-Electric UFF
POP: Removes and returns the last value of the list. It can also be
assign an index for removal, with the removed value being returned.

[Link]
Dictionaries are data structures formed by pairs of values.
where the first value is called key and the second content. From
In a way they are similar to lists, where each index of the list can
"is now represented by strings, in addition to integers and floats. One of the
easiest ways to introduce the dictionary is by placing your
elementos entre chaves da seguinte forma:,“chave”: “conteúdo”-

4.2.1. Accessing and creating keys and contents

One can also access the contents as in the list only.


putting in the place of what was the index a key. In addition, one can
create new keys by simply assigning values.
15
Federal Fluminense University
Introduction to Python
PET-Electric UFF
4.2.2. Methods

CLEAR(): Remove all elements from the dictionary.

.FROMKEYS(list,value): returns a new dictionary whose keys are


the elements of a list whose values are equal to the value.

GET(key,value): Retrieves the content of the key. If the key does not
exist returns the value.

ITEMS(): Returns a list of key/value pairs, unordered


specific.

KEYS(): Returns a list of keys, in no specific order.


16
Fluminense Federal University
Introduction to Python
Electric PET UFF
VALUES(): Returns a list of values, in no specific order.

.POP(key): Returns the value corresponding to the key and removes it


by key/value.

5. Controle de Fluxo
In every programming language, the following are present:
flow controllers, used for the program to execute
certain instructions from a condition.

5.1. If, Elif and Else

In Python, the flow control that uses conditions to evaluate


the next command to be executed is the if. With this command the
the interpreter is capable of evaluating whether a condition is true and with that
perform a sequence of different processes. The else command is
made if it does not meet the condition of the if. So that the program is
able to evaluate conditions, it is necessary to use logical comparators, such as
how:

EQUAL
!= - DIFFERENT
< - LESS THAN
GREATER THAN
17
Federal Fluminense University
Introduction to Python
PET-Electric UFF
<= - LESS THAN OR EQUAL TO

>= - GREATER THAN OR EQUAL TO

In this program it evaluates in the case if the remainder of the division of


number for 0. If so, it will display the phrase 'This
the number is even, otherwise it will display the phrase 'This number is'
odd.

Note: After using the commands if, elif, and else, it is necessary to use
dois pontos (:), e todo o código a ser seguido deve estar devidamente
Indented.

5.1.1. Difference between elif and else

The elif command is an abbreviation of else if. The else complements the
if, that is, if the condition is not true the commands to be
Those who are indented to the else will be executed. The elif, on the other hand, performs the
following commands evaluating a new condition.
Note: Unlike many languages, in Python the elif NEVER
It will be inside the if. The priority will be completely given to what comes first.

18
Fluminense Federal University
Introduction to Python
PET-Electric UFF
6. Repetition Control
The repetition commands are applied when one wants the
code to be executed a certain number of times throughout the
program, creating a loop.

[Link]
The for command in Python is a bit different from others.
languages. In Python, it iterates over elements of a variable. By
for example, it could iterate over the elements of a list, the letters of a
string and etc.
To use the for command, an auxiliary variable will be created, with a
any name, in such a way that with each interaction it will be equal to
an element of that object in order.

However, it is also possible to use the for in the same way as in


other languages, where some commands are made by a certain
number of times necessary. For this purpose, one can use the
range() function that returns a list with the number of elements that
is in your argument.

19
Fluminense Federal University
Introduction to Python
Electromagnetic PET UFF
If this command is integrated into the loop, the following will happen:

When traversing a sequence, one can obtain the index of the position.
current and its corresponding value through the enumerate() function.

>>>forordem, iin enumerate(*“Arroz”,”Feijão”,”Carne”+):


>>>printorder, i
0 Rice
1 Bean
2 Meat

6.1.1. For ... Else

Just like the if command, the for loop also has an else condition.
This last one will be executed only once, as soon as it finishes the
condition of the for.

20
Federal Fluminense University
Introduction to Python
PET-Electric UFF
[Link]
The while is a repetition structure that executes a code.
whenever a certain condition is true. From the moment
if this condition becomes false, the program will continue without accessing the
information about the while again.

Note: One must take great care so that at some point the
the while condition becomes false. If this never happens the program will
execute the command indefinitely. A very useful way to avoid
this type of disaster is the command 'break'. It makes the program
automatically exit the loop.

21
Fluminense Federal University
Introduction to Python
PET-Electric UFF
6.2.1. While ... Else

Just like in the for and in the if, a condition can be placed.
else in the while command, being executed only once as soon as it exits the
condition imposed by the command.

7. Functions
In general, when we create a program, we want to use it to
perform some actions often making the code long
and difficult to understand. One way to make the code simpler and
organized is replacing repeated actions with functions.

7.1. Syntax
In Python, to define functions, just use the def command.
function_name(parameter1, parameter2, ...):

22
Fluminense Federal University
Introduction to Python
UFF Electric PET
When we define a function in Python, we need to define
also one or more parameters, which are the variables used by the
function. Functions that need to return a number or a
strings use the return command.
To call a function already defined in your program, simply
write her name and indicate in parentheses which variable it is
function will take as parameter. If your function requires more than one
the parameter is important in the order when calling the function.

[Link] defined functions in Python

MAX(): Returns the maximum value of a list, dictionary, or string.

MIN(): Returns the minimum value of a list, dictionary, or string.

ABS(): Returns the absolute value of a number.

TYPE(): Returns the type of any object.

8. Classes
Class is the basic structure of the object-oriented paradigm, it is
a user-defined type that represents sets of objects, abstractions

23
Fluminense Federal University
Introduction to Python
UFF Electric PET
computational entities that have characteristics (attributes)
and similar actions (methods).
The use of classes is intended to solve the issue of creation of
objects, that is, instead of creating isolated objects, with definition of
attributes and methods for each one, are applied to the classes to define the
attributes and methods common to all objects.

[Link]
The class is created in Python using the reserved word class.
the syntax is as follows:

class ClassName:
>>> <commands>

In the case where the class does nothing, the reserved word pass is used:

class ClassName:
pass

It is recommended to use a capital letter to start the name of the


class.

[Link]
In general, instances are used for the execution of a
program and not the classes. Instances can be seen as individuals
of a class, having its attributes. The syntax used to produce
the instance is as follows:

Class_name(parameters)

To reference a given instance created, you are assigned a


variable, representing the object.

variable = Class_name(parameters)

24
Federal Fluminense University
Introduction to Python
PET-Electric UFF
8.3. Constructor
When an object is created, the class constructor is executed. In
In Python, the constructor is a special method called __new__(), after
in this call, the __init__() method is called to initialize a new
instance. When an object is deleted, the __done__() method is called.

class ClassName:
def __init__(self, arguments):
>>> [Link]=argumentos

The variable self, which represents the object that needs to be passed from
explicit form, it is a convention that can be replaced by another
word, but it is a good practice to keep it.

[Link]
The attributes are common to all instances of the class and
they represent their characteristics.

class ClassName:
attribute=quantity_or_quality_of_the_attribute

With the command dir() it is possible to check all the attributes


associated with the class.

To access an attribute of the object, just apply the syntax:

>>>object_name.attribute_name

25
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link]
Methods are functions defined within classes, used to
define actions to be executed by an instance of this class. For
to create a method it is necessary to use the syntax:

>>>def method_name():
>>> <commands>
26
Fluminense Federal University
Introduction to Python
PET-Electric UFF
In Python, to make attributes and methods private, just start with
the for a maximum of two underlines and end with an underline, the
other forms are public.

[Link]
Inheritance is used to take advantage of a part of the code. The
Classes in Python can inherit attributes, methods, etc., from others.
classes. Without the use of inheritance, each of the attributes, methods, etc,
It would have to be defined class by class. The syntax is as follows:

>>>class ParentClassName:
<attributes 1>
>>>class ChildClassName(ParentClassName):
<attributes 2>
In this case, the child class will have attributes 1 and 2, attribute 1
because it inherited from the parent class.

27
Federal Fluminense University
Introduction to Python
PET-Electric UFF
[Link] Overriding
Method overriding consists of defining a function in the class
father and define another function with the same name in the child class, but that
they have different functionalities.

28
Fluminense Federal University
Introduction to Python
UFF Electric PET
9. Files
Files in Python are represented by file-type objects.
that provide some forms of access to the file, such as reading and
writing.

[Link]/Close
File manipulation is done through the open() command.
where the filename and its state, whether it will be created or read, are defined.
When the file is created, the information inserted in it is
stored in the buffer and in order for them to be executed it is necessary to give the
commandclose().
variable=open("file_name.extension","file_mode")
>>> <commands>
[Link]()

[Link]
The manipulation modes in Python are as follows:
Write (w): It writes to the file; if the file does not exist, it is created.
created at the moment. The write mode overwrites what the file
contains, deleting the previously written information.
Append (a): In order for the content not to be deleted, one uses the
append mode, which inserts new information into the file without
to turn off what was previously in it. The added text will be
inserted at the end of the file. If the file does not exist, it will be
created.
The read is used to read the content of the existing file.

If no mode is used in the file, by default it is


employed the read mode.

29
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link] modifiers
The mode modifiers are used together with the modes.
described earlier, allowing for the expansion of the functionalities of
file manipulation. The mode modifiers are as follows:
Allows both reading and writing. For example: when used
in the following way "r+", allows reading and writing to the file.
b: Manipulate the file in binary and not in text as it is
usually done. For example: "rb".

[Link] applied to files


WRITE(): Used to write something to the file.
[Link](" Text to be inserted in the file")
READ(): Used to read the file.
>>> [Link]()
READLINE(): Used to read only one line from the file.
>>> [Link]()
.CLOSED(): Used to check if the file has actually been
closed. Your return will be a boolean, True if the file is
closed and False if it is open.
[Link]()

[Link], as
In Python, it is possible to create a file that is
automatically closed shortly after the commands without using the method
.close(). For this, the command with... as... is used to open the file.

>>>with open("[Link]", "file mode") as


variable:
[Link]("Text to be inserted into the file")

30
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link] Python Commands
10.1. Try / Except
When a code is written without errors, it will work
correctly, however when this does not occur, it is appropriate to use a
exception message. This task is to insert an exception message
is dedicated to the programmer through try/except. This operation is
important because when a failure occurs an exception is generated, and if this
if the exception is not handled, the program stops executing.
try:
>>> <commands>
except
>>> <commands>

[Link] using the ','


The comma (,) can be used in conjunction with the print function to
display the information without line breaks.

31
Federal Fluminense University
Introduction to Python
PET-Electric UFF
10.3. Understanding Lists
Assuming that one wants to build a list with 20 elements. For
this can use the command range(20). However, one may desire a
a certain list with restrictions and filters. For example, even numbers
from 0 to 50 or the numbers divisible by 7 from the sequence [3,158], or up to
even in a simplified way have a list of the sequence [0,50] that
they are even.

It could be done differently, but not as practically.

The general idea of list comprehension is to create a list with filters and
restrictions in a quick and simple way.

10.4. Slicing and dicing lists


Lists can be sliced using the following syntax:
List_name[start:end:step]
Start would be where the slicing begins. End where it finishes, however,
not including this number. The step is the space between each element of
slicing.

32
Federal Fluminense University
Introduction to Python
PET-Electrical UFF
The indices for slicing can be omitted, therefore, the
the index for the beginning becomes the standard, in this case index 0, the end of the list
assume a value determined by the user, and the step will be 1.

Note: The step can also be negative. Therefore, the list will be
traversed from right to left.

10.5. Lambda Functions


Lambda or Anonymous Functions are functions whose purpose is to leave the
simpler and more functional program.

What is the same as:

Anonymous functions are very useful when combined with the


filter() function, to filter a list.

33
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link]
Just like any other programming language, Python
it has code libraries, with predefined functions, among others
tools. To use these libraries, just use the command import
module_name, or the command from library_name import
module_name. Furthermore, to facilitate the call of a
library, we can use it with whatever name we want through the
commanding soimportmodule_name as alias or
from library_name import module_name as use_name.
Another very useful command when it comes to libraries is the
dir(library_name), to show all the functions contained in it.
To use the methods of a library, simply call it as
library_name.function_name(arguments).

Remember that when the import command is used, it will search


the module within the library, if not found, will pass to
interpret what is after 'import' as a library. In case
if the library does not exist, an error will occur.

The main uses of some libraries will be shown.


Python, some already installed, others not.

11.1. Math
The math library aims to facilitate the use of the language.
mathematics. Functions like square root, value of pi, etc. are already
embedded in it.

34
Fluminense Federal University
Introduction to Python
PET-Electric UFF
FACTORIAL(x): Returns the factorial of x.

.EXP(x): Returns the value of .

.SQRT(x): Returns the value of the square root of x.

.CEIL(x): Returns the smallest integer greater than x.

.FLOOR(x): Returns the largest integer value less than x.

LOG(x,[b]): Returns the logarithm value of x to the base b. If not given


The value of b is considered b = e (Euler's number).

.PI / .E: Returns the values of the constant pi and 'e' (number of
Euller).

35
Fluminense Federal University
Introduction to Python
PET-Electric UFF
DEGREES(x): Returns the value of angle x from radians to degrees.

.RADIANS(x): Returns the value of angle x from degrees to radians.

SIN(x) / COS(x) / TAN(X): Returns the sine/cosine/tangent of x.

.ASIN(x)/.ACOS(x)/.ATAN(x): Returns the value of arc sine/ cosine/ tangent


tangent of x.

11.2. Random
The Random module aims to take some element
random of some kind of data.

.RANDOM(): Returns a random element between 0 and 1.

.UNIFORM(a,b): Returns a random element between a and b,


including a and excluding b.

.RANDINT(a,b): Returns a random integer element between a and b


including these two.
36
Fluminense Federal University
Introduction to Python
PET-Electric UFF
.RANDRANGE(b)/(a,b,step): Returns a random integer element
between a and b, including a and excluding b, with a determined step.

CHOICE(seq): Returns a random element from a sequence


seq.

SAMPLE(seq, k): Returns a list of size k with k elements


random from a sequence seq.

11.3. Datetime
The Datetime library allows you to work with date and time.
[Link](): Collects the current day and time.

>>> print [Link]()


2015-11-08 01:58:02.182000

[Link]().YEAR: Highlights only the year from the date.

>>> print [Link]().year


>>> 2015

[Link]().MONTH: Highlights only the month from the date.

>>> print [Link]().month


11
37
Fluminense Federal University
Introduction to Python
PET-Electric UFF
[Link]().DAY: Highlights only the day from the date.

>>> print [Link]().day


>>>8

[Link]().HOUR: Highlights only the hour from the time.

>>> print [Link]().hour


1

[Link]().MINUTE: Highlights only the minute from the time.

>>> print [Link]().minute


>>>58

[Link]().SECOND: Highlights only the second from the time.

>>> print [Link]().second


18

11.4. Numpy
Numpy is a package whose main function is to perform
operations with vectors and matrices. This tool is far superior to the
operations with original Python vectors. The type of variable created by
the Numpy library is called an 'array'

.ARRAY([[Line1],[Line2],...,[LineN]]): main creation method


of matrices and vectors. Note that your arguments are lists within
a single list. If it is a vector, it can be done as follows:
.ARRAY([line1]).

38
Fluminense Federal University
Introduction to Python
PET-Electric UFF
SHAPE: Returns the size of each dimension of the matrix.

TRANSPOSE(): Returns the transpose of the matrix.

SUM(matrix, [axis=(0, 1)]): Returns the sum of all elements of


a matrix if it has only one argument. Otherwise, if placed
axis = 0, it will return a list with the sum of the elements of each column, if
for axis = 1, it will return a list with the sum of the elements of each row.

39
Fluminense Federal University
Introduction to Python
UFF-PET Electric
.ARANGE(c): Very similar to the range function. The great
difference that returns a variable of array type and not a list.

.ZEROS([a,b], dtype = Int): Creates a matrix with dimensions axb


filled with zeros of type float if only one argument was given. In
the second argument specifies an integer (dtype = int).

[Link](a): Returns the determinant of a matrix a.

11.4.1. Accessing elements

Just like with lists, each element can be accessed


an array. Similarly, the way to do this is
matrix[Index_row, Index_column].
Note: Do not forget that in Python we always start counting from
indices start from 0. So to access the element at row 2, column 3
it should be array[1,2]

40
Fluminense Federal University
Introduction to Python
PET-Electric UFF
11.4.2. Operations between arrays

One of the great advantages of using numpy is the fact that its
operations are already pre-programmed. The commands of
operations with arrays follow the same pattern as arithmetic operations
basic in addition and subtraction, with matrix multiplication done
with the command .DOT(a,b), where a and b are matrices.

41
Fluminense Federal University
Introduction to Python
PET-Electric UFF

You might also like