3.1. Numeric Int

  • Represents integer

  • Could be both signed and unsigned

  • There is no maximal or minimal int value

  • Default int size is 64 bit

  • Python automatically extends int when need bigger number

3.1.1. Syntax

  • Signed and Unsigned

  • Use _ for thousand separator

>>> data = 1
>>> data = +1
>>> data = -1

You can use _ for easier read especially with big numbers:

>>> million = 1000000
>>> million = 1_000_000
>>>
>>> print(million)
1000000

3.1.2. Type Casting

  • Builtin function int() converts argument to int

  • It is not rounding

  • Works with strings, if all characters could be converted to int

  • Supports only: +, - and _ (underscore)

Builtin function int() converts argument to int:

>>> int(1)
1
>>>
>>> int(+1)
1
>>>
>>> int(-1)
-1
>>> int(1.337)
1
>>>
>>> int(+1.1337)
1
>>>
>>> int(-1.337)
-1
>>> int('1')
1
>>>
>>> int('+1')
1
>>>
>>> int('-1')
-1
>>> int('1_000_000')
1000000
>>> data = 'abc'
>>>
>>> int(data, base=10)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'abc'
>>>
>>>
>>> int(data, base=16)
2748
>>>
>>> import string
>>> string.hexdigits
'0123456789abcdefABCDEF'

3.1.3. Type Casting Errors

  • Works with strings, if all characters could be converted to int

  • It is not validator or parser to extract all numbers from str

Builtin function int() fails when in argument there are parameters other than a digit, + or - sign and _

>>> int('3.1337')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '3.1337'
>>> int('+3.1337')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '+3.1337'
>>> int('-3.1337')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '-3.1337'
>>> int('3,1337')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '3,1337'
>>> int('+3,1337')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '+3,1337'
>>> int('-3,1337')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '-3,1337'

3.1.4. Type Checking

  • type() - Returns type of an argument

  • isinstance() - Allows for checking if value is expected type

  • To check if type is what you expected use type() or isinstance()

  • Later you will learn the difference

>>> x = 1
>>> type(x)
<class 'int'>
>>> x = 1
>>> type(x) is int
True
>>> x = 1
>>> isinstance(x, int)
True

3.1.5. Rounding

  • Builtin function int() does not round numbers - only converts to int

  • Use round() for numbers rounding

Builtin function int() does not round numbers:

>>> int(1.111)
1
>>>
>>> int(1.999)
1

Builtin function round() does that:

>>> round(1.111)
1
>>>
>>> round(1.999)
2

3.1.6. Built-in Functions

  • abs() - Absolute value

  • pow() - Raise number to the power of exponential (the same as **)

Absolute value:

>>> abs(1)
1
>>>
>>> abs(-1)
1

Power (the same as **):

>>> pow(2, 4)
16
>>>
>>> pow(16, 1/2)
4.0

3.1.7. Use Case - 0x01

>>> SECOND = 1
>>> MINUTE = 60 * SECOND
>>> HOUR = 60 * MINUTE
>>> DAY = 24 * HOUR
>>>
>>>
>>> duration = 123456 * SECOND
>>>
>>> duration // DAY
1
>>> duration // HOUR
34
>>> duration // MINUTE
2057
>>> duration // SECOND
123456

3.1.8. Use Case - 0x02

>>> m = 1
>>> km = 1000 * m
>>> mi = 1652 * m
>>>
>>>
>>> distance = 123*mi
>>>
>>> distance // m
203196
>>> distance // km
203

3.1.9. Use Case - 0x03

>>> PLN = 1
>>> EUR = 4.71 * PLN  # 2023-03-19 17:00 GMT+1
>>> USD = 4.41 * PLN  # 2023-03-19 17:00 GMT+1
>>>
>>>
>>> price = 100*PLN
>>>
>>> round(price // EUR)
21
>>> round(price // USD)
22

3.1.10. Assignments

Code 3.1. Solution
"""
* Assignment: Type Int Add
* Required: yes
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. One Kelvin is equal to 1 Celsius degree (1K = 1°C)
    2. Zero Celsius degrees is equal to 273.15 Kelvins
    3. For calculation use round number 273 (0°C = 273K)
    4. How many Kelvins has average temperatures at surface [1]:
        a. Mars highest: 20 °C
        b. Mars lowest: -153 °C
        c. Mars average: −63 °C
    5. Run doctests - all must succeed

Polish:
    1. Jeden Kelwin to jeden stopień Celsiusza (1K = 1°C)
    2. Zero stopni Celsiusza to 273.15 Kelwiny
    3. W zadaniu przyjmij równe 273°C (0°C = 273K)
    4. Ile Kelwinów wynoszą średnie temperatury powierzchni [1]:
        a. Mars najwyższa: 20 °C
        b. Mars najniższa: -153 °C
        c. Mars średnia: −63 °C
    5. Uruchom doctesty - wszystkie muszą się powieść

Hint:
    * Use only +273 and -273

References:
    [1] Centro de Astrobiología (CSIC-INTA).
        Rover Environmental Monitoring Station, Mars Science Laboratory (NASA).
        Year: 2019.
        Retrieved: 2019-08-06.
        URL: http://cab.inta-csic.es/rems/marsweather.html

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert mars_max is not Ellipsis, \
    'Assign your result to variable `mars_max`'
    >>> assert mars_min is not Ellipsis, \
    'Assign your result to variable `mars_min`'
    >>> assert mars_min is not Ellipsis, \
    'Assign your result to variable `mars_min`'
    >>> assert type(mars_max) is int, \
    'Variable `mars_max` has invalid type, should be int'
    >>> assert type(mars_min) is int, \
    'Variable `mars_min` has invalid type, should be int'
    >>> assert type(mars_min) is int, \
    'Variable `mars_avg` has invalid type, should be int'

    >>> assert mars_max == 293, \
    'Invalid value for `mars_max`, should be 293. Check you calculation'
    >>> assert mars_min == 120, \
    'Invalid value for `mars_min`, should be 120. Check you calculation'
    >>> assert mars_avg == 210, \
    'Invalid value for `mars_avg`, should be 210. Check you calculation'

"""

Celsius = 1
Kelvin = 273

# 20 Celsius in Kelvin
# type: int
mars_max = ...

# -153 Celsius in Kelvin
# type: int
mars_min = ...

# -63 Celsius in Kelvin
# type: int
mars_avg = ...

Code 3.2. Solution
"""
* Assignment: Type Int Sub
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

English:
    1. One Kelvin is equal to 1 Celsius degree (1K = 1°C)
    2. Zero Kelvin (absolute) is equal to -273.15 Celsius degrees
    3. For calculation use round number -273 (0K = -273°C)
    4. How many Celsius degrees has average temperatures at surface [1]:
        a. Lunar day: 453 K
        b. Lunar night: 93 K
    5. Run doctests - all must succeed

Polish:
    1. Jeden Kelwin to jeden stopień Celsiusza (1K = 1°C)
    2. Zero Kelwina (bezwzględne) to -273.15 stopni Celsiusza
    3. W zadaniu przyjmij równe -273°C (0K = -273°C)
    4. Ile stopni Celsiusza wynoszą średnie temperatury powierzchni [1]:
        a. Księżyca w dzień: 453 K
        b. Księżyca w nocy: 93 K
    5. Uruchom doctesty - wszystkie muszą się powieść

Hint:
    * Use only +273 and -273

References:
    [1] Centro de Astrobiología (CSIC-INTA).
        Rover Environmental Monitoring Station, Mars Science Laboratory (NASA).
        Year: 2019.
        Retrieved: 2019-08-06.
        URL: http://cab.inta-csic.es/rems/marsweather.html

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert lunar_day is not Ellipsis, \
    'Assign your result to variable `lunar_day`'
    >>> assert lunar_night is not Ellipsis, \
    'Assign your result to variable `lunar_night`'
    >>> assert type(lunar_day) is int, \
    'Variable `lunar_day` has invalid type, should be int'
    >>> assert type(lunar_night) is int, \
    'Variable `lunar_night` has invalid type, should be int'

    >>> lunar_day
    180
    >>> lunar_night
    -180
"""

Celsius = 273
Kelvin = 1

# 453 Kelvins in Celsius
# type: int
lunar_day = ...

# 93 Kelvins in Celsius
# type: int
lunar_night = ...

Code 3.3. Solution
"""
* Assignment: Type Int Mul
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

English:
    1. Calculate altitude in meters:
        a. Armstrong Limit: 19 km
        b. Stratosphere: 20 km
        c. USAF Space Line: 80 km
        d. IAF Space Line: 100 km
    2. Run doctests - all must succeed

Polish:
    1. Oblicz wysokości w metrach:
        a. Linia Armstronga: 19 km
        b. Stratosfera: 20 km
        c. Granica kosmosu wg. USAF: 80 km
        d. Granica kosmosu wg. IAF 100 km
    2. Uruchom doctesty - wszystkie muszą się powieść

References:
    * USAF - United States Air Force
    * IAF - International Astronautical Federation
    * Kármán line (100 km) - boundary between Earth's atmosphere and space
    * Armstrong limit (19 km) - altitude above which atmospheric pressure is
      sufficiently low that water boils at the temperature of the human body

Hints:
    * 1 km = 1000 m
    * Use // to get floor division as int

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert armstrong_limit is not Ellipsis, \
    'Assign your result to variable `armstrong_limit`'
    >>> assert stratosphere is not Ellipsis, \
    'Assign your result to variable `stratosphere`'
    >>> assert usaf_space is not Ellipsis, \
    'Assign your result to variable `usaf_space`'
    >>> assert iaf_space is not Ellipsis, \
    'Assign your result to variable `iaf_space`'
    >>> assert type(armstrong_limit) is int, \
    'Variable `armstrong_limit` has invalid type, should be int'
    >>> assert type(stratosphere) is int, \
    'Variable `stratosphere` has invalid type, should be int'
    >>> assert type(usaf_space) is int, \
    'Variable `usaf_space` has invalid type, should be int'
    >>> assert type(iaf_space) is int, \
    'Variable `iaf_space` has invalid type, should be int'

    >>> armstrong_limit
    19000
    >>> stratosphere
    20000
    >>> usaf_space
    80000
    >>> iaf_space
    100000
"""

m = 1
km = 1000 * m

# 19 kilometers in meters
# type: int
armstrong_limit = ...

# 20 kilometers in meters
# type: int
stratosphere = ...

# 80 kilometers in meters
# type: int
usaf_space = ...

# 100 kilometers in meters
# type: int
iaf_space = ...

Code 3.4. Solution
"""
* Assignment: Type Int Truediv
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

English:
    1. Calculate altitude in kilometers:
        a. Kármán Line Earth: 100_000 m
        b. Kármán Line Mars: 80_000 m
        c. Kármán Line Venus: 250_000 m
    2. In Calculations use floordiv (`//`)
    3. Run doctests - all must succeed

Polish:
    1. Oblicz wysokości w kilometrach:
        a. Linia Kármána Ziemia: 100_000 m
        b. Linia Kármána Mars: 80_000 m
        c. Linia Kármána Wenus: 250_000 m
    2. W obliczeniach użyj floordiv (`//`)
    3. Uruchom doctesty - wszystkie muszą się powieść

References:
    * Kármán line (100 km) - boundary between planets's atmosphere and space

Hints:
    * 1 km = 1000 m
    * Use // to get floor division as int

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert karman_line_earth is not Ellipsis, \
    'Assign your result to variable `karman_line_earth`'
    >>> assert karman_line_mars is not Ellipsis, \
    'Assign your result to variable `karman_line_mars`'
    >>> assert karman_line_venus is not Ellipsis, \
    'Assign your result to variable `karman_line_venus`'
    >>> assert type(karman_line_earth) is int, \
    'Variable `karman_line_earth` has invalid type, should be int'
    >>> assert type(karman_line_mars) is int, \
    'Variable `karman_line_mars` has invalid type, should be int'
    >>> assert type(karman_line_venus) is int, \
    'Variable `karman_line_venus` has invalid type, should be int'

    >>> karman_line_earth
    100
    >>> karman_line_mars
    80
    >>> karman_line_venus
    250
"""

m = 1
km = 1000 * m

# 100_000 meters in km
# type: int
karman_line_earth = ...

# 80_000 meters in km
# type: int
karman_line_mars = ...

# 250_000 meters in km
# type: int
karman_line_venus = ...

Code 3.5. Solution
"""
* Assignment: Type Int Time
* Required: yes
* Complexity: easy
* Lines of code: 12 lines
* Time: 8 min

English:
    1. Calculate how many seconds is one day (24 hours)
    2. Calculate how many minutes is one week (7 days)
    3. Calculate how many hours is in one month (31 days)
    4. Calculate how many seconds is work day (8 hours)
    5. Calculate how many minutes is work week (5 work days)
    6. Calculate how many hours is work month (22 work days)
    7. In Calculations use floordiv (`//`)
    8. Run doctests - all must succeed

Polish:
    1. Oblicz ile sekund to jedna doba (24 godziny)
    2. Oblicz ile minut to jeden tydzień (7 dni)
    3. Oblicz ile godzin to jeden miesiąc (31 dni)
    4. Oblicz ile sekund to dzień pracy (8 godzin)
    5. Oblicz ile minut to tydzień pracy (5 dni pracy)
    6. Oblicz ile godzin to miesiąc pracy (22 dni pracy)
    7. W obliczeniach użyj floordiv (`//`)
    8. Uruchom doctesty - wszystkie muszą się powieść

Hint:
    * Use // to get floor division as int

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert day is not Ellipsis, \
    'Assign your result to variable `day`'
    >>> assert week is not Ellipsis, \
    'Assign your result to variable `week`'
    >>> assert month is not Ellipsis, \
    'Assign your result to variable `month`'
    >>> assert workday is not Ellipsis, \
    'Assign your result to variable `workday`'
    >>> assert workweek is not Ellipsis, \
    'Assign your result to variable `workweek`'
    >>> assert workmonth is not Ellipsis, \
    'Assign your result to variable `workmonth`'
    >>> assert type(day) is int, \
    'Variable `day` has invalid type, should be int'
    >>> assert type(week) is int, \
    'Variable `week` has invalid type, should be int'
    >>> assert type(month) is int, \
    'Variable `month` has invalid type, should be int'
    >>> assert type(workday) is int, \
    'Variable `workday` has invalid type, should be int'
    >>> assert type(workweek) is int, \
    'Variable `workweek` has invalid type, should be int'
    >>> assert type(workmonth) is int, \
    'Variable `workmonth` has invalid type, should be int'

    >>> day
    86400
    >>> week
    10080
    >>> month
    744
    >>> workday
    28800
    >>> workweek
    2400
    >>> workmonth
    176
"""

SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR

# 1 day in seconds
# type: int
day = ...

# 7 days in minutes
# type: int
week = ...

# 31 days in hours
# type: int
month = ...

# 8 hours in seconds
# type: int
workday = ...

# 5 workdays in minutes
# type: int
workweek = ...

# 22 workdays in hours
# type: int
workmonth = ...

3.1.11. Homework

Code 3.6. Solution
"""
* Assignment: Type Int Bits
* Required: no
* Complexity: medium
* Lines of code: 4 lines
* Time: 3 min

English:
    1. File size is 1337 megabits [Mb]
    2. Calculate size in bits [b]
    3. Calculate size in kilobits [kb]
    4. In Calculations use floordiv (`//`)
    5. Run doctests - all must succeed

Polish:
    1. Wielkość pliku to 1337 megabits [Mb]
    2. Oblicz wielkość w bitach [b]
    3. Oblicz wielkość w kilobitach [kb]
    4. W obliczeniach użyj floordiv (`//`)
    5. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * 1 kb = 1024 b
    * 1 Mb = 1024 Kb
    * Use // to get floor division as int

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert size_b is not Ellipsis, \
    'Assign your result to variable `size_b`'
    >>> assert size_kb is not Ellipsis, \
    'Assign your result to variable `size_kb`'
    >>> assert size_Mb is not Ellipsis, \
    'Assign your result to variable `size_Mb`'
    >>> assert type(size_b) is int, \
    'Variable `size_b` has invalid type, should be int'
    >>> assert type(size_kb) is int, \
    'Variable `size_kb` has invalid type, should be int'
    >>> assert type(size_Mb) is int, \
    'Variable `size_Mb` has invalid type, should be int'

    >>> size_b
    1401946112
    >>> size_kb
    1369088
    >>> size_Mb
    1337
"""

b = 1
kb = 1024 * b
Mb = 1024 * kb

SIZE = 1337 * Mb

# SIZE in bits
# type: int
size_b = ...

# SIZE in kilobits
# type: int
size_kb = ...

# SIZE in megabits
# type: int
size_Mb = ...

Code 3.7. Solution
"""
* Assignment: Type Int Bytes
* Required: no
* Complexity: easy
* Lines of code: 7 lines
* Time: 3 min

English:
    1. File size is 100 megabytes
    2. Calculate size in kilobytes
    2. Calculate size in megabits
    3. Run doctests - all must succeed

Polish:
    1. Wielkość pliku to 100 megabajtów
    2. Oblicz wielkość w kilobajtach
    2. Oblicz wielkość w megabitach
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * 1 Kb = 1024 b
    * 1 Mb = 1024 Kb
    * 1 B = 8 b
    * 1 KB = 1024 B
    * 1 MB = 1024 KB
    * Use // to get floor division as int

Tests:
    >>> import sys; sys.tracebacklimit = 0


    >>> assert size_kB is not Ellipsis, \
    'Assign your result to variable `size_kB`'
    >>> assert size_Mb is not Ellipsis, \
    'Assign your result to variable `size_Mb`'
    >>> assert type(size_kB) is int, \
    'Variable `size_kB` has invalid type, should be int'
    >>> assert type(size_Mb) is int, \
    'Variable `size_Mb` has invalid type, should be int'

    >>> size_kB
    102400
    >>> size_Mb
    800
"""

b = 1
kb = 1024 * b
Mb = 1024 * kb

B = 8 * b
kB = 1024 * B
MB = 1024 * kB

SIZE = 100 * MB

# SIZE in kilobytes
# type: int
size_kB = ...

# SIZE in megabits
# type: int
size_Mb = ...

Code 3.8. Solution
"""
* Assignment: Type Int Bandwidth
* Required: no
* Complexity: easy
* Lines of code: 10 lines
* Time: 3 min

English:
    1. Having internet connection with speed 100 Mb/s
    2. How long will take to download 100 MB?
    3. To calculate time divide file size by speed
    4. Note, that all values must be `int` (type cast if needed)
    5. In Calculations use floordiv (`//`)
    6. Run doctests - all must succeed

Polish:
    1. Mając łącze internetowe 100 Mb/s
    2. Ile zajmie ściągnięcie pliku 100 MB?
    3. Aby wyliczyć czas podziel wielkość pliku przez prękość
    4. Zwróć uwagę, że wszystkie wartości mają być `int`
       (rzutuj typ jeżeli potrzeba)
    5. W obliczeniach użyj floordiv (`//`)
    6. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * 1 Kb = 1024 b
    * 1 Mb = 1024 Kb
    * 1 B = 8 b
    * 1 KB = 1024 B
    * 1 MB = 1024 KB
    * Use // to get floor division as int

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert bandwidth is not Ellipsis, \
    'Assign your result to variable `bandwidth`'
    >>> assert size is not Ellipsis, \
    'Assign your result to variable `size`'
    >>> assert duration is not Ellipsis, \
    'Assign your result to variable `duration`'
    >>> assert type(bandwidth) is int, \
    'Variable `bandwidth` has invalid type, should be int'
    >>> assert type(size) is int, \
    'Variable `size` has invalid type, should be int'
    >>> assert type(duration) is int, \
    'Variable `duration` has invalid type, should be int'

    >>> duration
    8
"""

SECOND = 1

b = 1
kb = 1024 * b
Mb = 1024 * kb

B = 8 * b
kB = 1024 * B
MB = 1024 * kB

# 100 megabits per second
# type: int
bandwidth = ...

# 100 megabytes
# type: int
size = ...

# Duration is size by bandwidth in seconds
# type: int
duration = ...