Python From Scratch
Python From Scratch
PYTHON
DO ZERO
Augusto Patsch
@programmer_empire
SUMMARY
INTRODUCTION..................................................04
Why learn Python?....................................................04
Applications in Python..........................................................05
PYTHON INSTALLATION.............................................................06
Windows
Linux
MacOS
PYCHARM INSTALLATION.........................................................10
Windows 10
Linux
MacOS..................................................................................17
VARIABLES
What are variables?...............................19
Rules for declaring variables..............................................19
Dynamic typing...............................................................19
Types of variables .................................................................20
Input( ) ..................................................................................21
STRINGS...................................................................................22
What is a string?
Concatenation......................................................22
Manipulation.................................................................22
Slicing............................................................................26
NUMBERS................................................................................27
Arithmetic operators........................................................27
Comparison operators...............................................27
Logical operators..............................................................28
SUMMARY
COLLECTIONS..............................................................................29
Lists.........................................................................29
Tuples.........................................................................33
Dicionários............................................................................34
DECISION STRUCTURE.......................................................35
If............................................................................................35
If Else.....................................................................................36
If Elif Else..............................................................................37
LOOP STRUCTURE.................................................38
While
For.........................................................................................39
FUNCTIONS............................................................40
What is a function?.........................................................40
Syntax..................................................................................40
Parameters and Arguments....................................................40
Variable scope..............................................................41
Return of values................................................................41
BIBLIOGRAPHY........................................................................42
INTRODUCTION
WHY PYTHON?
EASE
Python language is one of the easiest to learn. If you are a beginner
In the world of programming, there will be no great difficulties, just a basic understanding is enough.
basic English language and will learn comfortably. It is due to its simplicity.
What beginner programming courses commonly use the Python language.
IT IS PORTABLE
Saying that Python is a portable language means that we can run it on
the same program on different operating systems without needing to change the code.
PRACTICALITY
Python is a much more practical language than the others, a program made in Python
usually has much fewer lines of code required to perform a task
than C/C++ and Java, for example. Let's take an example of a program
that your task is to open a csv file.
In Java:
04
IT'S FREE
To program in Python you don't need any license, it runs on
any computer or laptop. Other resources such as modules, libraries, and IDEs
are completely free.
LIBRARIES
Python has a huge number of libraries that will assist you when programming.
With libraries, you can use codes already made by other people without having to
invent everything from scratch.
PYTHON APPLICATIONS
DATA SCIENCE
Data Science is a field whose main objective is to study the analysis of data extracted from
various sources to obtain information and subsequently make predictions. The
the most used libraries are Pandas, NumPy, and SciPy.
MACHINE LEARNING
AlsoknownasMachineLearning,machinelearningisabranchof
Artificial Intelligence. It automates the construction of analytical models from a
data analysis so that the machine can identify patterns and make decisions with the
minimum possible human interference.
WEB DEVELOPMENT
Through two widely used frameworks, Django and Flash, it is possible to create applications
the sites that are accessed directly from the browser on computers, mobile phones and
tablets.
SCRIPTING
They are short programs that automate daily tasks that could be done by
own humans, like sending emails and sending automatic messages on WhatsApp.
GAMES
Itisalsopossibletocreatesimplegames,suchasFlappyBird,Snake,game
from memory, among others, through the PyGame library.
These are just some of the main applications of the Python language. With Python,
It's possible to do practically anything you want!
05
PYTHON INSTALLATION
WINDOWS
To install Python on Windows, you need to download the installer, which you can find
on the official site ([Link]/downloads/). Click on download.
By default, Python 3 will be downloaded for 32-bit systems. For the installer
of 64 bits, click on windows and select the appropriate 64-bit installer, such as
shown below.
06
Download the executable installer for Windows (32 or 64 bits) and double click
click on it to start the Python installation assistant, as shown below.
If everything goes well, the next screen will be displayed. Click on 'Close'.
07
LINUX
Installation via Package Managers
The apt-get (Debian, Ubuntu) and yum (RedHat, CentOS) are the package managers
most common. If you do not use one of these package managers, visit
the Python downloads page.
Apt-get
To install Python 3, type in a terminal:
Yum
To install Python 3, type in a terminal:
08
MacOS
If you have macOS version 10.2 or higher, you probably already have some
installed version of python.
If it returns something like /usr/bin/python means that you already have Python
installed.
INSTALLATION
Before installing Python, install Xcode (App Store) from the development package.
in command line on macOS, command line tools and package managers
pip and homebrew.
$ xcode-select --install
09
PYCHARM INSTALLATION
With Python already installed, now we need a text editor so that we can
write our codes.
For this, we will use PyCharm, one of the most commonly used IDEs for programming in
python.
WINDOWS
To install PyCharm, go to the IDE website ([Link]/pycharm/)
and click on the download button
10
Welcome to PyCharm: Click on next
Installation Options: check all the options presented and click next
11
Choose Start menu folder: we will not select any option, we just click on
Install
In the end, the option to reboot the machine will appear, however, we will select the option
I want to manually reboot later
12
Open PyCharm and select the option 'Do not import settings' and click OK
Choose the option you prefer and click on 'Skip Remaining and Set Default'
We need to inform the program where Python is installed. To do this, access the
settings and configurations
13
In Project Interpreter, click on the Show All option.
14
LINUX
VIA SNAP
Open a terminal
Update the PyCharm IDE snap (later if necessary), use this command:
you
Download and add the GetDeb repository key with the command:
15
To install the PyCharm community IDE use this command:
16
MacOS X
Python is installed, but now we will require a Development Environment
Integrated, also known as IDE, may be installed on your computer to allow
that you code.
Go to [Link] This will display the
latest version of PyCharm. Below the community, download the free version and
PyCharm open source.
Select Open when attempting to run the application for the first time.
17
Now we will test if PyCharm works by running the program. You will be prompted.
reading the JetBrains Privacy Policy. After reading, confirm that you have read the Agreement.
of the User.
Now you can choose from different options for the installation of Pycharm.
Select 'I have never used Pycharm' to optimize your experience as a beginner.
18
VARIABLES
Example = 10
_Exemplo = 10
0Example = 10
Example = 10
2. The rest of the variable can contain letters, numbers, and underscores.
Exemplo_com_0 = 10
DYNAMIC TYPING
In Python, you do not need to specify the type of the variable before assigning a value to it.
value, as in C and Java, for example. Here, the interpreter infers the data type itself.
that a variable receives
19
TYPES OF VARIABLES
INTEGER - it is a number without decimal places, for example: 1, 3, 10, 10050.
STRING - is one or more characters, must be assigned to the variable with single quotes or
pairs
print( ) type( )
It is a function used to print the It is a function used to identify
arguments in a terminal the type of a variable
20
Input() is the function responsible for data entry in the program. Every time the input
the string passed as a parameter will be printed to the terminal and then
request a value from the user.
In the code:
No terminal:
As we see in the image below, the input always returns a value of type string (str), even
whether it's an integer or a float
In the code: No terminal:
To correct this, we can use the function int() to convert it into an integer.
cast() to convert to a real number
21
STRINGS
WHAT IS STRING?
It is a sequence of one or more characters. To name a string, in Python
we can use single quotes (‘...’) or double quotes (‘’...’)
CONCATENATION
To concatenate two or more strings, the + operator is used.
In the code:
Space Space
No terminal:
a b c
Space
MANIPULATION
In Python, there are some functions/methods to help with string manipulation. They will be
listed below are the main methods
len()
Returns the length of the string
22
capitalize()
Return the string with the initial capital letter.
Attention: There are some functions that will follow the string separated by a dot,
like in the example below
count( )
Returns how many times a character (or sequence of characters) appears in a string
startswith( )
Return True or False. Check if a string starts with a sequence of characters.
oh no
endswith()
Returns True or False. Checks if a string ends with a sequence of characters.
or not
isalnum()
Returns True or False. Checks if a string contains letters and/or numbers
23
isalpha()
Return True or False. Check if a string contains only letters.
islower()
Return True or False. Check if a string is entirely in lowercase.
isupper()
Returns True or False. Checks if a string is entirely in uppercase.
lower()
Transform a string into only lowercase characters
upper( )
Transform a string into only uppercase characters
swapcase()
Invert the content of the string (uppercase/lowercase)
24
title
Transform The Initial Of All Letters To Uppercase
split( )
Transform a string into a list, using spaces (default) as a reference.
replace(s1, s2)
Replace in the string, the part s1 with s2
find()
Returns the index of the first occurrence of a character. If there is none, returns -1
0 1 2 3 4 5 6
ljust( )
Adjust the string to a minimum length. If necessary, add spaces to the right.
rjust()
Adjust the string to a minimum length. If necessary, add spaces to the left
25
center()
Adjust the string to a minimum length. If necessary, add spaces on the left and the
right
lstrip( )
Remove all whitespace from the left side.
rstrip()
Remove all white spaces from the right.
strip()
Remove all spaces on the left and right
Slicing
With the slices, we can call several character values by creating an interval of
index numbers separated by colons [x : y]:
When creating a slice, the first index number is where the slice starts (inclusive),
and the second number of the index is where the slice ends (not included)
26
NUMBERS
ARITHMETIC OPERATORS
Returns the result of the operation
+ SOMA
- SUBTRACTION
* MULTIPLICATION
/ DIVISION
% REST OF DIVISION
** POWER
COMPARISON OPERATORS
Return True or False
< LESS
> LARGER
== SAME
!= DIFFERENT
27
LOGICAL OPERATORS
Returns True or False
NOT INVERT A
CONDITION
28
COLLECTIONS
LIST
WHAT IS A LIST?
A list is a data structure in Python that is an ordered sequence of
mutable elements. Each element or value that is inside a list is called a
item. Just as strings are defined as characters in quotes, lists are
defined by having values between brackets [ ]
Lists can contain any type of value: integer, float, string, including other lists.
tuples and dictionaries that we will see later.
To change an item in the list, you can change it using the index number, as in
image below
29
MANIPULATION
Now we will look at functions used to manipulate a list
len( )
Returns the size of the list
min( )
Returns the minimum value of the list
max( )
Returns the maximum value of the list
sum( )
Returns the value of the sum of all elements
append()
Insert a value at the end of the list
extend()
Insert a list at the end of a list
30
of
Remove an element from the list, given its index
in
Check if a number is in the list
sort( )
Sort in ascending order
reverse()
Invert the order of the elements
OPERATIONS
Concatenation
To combine two or more lists, we can use the + operator.
Repetition
To repeat a list, we can use the * operator.
31
Slicing
The slicing of the list occurs similarly to the slicing of strings.
range( n )
Generate an interval from de0an-1
range(i, n)
Generate a range of deian-1
range(i, n, p)
Generates an interval of deian-1 with step
32
TUPLE
WHAT IS A TUPLE?
A tuple is a data structure in Python that is an ordered sequence of
elements, just like a list, but immutable. Just like lists are defined
for having values in brackets [ ], tuples are defined by having values in
parentheses
The lists can contain any type of value: integer, float, string, including other tuples.
lists and dictionaries.
33
DICTIONARY
WHAT IS A DICTIONARY?
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with braces { } and have keys and values:
Nome_do_dicionário
value1
value2
value3
...
valorN
}
Examples:
Form 1: Form 2:
OPERATIONS
Examples:
del
Remove an item from the dictionary
keys( )
Get the keys of a dictionary
values( )
Get the values of a dictionary
34
STRUCTURES
OF DECISION
IF STRUCTURE
LOGIC
entry
True EXECUTE A
CONDITION
COMMAND
False
does nothing
SYNTAX
if<condition> :
<command block>
EXAMPLE
To understand what is happening here, let's observe the following: we have the variable
value which is equal to 10. In the next line we have the condition for the if: the value is greater than
5? Yes, so it returns TRUE and the line below is executed
As we can see, the value that was 10 has been multiplied by 3, now the variable value is
equal to 30.
35
IF...ELSE STRUCTURE
LOGIC
entry
True PERFORM A
CONDITION
COMMAND
False
EXECUTES A
COMMAND
SYNTAX
if<condition>:
command block
else:
<command block>
EXAMPLE
Example 1 Example 2
In the first case, we see that the value (10) is greater than 5, so it returns TRUE and the value 0 is
assigned to the variable value
In the second case, the value (3) is not greater than 5, so it returns FALSE and the value 1 is
assigned to the variable value
36
IF...ELIF...ELSE STRUCTURE
LOGIC
entry
True EXECUTE A
CONDITION
COMMAND
False
True EXECUTE A
CONDITION
COMMAND
False
EXECUTE A
COMMAND
SYNTAX
if<condition> :
<command block>
elif:
<command block>
... You can put as many as you want.
elif:
<command block>
else:
<command block>
EXAMPLE
As we see in the example to the side, he keeps testing
each condition at a time...
Is the value 1? NO
Is the value 2? NO
the value 3 3? YES
so print on the screen 'dog'
comes from the if structure
37
STRUCTURES
ON REPETITION
WHILE
LOGIC
entry
False
CONDITION CLOSE
True
EXECUTE A
COMMAND
SYNTAX
while<condition> :
<command block>
EXAMPLE
38
FOR
LOGIC
entry
ITEM NO False
SEQUENCE CLOSE
True
EXECUTE A
COMMAND
SYNTAX
A for loop is used to iterate over a numerical sequence, using the function
range() or about lists, tuples, dictionaries, and strings.
EXAMPLE
39
FUNCTIONS
WHAT IS FUNCTION?
A function is a block of code that is only executed when it is called. You can
pass data, known as parameters, to a function. A function can
return data as a result. Functions are widely used to avoid writing the
same algorithms several times
SYNTAX
def function_name(<parameters>) :
<command block>
EXAMPLE
argument
40
SCOPE OF VARIABLES
Variables that are defined within a function body have a local scope.
those defined outside have a global scope. This means that local variables can
can only be accessed within the function in which they are declared, while the variables
globals can be accessed throughout the body of the program by all functions.
RETURN OF VALUES
The return statement in Python is a special statement that you can use within
a function to send the result of the function back to the user. An instruction of
return consists of the keyword return followed by an optional return value. The value
The return from a Python function can be any Python object.
41
BIBLIOGRAPHY
What is Python, why everyone should learn it, and its advantages. Available at:
What is Python? Advantages
e-why-everyone-should-learn/. Accessed on: January 7, 2021.
42