0% found this document useful (0 votes)
14 views42 pages

Python From Scratch

1) The document provides instructions on how to install Python and PyCharm on different operating systems and introduces basic programming concepts in Python such as variables, strings, numbers, collections, and decision and repetition structures. 2) After installing Python and PyCharm, the document explains what variables, strings, numbers, lists, tuples, dictionaries, if/else structures, and while and for loops are. 3) The document also discusses why to learn Python, its main applications such as data science, machine learning.
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)
14 views42 pages

Python From Scratch

1) The document provides instructions on how to install Python and PyCharm on different operating systems and introduces basic programming concepts in Python such as variables, strings, numbers, collections, and decision and repetition structures. 2) After installing Python and PyCharm, the document explains what variables, strings, numbers, lists, tuples, dictionaries, if/else structures, and while and for loops are. 3) The document also discusses why to learn Python, its main applications such as data science, machine learning.
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

HOW TO PROGRAM IN

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:

In Python (Pandas Library):

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.

LARGE COMPANIES USE


Python is a programming language widely used in various companies around the world, including by
large companies like Google, Instagram, Amazon, Spotify, Facebook, Dropbox,
NASA, Electronic Arts, and Disney

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.

The installation is quite easy:


1. Activate the 'Add Python to PATH' option
Click on "Install Now"

Wait for the installation to finish

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:

$ sudo apt-get install python3

To install the package manager pip, type in a terminal:

$ sudo apt-get install python3-pip

Yum
To install Python 3, type in a terminal:

$ sudo yum install python3

To install the package manager pip, type in a terminal:

$ yum -y install python3-pip

08
MacOS
If you have macOS version 10.2 or higher, you probably already have some
installed version of python.

To check, type in the terminal:

$ which python or $ which python3

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.

To install the command line tools, type in a terminal:

$ xcode-select --install

To install pip, type in a terminal:

$ sudo easy_install pip

To update pip, type in a terminal:

$ sudo pip install --upgrade pip

To install Homebrew, type in a terminal:

$ ruby -e "$(curl -fsSL [Link]

To install Python 2, type in a terminal:

$ brew install python

To install Python 3, type in a terminal:

$ brew install python3

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

Choose the community option and click on download

10
Welcome to PyCharm: Click on next

Choose install Location: keep the destination and click 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

On the next screen, we will see the progress of the installation.

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.

Click on the '+' in the right corner

Choose the System Interpreter option and click OK

Now, just click OK again and PyCharm is ready to be used!

14
LINUX
VIA SNAP
Open a terminal

Install the PyCharm community IDE using this command:

sudo snap install pycharm-community --classic

Install the PyCharm professional IDE using this command:

sudo snap install pycharm-professional --classic

Update the PyCharm IDE snap (later if necessary), use this command:

sudo snap refresh pycharm-community --classic

you

sudo snap refresh pycharm-community pycharm-professional

To uninstall PyCharm, use this command:

sudo snap remove pycharm-community pycharm-professional

UBUNTU 16.04, 14.04, LINUX MINT 18, 17 and its derivatives


Open a terminal

Add the app repository with the following command:

echo "deb [Link] zesty main" |


sudo tee /etc/apt/[Link].d/[Link]

Download and add the GetDeb repository key with the command:

wget -q -O - [Link] | sudo apt-key add -

Update Apt with the command

sudo apt-get update

15
To install the PyCharm community IDE use this command:

sudo apt-get install pycharm

To install the PyCharm Professional IDE, use this command;

sudo apt install pycharm-professional

To uninstall, use the command:

sudo apt remove --autoremove pycharm pycharm-professional

UBUNTU 17.04, 16.10 and its derivatives


Open a terminal
To add the program repository use the command:

sudo add-apt-repository ppa:viktor-krivak/pycharm

To update the package manager, use the command:

sudo apt-get update

To install the PyCharm Community IDE, use the command:

sudo apt-get install pycharm

To install the PyCharm Professional IDE, use the command:

sudo apt install pycharm-professional

To uninstall, use the command:

sudo apt remove --autoremove pycharm pycharm-professional

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.

Click on the .dmg file. PyCharm should then start installing.

Drag and drop the application into the Applications folder.

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

WHAT ARE VARIABLES?


In programming, a variable is a storage location (identified by a name) that can hold data.
memory address paired with an associated symbolic name, which contains
some known or unknown quantity of information referred to as a value.

RULES FOR DECLARING VARIABLES


1. Start the variable name with a LETTER or UNDERLINE.

Example = 10
_Exemplo = 10
0Example = 10
Example = 10

2. The rest of the variable can contain letters, numbers, and underscores.

Exemplo_com_0 = 10

3. Python is CaseSensitive, which means that it distinguishes between lowercase and


uppercase.
NUMERO = 10
numero = 5
NUMBER≠number

4. You cannot use reserved words of Python as variable names.


‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’,
‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘nally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’,
‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’

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.

FLOAT is a number with decimal places, example: 1.50, 3.55, 5.00.

STRING - is one or more characters, must be assigned to the variable with single quotes or
pairs

BOOLEAN - it is true (True) or false (False)

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

ATTENTION: THE INDEXING


PYTHON STARTS AT ZERO
EX: i m p e r i o

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)

from 0 (inclusive) to 5 (exclusive) string indexing


i m p é r i o d o p r o g r a m a d o r
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
up to index 8 (not included)

from index 5 (inclusive)

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

<= LESS THAN OR EQUAL TO

> LARGER

>= GREATER THAN OR EQUAL TO

== SAME

!= DIFFERENT

27
LOGICAL OPERATORS
Returns True or False

NOT INVERT A
CONDITION

AND ALL THE CONDITIONS


MUST BE TRUE

OR JUST NEEDS ONE


TRUE 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 [ ]

In Python, lists are declared as follows


[ value1, value2, value3, ..., valueN ]

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.

CREATION WITH RANGE


Range() is a function that defines a range of integers. Using it together with
The function list( ) allows you to create a list with the values of a range.

The range function can take 3 parameters.

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

In Python, tuples are declared as follows


Tuple_name = ( value1, value2, value3, ..., valueN )

The lists can contain any type of value: integer, float, string, including other tuples.
lists and dictionaries.

It is not possible to change a tuple

One use of a tuple is unpacking, which allows assigning the elements.


stored in a tuple with various variables.

33
DICTIONARY
WHAT IS A DICTIONARY?
Dictionaries are used to store data values in key:value pairs.

A dictionary is an unordered, mutable collection that does not allow duplicates.

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

To understand what happens here, let's observe the following:


Initially we have a variable that has a value of 0, after that we will enter the while loop
It will check if the condition (a < 10) is true. If it is true, it executes the command. In case a
it was less than 10, so it prints the value on the screen and adds 1, and repeats this cycle
until it reaches 9. When it reaches 10, it reads the condition and returns false, therefore the loop
while it closes.

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.

forxinrange( ) : forxin[ list ] :


<command block> command block

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

PARAMETERS AND ARGUMENTS


The terms parameter and argument can be used for the same thing: information
what are passed to a function. A parameter is the variable listed in parentheses
after the definition of the function. An argument is the value sent to the function when it is
call.
parameter

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.

Example with local variable:


As we see, we cannot access the variable result outside the function.

Example with global variable:


By declaring the variable as global, we can access the variable 'result' outside.
of the function

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

INSTALLATION OF PYTHON. Available at: [Link]


do-python/40643. Accessed on: January 7, 2021.

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.

Linux Installation. Available at: [Link] Accessed on:


January 7, 2021

HOW to install pycharm on mac. Available at: [Link]


install-python-and-pycharm-on-mac. Accessed on: January 7, 2021.

How to create variables in Python. Available at: [Link]


variables-in-python/. Accessed on: January 8, 2021.

PYTHON Dictionaries. Available at: [Link]


[Link]. Accessed on: January 09, 2021.

42

You might also like