Sei sulla pagina 1di 30

Chapter 2

Python Fundamentals
Mathematical operators
+ - adding
- - subtraction
* - multiplication
/ - division
% modulo – rest of division
** - raising to power
// floor division
Initialization and auto-operating operators
= c=a+b
+= c += a - equivalent with: c = c + a
-= c -= a - equivalent with: c = c - a
*= c *= a - equivalent with: c = c * a
/= c /= a - equivalent with: c = c / a
Round
Round() – can make go to either supperior or lower value, based on the closest margin of
the value that is passed as an argument

>>> round(3.3)
3
>>> round(3.6)
4
Ceil & Floor
Ceil – rounds to the closest superior value, without considering the decimal
Floor – rounds to the nearest inferior value

Ceil & Floor belong to the module - math. In order to use methods and variables from the
module we need to import it in our code.

>>> import math


>>> math.ceil(3.3)
4
>>> math.floor(3.3)
3
Printing on a new line
>>> m = "This string\nspans multiple\nlines"
>>> m
'This string\nspans multiple\nlines'
>>> print(m)
This string
spans multiple
Lines
>>>
Printing on multiple lines without \n
>>> m = """This is
>>> .... a multiline string"""
>>> m
'This is\na multiline string'
>>> print(m)
This is
a multiline string
>>>
Printing using tab (\t)
>>> m = "test1 \t test2"
>>> print(m)
test1 test2
>>>
Priting quotations marks and
apostrophes
>>> m = "test \'"
>>> print(m)
test '
>>> m = "test \"„
>>> print(m)
test „
>>> m = 'test "‘
>>> print(m)
test "
Printing backslash
>>> print(“This is the proper way of printing \\")
This is the proper way of printing \

>>> print(“This isn’t the proper way of printing backslash \")


File "<stdin>", line 1
print(" This isn’t the proper way of printing backslash \")
^
SyntaxError: EOL while scanning string literal
Printing raw strings
>>> m=r'C:\Users\Merlin\Documents\Spells‘
>>> print(m)
C:\Users\Merlin\Documents\Spells
>>> m=r"test'test„
>>> print(m)
test'test
>>> m=r'test"test‘
>>> print(m)
test"test
>>> m='test\test'
>>> print(m)
test est
Decision making operators
== equality checking operator
!= inequality checking operator
< “smaller than” operator
> “greater than” operator
<= “smaller or equal than” operator
>= “greater or equal than” operator

Q: What will be the data-types returned by this operators?


Decision making operators
>>> g = 20
>>> g == 20
True
>>> g == 13
False
>>> g != 20
False
>>> g != 13
True
>>> “telacad” == “telacad”
True
Logical operators
and – returns True if expressions on both left and right are True
or – returns True if either the left or right operators are True
not – changes the bool value
Logical operators
print((9 > 7) and (2 < 4)) => True

print((8 == 8) or (6 != 6)) => True

print(not(3 <= 1)) => True


IF Decision control structure
if expression:
print(“The expression is true”)

• The expression is converted to bool and evaluated


• We will notice that the preffered intendation in Python contains 4 spaces (TAB)
IF Decision control structure
>>> if True:
print(“the expression is true")
>>>
the expression is true

>>> if False:
print(“the expression is false")
IF Decision control structure
>>> if bool("telacad"):
print(“expression was evaluated to True")
>>>
expression was evaluated to True
>>>
>>> if "telacad":
print(" expression was evaluated to True")
>>>
expression was evaluated to True
>>>
Nesting IFs
>>>if height > 50:
print(“Height is over 50")
else:
if height < 20:
print(“Height is below 20")
else:
print(“Height is between 20 and 50 ")
>>>
Height is between 20 and 50
IF-ELIF-ELSE Structure
>>> if height > 50:
print("Height is over 50 ")
elif inaltimea < 20:
print(" Height is below 20")
else:
print("Height is between 20 and 50 ")
>>>
Height is between 20 and 50
>>>
• This structure MAY offer more clarity to the code
Repetitive control structure
WHILE structure
>>>while expression:
print(“loop with be executed as long as the expression is evaluated to True”)

Expression is converted to bool data type and evaluated


WHILE structure
>>> c = 5
>>> while c:
print(c)
c -= 1
>>>
5
4
3
2
1
Break & continue in loops

Break – exits the current loop and is continuing with the code that follows after the while
structure
Continue – interrupts the current iteration of the loop and jumps to the next one
Break
>>>while True:
if expressions:
break
print(“We’re reaching this point after breaking the loop”)
Continue
>>>while expression_1:
if expression_2:
continue
print(“This text will not be printed”)
c += 1
Repetitive control structure
FOR Structure
>>> for i in range(5): (we are going through a range of numerical values)
print(i)
>>>
0
1
2
3
4
>>>
FOR Structure
>>> # Measure some strings:
>>> words = ['cat', 'window', 'defenestrate']
(we’re parsing through a sequence of strings)
>>> for w in words:
print(w, len(w))
>>>...
cat 3
window 6
defenestrate 12
>>>
Exercises

1. Use the WHILE loop in order to repeatedly read user input data, until the string that is read is
“telacad”. When this condition is met, exit the loop and print the following message: “End or
program”.

2. Use a repetitive strucutre to read values from the user. Convert those values to integer and
check if they are greater than 2. If they are not, ask the user to input the value once again. If
the value is greater than 2, calculate the sum from 1 to that value (1 +2 +3 …+ n).

3. Read an input string and verify if it’s equal to “telacad”. If the value is different, ask the user to
enter strings until one of them is equal to“telacad”. When the entered string will have the
desired value, print the elements of the following list in a single string, concatanted with
spaces [“telacad”, “over 13 years experience”, “teaching”,“online courses”] .
Exercises
4. x = a numerical value set at the beginning of the program. If the data type of x is integer, add
3; if the data type is float, divide x by 2 and if it’s imaginary/compex, display the real part,
imaginary part and calculate the module.

HINT: Use the isinstance() method to verify the data type of x.

5. Read a value from the user and perform the following verifications:
• Check to see if the value is numerical; if it’s not, print an error message
• If the value is greater than 10 print “the value is greater than 10
• If the value is between 5 and 10 print “the value is between 5 and 10”
• If the value is below 5 print “the value is below 5”
Optional exercises
1. Verify if a value read from the user is odd or even.
2. Verify if a value read from the user is either prime or not prime.
3. Display the first 5 values from the Fibonacci series without using recursion – only loops
(for, while)

Potrebbero piacerti anche