Operators and Operands

aqui puedo poner apuntes o cualquier texto

Floor Divsion or Integer division //


In [27]:
1//2


Out[27]:
0

In [28]:
#should equal 33.33
100//3


Out[28]:
33

In [6]:
#should not equal 0, but it does
59//60


Out[6]:
0

True division /


In [9]:
1/2


Out[9]:
0.5

In [10]:
100/3


Out[10]:
33.333333333333336

In [11]:
59/60


Out[11]:
0.9833333333333333

Modulo %

Yields the remainder from the division of the first arg by the second. Basically, for simple calculations - returns the remainder. It can be used to determine divisibilty. Is 25 divisible by 5?


In [29]:
25 % 5


Out[29]:
0

In [22]:
23 % 5


Out[22]:
3

In [38]:
nums = [x for x in range(0,100)]

for entry in nums:
    if not entry % 5 :
        print(entry)


0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95

Square **

Unlike other programming languages, Python uses ** and not ^


In [23]:
5 ** 2 # or 5 squared


Out[23]:
25

In [26]:
nums = [0,1,2,3,4,5]
nums_squared = [element ** 2 for element in nums] # list comprehension
nums_squared


Out[26]:
[0, 1, 4, 9, 16, 25]

Data Types

  • Numeric Types: ints, floats, complex
  • Text Sequence Types: str (already saw this)
  • Sequence Types: list, tuple, range (coming up)
  • Mapping Types: dicts (coming up)
  • Binary Sequence Types: bytes, bytearray, memoryview
  • Iterator Types (Advanced Python)
  • Generator Types (Advanced Python)
  • Set Types (Advanced Python)

ints are whole number integers like, 1, 93874, -4


In [44]:
this_is_an_int = 9
nums = [2,2,2,2,2,2,2]

type(nums)


Out[44]:
list

Control Flow and Compound Statements

  • if
  • for
  • while
  • try
  • with

In [12]:
x = 1
if x < 100:
    print('X is less than 100')


X is less than 100

In [14]:
x = 1000
if x > 100:
    print('X is greater than 100')


X is greater than 100

In [17]:
x = int(input('Please enter a number'))
if x < 0:
    print('X is a negative number')
elif x == 0:
        print('x is 0')
else:
    print('x is a positive number')


Please enter a number0
x is 0

There can be no elif and the final else is optional. Note for people with a different language background, Python doesn't have a switch or case statement

For

Python iterates over items of any sequence


In [18]:
words = ['cat', 'dog', 'alligator', 'pirate']
for w in words:
    print(w, len(w))


cat 3
dog 3
alligator 9
pirate 6

In [51]:
var1 = "this is sstring"
for char in var1:
    print(hex(ord(char)))


0x74
0x68
0x69
0x73
0x20
0x69
0x73
0x20
0x73
0x73
0x74
0x72
0x69
0x6e
0x67

In [49]:
help(ord)


Help on built-in function ord in module builtins:

ord(c, /)
    Return the Unicode code point for a one-character string.

While

convention: while true:


In [ ]:
while True:

References


In [ ]: