0% found this document useful (0 votes)
24 views

Python Lessons

Uploaded by

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

Python Lessons

Uploaded by

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

PYTHON LESSONS

How to write a sentese:


Print (“Hello world”); the quotacion marks can be write as ‘ or “

will be show: Hello world

In a sentese if you want to add a ‘ mark inside a print and not and the sentese use ‘\

How to jump a line:


You only will add the \n at the and of the sentese you want to end, it can be use inside the
print

How to add two senteses (String concatenacion):


If you have two senteses in diferente words you can add + in the between so the can show as
the were only one print

To add a space in the sentese or you can add a spece at the and of the fist print word ou at the
begining of the second or do this:

Print (“Hello” + “” + “world”)

Will be show: Hello world

How to use + for numbers:


If you write two numbers with a + in between, for exemple, 7+4 the answer will be 74

If used the print, for exemple, print (‘7+4’); will be show: 11

If the sentese is writen like that print (‘7’ + ‘4’); will be show: 74

How to create a variable:


To create a variable must to write a word followed by a igual, Reading like receive, after the
igual add na informacion which will be related to the funcion

Ex.:

Name = (‘Heloisa’)

hight = 1.64

The variables will be “name” and “hight”, if writen a frase use quotacion marks and if the
format it is ‘int” or “float” use just numbers

When you creat a variable use lower case, once python see the diference between capital
letter and lower case.

When you write a “float” remember to use a dot insted to a comma.


How to prepare Python to recive na information:
In that case we will be using a variable and an “input” insted of “print”:

Variable = input (“Type your name”)

Will be show: Type your name; with the possibility to type an answer

To limitate the answer to right the type use “int”, ”float’,”str” e “bool” before the “input”:

V= int(input(“Type a number: “))

How to add a commentary:


To write a commentary just use a “#” at the beginning of the line, that so will be no used at the
resto f the code.

To do that automatically you can select the frase and then press Ctrl+/; to undo press Ctrl+z

How to switch values:


If you want to switch values for exemple:

A= input (‘Type it down a number: )

B = input (‘Type it down a number: )

In with, A igual to 1 and B igual to 2 for exemple. If you want to this is what shown:

Print(A); and show 2 (B)

Print(B); and show 1 (A)

You must to creat a new variable (c), and write this sequence :

C=A

A=B

B=C

Primitive types:
 Interger:
This type is use to refere to whole numbers
Ex.: 1; 34; 6749
 Float:
This primitive type is use to real numbers or also call numbers with floating dots.
Ex.: 2.5; 7.89; 34.1
If you want to restrict a Division with to many numbers after the dot use this:
Format(math.pi,’.f2’)
Will show, 3.14
That way the restriction will be to 2 numbers after the dot.
 Strings:
They are related to the caractere values, witch can be used to “int” or “float” in a more
open situacion
Ex.: 1.2; ‘Hello’ ;’0’; -9
 Boolean:
They apresente only two values (True or False) the fist letter is writen with a capital
letter
Ex.: True; False

How to change a primitive type into another:


This change is conveniente when you want to mix two or more primitive type, that
may end in to an erro. To change you must follow the steps:

Name = len (input(‘What is your name?’))


Name2 = str (Name)
Print (‘Your name has’ + Name2 + ‘characters’)

Mathematical operation on Python:


To represente the 4 mathematical operations use:
 Addition:
To use this operacion use + symbol
 Subtraction:
To use this operacion use - symbol
 Multiplication:
To use this operacion use * symbol
 Division:
To use this operacion use / symbol
The primitive type of a Division is Float
 Exponents:
To use this operacion use ** symbol
 Whole Division:
To use this operacion use // symbol
 Rest of Division:
To use this operacion use % symbol

Order of priority of the mathematical operation on


Python:
To make more easy to remember think on the PEMDASLR:
1) Parentheses;
2) Exponents;
3) Multiplication and Division;
4) Addition and Subtraction;

The LR part is to remember the order of Reading is from left to right.


Number manipulation:
To manipulate a value using a using it’s previous values do this:

Score = 0

Score += 1

Print(score)

From that exemple the value “score” will be sum to 1. The + can be replaced for
-,*, / , // ou % based on what you want.

F – String:
As you alread know in a line of Pyhton all the primiteve type must be the same and
that so you must change the type to fill in the line, as explaned before. But thats a hack
witch you just need to write and f before de sentese in the print and you can mencione
any type you want:

Score = 0

Height = 1.86

Iswinning = True

Print(f ‘Your score ir {Score}, your height is {Height} and your winning ir {Iswinning}’)

That way that will be any more erros on you code

Text manipulation:
If a phase is type in python, this phase is going to be read by the softwere as micro
spaces being fill by strings and each being knowledge by a number starting by 0 and
groing to the last one. The empty spaces are also count.

phase = ‘Python lessons’

Due that we can make a couple manipulations:

 phase[8], will show ‘e’


 phase[7:14], will show ‘lessons’
* add one more number on the last number, because python is goint to read one mere
 Phase[7:14:2], will show ‘lsos’
 Phase[:6], will show ‘Python’
 Phase[7:], will show ‘lessons’
 * When the number isn’t written at the beging the stoftwere will start to count to 0
and if isn’t written at the end the reverse process will happen.
Condicional operacions (if/else):
Using the operato,s ‘if” and “else” you can make the program shape into te format
you want, you can use in this format:

Height = input(‘What is your height?\n’)

If height > 120:

Print(‘You can rid the rollercoaster!’)

Else:

Print(‘Sorry, you don’t have the minimun height to ride the rollercoaster’)

Depending on the answer of the height the respond will change.

Comparison operators
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

IF/ELIF/ELSE
You can add the conditional text inside a conditional text.

If that is one more condicional use ‘elif’ between the if and else, the many times you
want.

If condition1:

do A

elif condition2:

do B

else:

do C

IF/IF/IF
That will be cases in with the conditional 3 will depend on conditional 1 and 2, like:

If condition 1:

If condition 1.1:

Elif condition 1.2:


Else condition 1.3:

If condition 3:

If condition 3.1:

Else condition 3.2:

Else:

LOGICAL OPERATORS:

 The ‘AND’ logical operator


To combine two diferentes conditionals like
If A and B == 0:
If them both are TRUE then the result will be TRUE
But i fone of them are FALSE then the result will be FALSE

 The ‘OR’ logical operator


If one of then is FALSE then the result will be FALSE
If A or B == 0:
 The ‘NOT’ logical operator
If the operator if FALSE it will return TRUE and if is TRUE it will return FALSE
If not A == 0:

It is import to bring it up that logical operator if is an variable(condition) can’t not been


written like this:

If condition == ‘True’ or ‘true’

This may cause an erro, do this insted:

If condition == ‘True’ or condition ==’true’

Randomisation:
That’s a cuple of funcions you can acess in the Python module, fist type on you code:

Import random

 Randint(a,b)
Will return you an integer random number between a and b (a < b, or else
erro)

A = random.randint(100,200)
 Random
Will return you na float random number between 0 and 1 (not included)

 Random.sample
To have random number from a list, in witch you chose how many numbers do
you want, write this:

Random.sample(list,num_elements)

In witch “list” is the list you want to use the elements from and the
“num_elements” the quantites of elements from the list you want.

List:
The format, a variable, an igual, square brackets and the itens you want in
your list
Variable = [‘item1’, ‘item2’]
Lists can can make your life easy by not having to create multiples variables.
If you do this:
Print(variable[0])
This will lead to the answer item1
If you write for exemple -1 the return will be item2, once it start to count from
back to front.

You can change an item from your list doing:


Variable[0] == ‘Cookie’

To add one more item you can use this funtion:


Variable.append(‘item3’)
If you want to add more than one use:
Variable.extend(‘item3’,’item4’)
To split a string(word) into letters do:
Word = list(word)
P.S: to make it back (to a normal string) use:
New_variable = ‘ ’.join(word)
To find if the element belogs to a list use:
Variable.index(variable2)

Nested list:
It means on Python to put two lists inside one, for exemple

Fruits = [‘banana’, ‘apple’,’strawberries’,’peachs’,’berries’]


Vegetables = [‘kale’,’tomatos’,’celery’,’potatoes’]
Dirty_dozen = [Fruits, Vegetables]
Print(Dirty_dozen)

 [ [‘banana’, ‘apple’,’strawberries’,’peachs’,’berries’],
[‘kale’,’tomatos’,’celery’,’potatoes’]]

If you write on print this way


Print(Dirty_dozen[0][1])
Will show
Apple
Because the fist square brackets means witch list you want and the second
one it is the position of the item you want to print. If that’s no seconf square
brackets the program will print the whole list selected.

For loop:
The tool FOR on python is a structure for repetition and you can write like this:
For name in fruits:
On the name part you can write any name to represent an single item.
On the vegetables part you call and variable that you have on your code.
If is and list, you code will this way:
Fruits = [‘apple’,’peach’,’pear’]
For name in fruit:
Print(name)
 Apple
 Peach
 Pear

Range:
If you want to generete a range of numbers, use:

For number in range (a,b):

Print(number)

 A
 A+1
 ...
 B-1

”a” must be smaller than “b” and “b” won’t be considered

If you want to add soe steps in the range do this:

for number in range (a,b,c):

print(number)

 A
 A+ C
 ...

Functions:
The format of a function is it’s name follow by “()”.
But if you want to define your won function use the keyword def to define a fuction
follow by the name of that function and na colon, for exemple:
Def my_function():
That so everything that come after that line indented belong to “my_function”.
To call that new function, do this:
My_function()
Functions is the simples way to refering to multiple tasks at the same time

While loops:
The loop that will continue going while a particular condition is looping.
For exemple:
While something_is_true:
#Do something repeatedly

Functions with input


To add a input in a function use it's structure more expecific the parenteses to add a
variable.
ex.:
def my_function(name):
print(f'Hello {name}')

my_function('Heloisa')
* When you call the function adding an information to the parenteses the name will be
replaced
to the new one
*The NAME variable in the exemple is call PARAMETER and the HELOISA statement it's
call ARGUMENT

Position Argument
You can add more than one function just by using a comma, for exemple:
my_function(name, location)
*remember the position is important

Keyword Arguments
In order to not confuse the sequence you can you an keyword argument, for exemple:
my_function(c=3, a=1, b=2)

Dictionary
Dictionany in Python is composte by the “KEY” with is equivalente to the name in the
regular dictionary, followed bu the “VALUE” that represent the definition of the key.
The syntax looks like this:
Dictionary = {Key : Value}
Ex.:
{“Bug”: “An erro in a program that prevents the program from running as expected.”,
“Function”: “A piece of code that you can easily call over and over again.”,
“Loop”: “The action of doing something over and over again.” }
PS.: to add more Keys and values, use a comma (,)

To call any key of the dictionary, use the formula:


Dictionary[“Bug”]
Or
Print(dictionary[“Bug”])
The last one will print the value of the key
*If you type the word wrong will show you an erro call KeyErro: ‘wrong word’

To add a New key, use the metodo:


Dictionary["Loop"] = 'The action of doing something over and over again'

To wipe an existing dictionary:


Dictionary = {}

Edit an item in a dictionary


Dictionary ["Bug"] = 'a moth in your computer'
Print(dictionary)

Loop through a dictionary, use


For thing in dictionary
Print (thing)

Keys names
For key in dictionary
Print (key)
Print(dictionary[key])

Nesting List and Dictionary


Inside a dictionary you can write a list or a dictionary as well to make it more complex
and more usable, structure:

Dictionary = {
key : [list],
Key2 : {dictionary}
}

List:
Capitals = {
“France”: “Paris”
“Germany”: “Berlin”
}

Exemple of nesting a list in a dictionary:


Travel_log = {
“France”: [“Paris”, “Lille”, “Dijon”]
“Germany”:
[“Berlin”,”Hamburg”,”Stuttgart”]
}
*You can nest a list inside a list

Exemple os nesting a dictionary in a dictionary:


Travel_log = {
“France”: {“cities_visited”: [“Paris”,
“Lille”, “Dijon”]}, {“total_visits”:12}},
“Germany”: {{“cities_visited”:
[“Berlin”,”Hamburg”,”Stuttgart”]}, {“total_visits”:5}
}
Nesting a dictionary inside a list, structure:
Dictionary = [{
key : [list],
Key2 : {dictionary}
}
,{ key : Value,
Key2 : Value
}]
Exemple:
Travel_log = [{
“Country”:“France”:
“cities_visited”: [“Paris”, “Lille”,
“Dijon”],
“total_visits”:12
},
{
“Country”:“Germany”:
“cities_visited”:
[“Berlin”,”Hamburg”,”Stuttgart”],
“total_visits”:5
}]

P.S.: When you use a for loop in a dictionary, the loop is going to each of the Keys. To refere
the value, do this

For key in dictionary:

New_variable = dictionary[key]

Use this website to decode your code : https://pythontutor.com/

Functions with outputs


To use an output in order to save a variable insted of this:

Def my function():
Result = 3*2

Return

Do this:

Def my function ()
Return 3*2

The return must Always be on the end, Other wise it won’t work

If you add na argument on a def function you can add more than one return, witch will be
releted to this argument in particular

Docstrings
When you pass you mouse on functions on python you can see the image below

To create this effect on a created function, jump to the fist indented line write 3 quotations
marks then the docstrigs and then close it with 3 quotations marks.

Print vs Return
The print operation reduce it self to show a phase or an input inside of a variable.

The return can do those things but also use an output and use as input to another variabe
giving another output.

Basically the return statement can turn the code more complex and conected to it self.

Recursions
This is as method that you call a function inside a function, then you can use it as a loop

Be careful! It can turn into a infinit loop if you don have a complex code, like just a print.

Scope
Local scope: In a function, if you call a variable inside a function it work if you call it outside
will give you a NameErro telling the variable wasn’t define
Global scope: To create a global scope you must create a variable outside the function. On the
exemple below, the answer to “drink_potion()” is 10 and “print(player_health)” is also 10,
once they follow the global scope over the local scope.

P.S: if the function “drink_potion()” was indeted inside Other function, the local scope
“potion_strength” couldn’t be call giving NameErro and that the variable wasn’t define.

To correct that print the variable in the indented function.

To modify a global scope: you must call it inside the function, to do that you must write
‘global’ follow the name of the variable. Then you can modify the way you want.

You can also modify a global scope using the return


How to create a personalized:
Use this link to create a tittle :
https://patorjk.com/software/taag/#p=display&f=Grafite&t=Type%20Something%20
Then copy your new tittle, then create a new file (art.py). Inside this new file create a
variable then paste your tittle and put it between ‘’’.

How to find and fix an erro on your code


1. Describe the problem

Try the code or function on and check the results. Once it got wrong, ask questions about
the function like what the function supose to do? the results are aperring on the right time
and the right way?

2. Reproduce the bug

This type of erro shows after you run multiple times your code.

Remember to read the IndexErro.

3. Play computer and evaluate each line

When your code it’s not runnig, read the code as if you were a computer then try to find
the erro.

4. Fix the erro

Read the TypeErro and try undestand the problem or copy and paste into google

5. Print is your friend

When you have no sure of the value of the input you have, use the print statement so you
can see whats goint on.

6. Use the debugguer

Use this website to undestand what happening to your code:


https://pythontutor.com/visualize.html#mode=edit

7. Take a break

8. Ask a friend

9. Run often

Run your code after Every change in your code, so it can make more simple to visualize the
erro

10. Ask StackOverflow


Site in each you can ask to others developers to help you:
https://stackoverflow.com/questions/tagged/python

Object Oriented Programming (OOP)


It’s a pattem of programing witch organizes the codes round objects, that is a instance of a
class.

Objects(have or attibutes): is a fancy word to a variable

Class(can do or mathods): made of functions

Python Packages:
Site: https://pypi.org/

You might also like