Python Lessons
Python Lessons
In a sentese if you want to add a ‘ mark inside a print and not and the sentese use ‘\
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:
If the sentese is writen like that print (‘7’ + ‘4’); will be show: 74
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.
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”:
To do that automatically you can select the frase and then press Ctrl+/; to undo press Ctrl+z
In with, A igual to 1 and B igual to 2 for exemple. If you want to this is what shown:
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
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}’)
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.
Else:
Print(‘Sorry, you don’t have the minimun height to ride the rollercoaster’)
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:
If condition 3:
If condition 3.1:
Else:
LOGICAL OPERATORS:
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.
Nested list:
It means on Python to put two lists inside one, for exemple
[ [‘banana’, ‘apple’,’strawberries’,’peachs’,’berries’],
[‘kale’,’tomatos’,’celery’,’potatoes’]]
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:
Print(number)
A
A+1
...
B-1
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
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 (,)
Dictionary = {
key : [list],
Key2 : {dictionary}
}
List:
Capitals = {
“France”: “Paris”
“Germany”: “Berlin”
}
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
New_variable = dictionary[key]
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 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.
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?
This type of erro shows after you run multiple times your code.
When your code it’s not runnig, read the code as if you were a computer then try to find
the erro.
Read the TypeErro and try undestand the problem or copy and paste into google
When you have no sure of the value of the input you have, use the print statement so you
can see whats goint on.
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
Python Packages:
Site: https://pypi.org/