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
Listing 640. 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. Assignment

  • 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)

The whys and wherefores
  • Defining constants and variables

  • Naming convention

  • Mathematical operations

Hint
  • 1 h = 60 min

  • 1 min = 60 s

3.3.2. float

value = 13.37           # 13.37
value = -13.37          # -13.37
Listing 641. Notation without leading or trailing zero. Used by numpy
value = 10.             # 10.0
value = .44             # 0.44
Listing 642. 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. Assignment

  • Complexity level: easy

  • Lines of code to write: 4 lines

  • Estimated time of completion: 5 min

  • Filename: solution/types_float.py

English
  1. Declare variable for holding value of 1337 meters

  2. Print values in other units

  3. Use code output (see below) as a template

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

  5. Instead ... substitute calculated and converted values

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

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

  3. Użyj kodu wyjściowego (patrz sekcja input) jako szablonu

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

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

Non-functional requirements
  1. Do not use input()

Input
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
The whys and wherefores
  • Defining constants and variables

  • Naming convention

  • Print formatting

  • Mathematical operations

  • Separation of business logic and view

Hints
  • 1000 m = 1 km

  • 1608 m = 1 mile

  • 1852 m = 1 nautical mile

3.3.3. str

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

text = """
    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

name = "Jan Twardowski"
name = 'Jan Twardowski'
name = """Jan Twardowski"""
name = '''Jan Twardowski'''
name = """My name's "José Jiménez""""
name = '''My name's "José Jiménez"'''
Listing 644. When to use single or double quotes?
my_str = 'It\'s Twardowski\'s Moon.'
my_str = "It's Twardowski's Moon."
my_str = '<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'
Listing 645. 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 87. 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

Listing 646. Format string (string interpolation)
first_name = 'Jan'
last_name = 'Twardowski'

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

name = f'{first_name} {last_name}'
print(name)
# Jan Twardowski
Listing 647. Unicode literals. In Python 3 u'...' is only for compatibility with Python 2
u'zażółć gęślą jaźń'
Listing 648. Bytes literals. Used in sockets and HTTP connections. Use bytes.decode() or str.encode() for conversion.
b'this is bytes literals'
Listing 649. 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')
# 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

Listing 650. Length of a str
len('Jan')      # 3
len('')         # 0

3.3.3.7. Assignment

  • 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

my_var = True               # True
my_var = False              # False

3.3.4.1. Converting to bool

Listing 651. 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
Listing 652. 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 88. 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

  • Complexity level: easy

  • Lines of code to write: 15 lines

  • Estimated time of completion: 10 min

  • Filename: solution/types_bool.py

English
  1. Which variables are True?

  2. Which variables are False?

Polish
  1. Które zmienne są True?

  2. Które zmienne są False?

Input
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')
The whys and wherefores
  • Defining variables

  • Type casting

  • Logic types

3.3.8. Operators

3.3.8.1. Numerical Operators

Listing 653. Addition
value = 10 + 2
print(value)
# 12

value = 10
value += 2
print(value)
# 12
Listing 654. Subtraction
value = 10 - 2
print(value)
# 8

value = 10
value -= 2
print(value)
# 8
Listing 655. Multiplication
value = 10 * 2
print(value)
# 20

value = 10
value *= 2
print(value)
# 20
Listing 656. 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
Listing 657. Division
value = 10 / 2
print(value)
# 5

value = 10
value /= 2
print(value)
# 5
Listing 658. Quotient of division
10 // 2         # 5
10 // 3         # 3
4 // 2          # 2
5 // 2          # 2
Listing 659. Modulo. Reminder of division.
10 % 2          # 0
10 % 3          # 1
4 % 2           # 0
5 % 2           # 1

3.3.8.2. Numeric Functions

Listing 660. 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
Listing 661. Minimal value
min(3, 1, 5)    # 1
Listing 662. Maximal value
max(3, 1, 5)    # 5
Listing 663. Absolute value
abs(1)          # 1
abs(-1)         # 1
abs(13.37)      # 13.37
abs(-13.37)     # 13.37
Listing 664. 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