Introduction to Python Programming
Introduction to Python Programming
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').
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 (')
9
Fluminense Federal University
Introduction to Python
PET-Electric UFF
2.4.1. Indices
2.4.3. Methods
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.
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.1.3. Methods
13
Fluminense Federal University
Introduction to Python
Electric PET UFF
.INDEX(): Displays the index of the first occurrence of a certain
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”-
GET(key,value): Retrieves the content of the key. If the key does not
exist returns the 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.
EQUAL
!= - DIFFERENT
< - LESS THAN
GREATER THAN
17
Federal Fluminense University
Introduction to Python
PET-Electric UFF
<= - LESS THAN OR EQUAL TO
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.
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.
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.
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.
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
[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)
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
>>>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.
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], 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.
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>
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.
The general idea of list comprehension is to create a list with filters and
restrictions in a quick and simple way.
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.
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).
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.
.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.
11.2. Random
The Random module aims to take some element
random of some kind of data.
11.3. Datetime
The Datetime library allows you to work with date and time.
[Link](): Collects the current day and time.
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'
38
Fluminense Federal University
Introduction to Python
PET-Electric UFF
SHAPE: Returns the size of each dimension of the matrix.
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.
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