3.3. Types

3.3.1. int

  • In Python 3 there is not maximal int value

  • Python 3 dynamically extends int, when it's too big

value = 30              # 30
value = -30             # -30
Code 3.228. You can use _ for easier read especially with big numbers
million = 1000000        # 1000000
million = 1_000_000      # 1000000

3.3.1.1. Converting to int

  • Also known as "type casting"

  • int() converts argument to int

  • int() does not round numbers, it returns integer value

int(10)                 # 10
int(10.0)               # 10
int(10.9)               # 10
int(13.37)              # 13
int(-13.37)             # -13
int('1')                # 1
int('-1')               # -1
int('13.37')            # ValueError: invalid literal for int() with base 10: '1.23'
int('-13.37')           # ValueError: invalid literal for int() with base 10: '-1.23'

3.3.1.2. Assignments

  • Assignment: Assignments

  • Last update: 2020-10-01

  • Complexity level: easy

  • Lines of code to write: 12 lines

  • Estimated time of completion: 5 min

  • Filename: solution/types_int.py

English:
  1. Calculate how many seconds is five minutes

  2. Calculate how many seconds is one hour

  3. Calculate how many seconds is work day (8 hours)

  4. Calculate how many seconds is work month (22 days per 8 hours)

  5. Calculate how many minutes is work week (40 hours)

Polish:
  1. Oblicz ile sekund to pięć minut

  2. Oblicz ile sekund to jedna godzina

  3. Oblicz ile sekund to dzień pracy (8 godzin)

  4. Oblicz ile sekund to miesiąc pracy (22 dni po 8 godzin)

  5. Oblicz ile minut to tydzień pracy (40 godzin)

Hints:
  • 1 h = 60 min

  • 1 min = 60 s

3.3.2. float

value = 13.37           # 13.37
value = -13.37          # -13.37
Code 3.229. Notation without leading or trailing zero. Used by numpy
value = 10.             # 10.0
value = .44             # 0.44
Code 3.230. Engineering notation
million = 1e6           # 1000000.0
million = 1E6           # 1000000.0
+1e6                    # 1000000.0
-1e6                    # -1000000.0
1e-3                    # 0.001
1e-4                    # 0.0001
1e-5                    # 1e-05
1e-6                    # 1e-06
1.337 * 1e3             # 1337.0
1.337 * 1e-3            # 0.001337

3.3.2.1. Converting to float

  • Also known as "type casting"

  • float() converts argument to float

float(10)               # 10.0
float(-10)              # -10.0
float(10.5)             # 10.5
float(-10.5)            # -10.5
float(13.37)            # 13.37
float(-13.37)           # -13.37
float('+13.37')         # 13.37
float('-13.37')         # -13.37
float('13,37')          # ValueError: could not convert string to float: '13,37'
float('-13,37')         # ValueError: could not convert string to float: '-13,37'

3.3.2.2. Assignments

  • Assignment: Assignments

  • Last update: 2020-10-01

  • Complexity level: easy

  • Lines of code to write: 4 lines

  • Estimated time of completion: 5 min

  • Filename: solution/types_float.py

English:
  1. Use code from "Input" section (see below)

  2. Declare variable for holding value of 1337 meters

  3. Print values in other units

  4. Convert data to types shown in comments at the right side

  5. Instead ... substitute calculated and converted values

  6. Non-functional requirements:

    • Do not use input()

Polish:
  1. Użyj kodu z sekcji "Input" (patrz poniżej)

  2. Zdefiniuj zmienną dla przechowywania wartości 1337 metrów

  3. Wypisz wartość w różnych jednostkach

  4. Przekonwertuj dane do typów podanych w komentarzu po prawej stronie

  5. Zamiast ... podstaw wyliczone i przekonwertowane wartości

  6. Wymagania niefunkcjonalne:

    • Nie używaj input()

Given:
print(f'Meters: {...}')                              # int
print(f'Kilometers: {...}')                          # int
print(f'Miles: {...}')                               # float
print(f'Nautical Miles: {...}')                      # float
print(f'm: {...}, km: {...}, mi: {...}, nm: {...}')  # int, int, float, float
Hints:
  • 1000 m = 1 km

  • 1608 m = 1 mile

  • 1852 m = 1 nautical mile

3.3.3. str

data = ''
data = 'Jan Twardowski'
Code 3.231. Multiline str. Always use double quote characters to be consistent with the docstring convention PEP 257
data = """First line
Second line
Third line"""
# 'First line\nSecond line\nThird line'

data = """
    First line
    Second line
    Third line
"""
# '\n        First line\n        Second line\n        Third line\n    '

3.3.3.1. Single or double quote?

  • " and ' works the same

  • Choose one and keep consistency in code

  • Python console uses '

  • it matters for doctest, which compares two outputs character by character

data = "Jan Twardowski"
data = 'Jan Twardowski'
data = """Jan Twardowski"""
data = '''Jan Twardowski'''
data = """My name's "José Jiménez""""
data = '''My name's "José Jiménez"'''
Code 3.232. When to use single or double quotes?
data = 'It\'s Twardowski\'s Moon.'
data = "It's Twardowski's Moon."
data = '<a href="http://python.astrotech.io">Python and Machine Learning</a>'

3.3.3.2. Type casting to str

str('hello')        # 'hello'
str(1969)           # '1969'
str(13.37)          # '13.37'
Code 3.233. Print converts argument to str before printing
print('hello')      # str('hello') -> 'hello'
# hello

print(10)           # str(10) -> '10'
# 10

3.3.3.3. Escape characters

  • \r\n - is used on windows

  • \n - is used everywhere else

Table 3.11. Escape characters

Sequence

Description

\n

New line (LF - Linefeed)

\r

Carriage Return (CR)

\t

Horizontal Tab (TAB)

\'

Single quote '

\"

Double quote "

\\

Backslash \

\a

Bell (BEL)

\b

Backspace (BS)

\f

New page (FF - Form Feed)

\v

Vertical Tab (VT)

\uF680

Character with 16-bit (2 bytes) hex value F680

\U0001F680

Character with 32-bit (4 bytes) hex value 0001F680

\o755

ASCII character with octal value 755

\x1F680

ASCII character with hex value 1F680

print('\U0001F680')     # 🚀

3.3.3.4. Characters before strings

  • f'string' - Format string

  • u'string' - Unicode literals

  • b'string' - Bytes literals

  • r'string' - Raw string

Code 3.234. Format string (string interpolation)
firstname = 'Jan'
lastname = 'Twardowski'

print(f'My name is {lastname}')
# My name is Twardowski

name = f'{firstname} {lastname}'
print(name)
# Jan Twardowski
Code 3.235. Unicode literals. In Python 3 u'...' is only for compatibility with Python 2
u'zażółć gęślą jaźń'
Code 3.236. Bytes literals. Used in sockets and HTTP connections. Use bytes.decode() or str.encode() for conversion.
b'this is bytes literals'
Code 3.237. Raw String. Escapes does not matters
pattern = r'[a-z0-9]\n'

print(r'C:\Users\Admin\file.txt')
# C:\Users\Admin\file.txt

print('C:\Users\Admin\file.txt')
# Traceback (most recent call last):
# SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

3.3.3.5. Reading user input

  • input() returns str

  • Good practice: add space at the end of prompt

name = input('Type your name: ')
# User inputs: Jan Twardowski

print(name)     # 'Jan Twardowski'
type(name)      # <class 'str'>
age = input('Type your age: ')
# User inputs: 42

print(age)      # '42'
type(age)       # <class 'str'>

3.3.3.6. Methods

Code 3.238. Length of a str
len('Jan')      # 3
len('')         # 0

3.3.3.7. Assignments

  • Assignment: Assignments

  • Last update: 2020-10-01

  • Complexity level: easy

  • Lines of code to write: 3 lines

  • Estimated time of completion: 3 min

  • Filename: solution/types_str.py

English:
  • Ask user to input text

  • Print number of characters

Polish:
  • Poproś użytkownika o wprowadzenie tekstu

  • Wypisz liczbę znaków

3.3.4. bool

data = True                 # True
data = False                # False

3.3.4.1. Converting to bool

Code 3.239. Negative values
bool(False)                 # False
bool(None)                  # False
bool(0)                     # False
bool(0.0)                   # False
bool(0+0j)                  # False
bool(0.0+0.0j)              # False
bool(str())                 # False
bool(tuple())               # False
bool(dict())                # False
bool(set())                 # False
bool('')                    # False
bool(())                    # False
bool([])                    # False
bool({})                    # False
Code 3.240. Positive values
bool(1)                     # True
bool(1.0)                   # True
bool('Jan Twardowski')      # True

3.3.5. Boolean logic

3.3.5.1. Using and

True and True               # True
True and False              # False
False and True              # False
False and False             # False
1 and 1                     # True
1 and 0                     # False
0 and 1                     # False
0 and 0                     # False
'Jan' and 'Jan'             # True
'Jan' and ''                # False
'' and 'Jan'                # False
'' and ''                   # False
'Jan' and 1                 # True
'Jan' and 0                 # False
0.0 and 'Jan'               # False
1 and False                 # False

3.3.5.2. Using or

True or True                # True
True or False               # True
False or True               # True
False or False              # False
1 or 1                      # True
1 or 0                      # True
0 or 1                      # True
0 or 0                      # False
'José' or 'Иван'            # True
'José' or ''                # True
'' or 'José'                # True
'' or ''                    # False
1 or 'Иван'                 # True
True or ''                  # True
0 or True                   # True
0.0 or False                # False

3.3.5.3. Using both: or and and

True and True or False      # True
True and False or False     # False
False and False or True     # True

3.3.6. Logic operators

Table 3.12. Logic operators

Operand

Example

Description

x < y

x < 18

value of x is less than y

x <= y

x <= 18

value of x is less or equal y

x > y

x > 18

value of x is greater than y

x >= y

x >= 18

value of x is greater or equal than y

x == y

x == 18

value of x is equal to y

x != y

x != 18

value of x is not equal to y

3.3.7. Assignments

3.3.7.1. To bool or not to bool

  • Assignment: To bool or not to bool

  • Last update: 2020-10-01

  • Complexity level: easy

  • Lines of code to write: 15 lines

  • Estimated time of completion: 13 min

  • Filename: solution/types_bool.py

English:
  1. Use data from "Given" section (see below)

  2. Which variables are True?

  3. Which variables are False?

Polish:
  1. Użyj danych z sekcji "Given" (patrz poniżej)

  2. Które zmienne są True?

  3. Które zmienne są False?

Given:
a = bool(False)
b = bool(True)

c = bool('a')
d = bool('.')
e = bool('0')
f = bool('0.0')
g = bool('')
h = bool(' ')

i = bool(0)
j = bool(0.0)
k = bool(-0)
l = bool(-0.0)

m = bool(int('0'))
n = bool(float('-0'))

o = bool(-0.0+0.0j)
p = bool('-0.0+0.0j')

3.3.8. Operators

3.3.8.1. Numerical Operators

Code 3.241. Addition
value = 10 + 2
print(value)
# 12

value = 10
value += 2
print(value)
# 12
Code 3.242. Subtraction
value = 10 - 2
print(value)
# 8

value = 10
value -= 2
print(value)
# 8
Code 3.243. Multiplication
value = 10 * 2
print(value)
# 20

value = 10
value *= 2
print(value)
# 20
Code 3.244. Number to the n-th power
10 ** 2         # 100
3 ** 4          # 81
-1 ** 2         # 1
2 ** -1         # 0.5
1.337 ** 3      # 2.389979753
4 ** 0.5        # 2.0
2 ** 0.5        # 1.4142135623730951
Code 3.245. Division
value = 10 / 2
print(value)
# 5

value = 10
value /= 2
print(value)
# 5
Code 3.246. Quotient of division
10 // 2         # 5
10 // 3         # 3
4 // 2          # 2
5 // 2          # 2
Code 3.247. Modulo. Reminder of division.
10 % 2          # 0
10 % 3          # 1
4 % 2           # 0
5 % 2           # 1

3.3.8.2. Numeric Functions

Code 3.248. Rounding numbers
pi = 3.14159265359

round(pi)               # 3
round(pi, 2)            # 3.14
round(pi, 4)            # 3.1416

print(f'{pi:.2f}')      # 3.14
print(f'{pi:.4f}')      # 3.1416
Code 3.249. Minimal value
min(3, 1, 5)    # 1
Code 3.250. Maximal value
max(3, 1, 5)    # 5
Code 3.251. Absolute value
abs(1)          # 1
abs(-1)         # 1
abs(13.37)      # 13.37
abs(-13.37)     # 13.37
Code 3.252. Number to the n-th power
pow(10, 2)      # 100
pow(3, 4)       # 81
pow(-1, 2)      # 1
pow(2, -1)      # 0.5
pow(1.337, 3)   # 2.389979753
pow(4, 0.5)     # 2.0
pow(2, 0.5)     # 1.4142135623730951