%%html
<!-- The customized css for the slides -->
<link rel="stylesheet" type="text/css" href="../../assets/styles/basic.css"/>
<link rel="stylesheet" type="text/css" href="../../assets/styles/python-programming-basic.css"/>

43.2. Python programming basics#

43.2.1. 1. Python syntax#

  • Python was designed for readability and has some similarities to the English language.

  • Python uses new lines to complete a command, not semicolons or parentheses.

  • Python relies on indentation, using whitespace, to define scope, not curly brackets.

43.2.1.1. Python indentations#

Python uses indentation to indicate a block of code.

if 5 > 2:
    print("Five is greater than two!")

43.2.1.2. Comments#

Python has the commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:

# This is a comment.
print("Hello, World!")

43.2.1.3. Docstrings#

Python also has extended capability for multiline documentation, called docstrings.

"""This is a 
multiline docstring."""
print("Hello, World!")

43.2.2. 2. Variables#

Python is completely object-oriented, and not “statically typed”. You do not need to declare variables or their type before using them. Every variable in Python is an object.

Rules for Python variables:

  • must start with a letter or the underscore character.

  • cannot start with a number.

  • can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

  • case-sensitive (age, Age and AGE are three different variables).

integer_variable = 5
string_variable = 'John'

assert integer_variable == 5
assert string_variable == 'John'

43.2.3. 3. Operators#

Operators are used to performing operations on variables and values. Python divides the operators into the following groups:

  • Arithmetic operators

  • Assignment operators

  • Comparison operators

  • Logical operators

  • Identity operators

  • Membership operators

  • Bitwise operators

43.2.3.1. Arithmetic operators#

Arithmetic operators are used with numeric values to perform common mathematical operations.

# Addition.
assert 5 + 3 == 8

# Subtraction.
assert 5 - 3 == 2

# Multiplication.
assert 5 * 3 == 15
assert isinstance(5 * 3, int)

# Division.
# Result of division is float number.
assert 5 / 3 == 1.6666666666666667
assert isinstance(8 / 4, float)

# Modulus.
assert 5 % 3 == 2

# Exponentiation.
assert 5 ** 3 == 125
assert isinstance(5 ** 3, int)

# Floor division.
assert 5 // 3 == 1
assert isinstance(5 // 3, int)

43.2.3.2. Comparison operators#

Comparison operators are used to compare two values.

# Equal.
number = 5
assert number == 5

# Not equal.
number = 5
assert number != 3

# Greater than.
number = 5
assert number > 3

# Less than.
number = 5
assert number < 8

# Greater than or equal to
number = 5
assert number >= 5
assert number >= 4

# Less than or equal to
number = 5
assert number <= 5
assert number <= 6

43.2.4. 4. Data types#

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built in by default, in these categories:

Name

Type

Text Type

str

Numeric Types

int, float, complex

Sequence Types

list, tuple, range

Mapping Type

dict

Set Types

set, frozenset

Boolean Type

bool

Binary Types

bytes, bytearray, memoryview

None Type

NoneType

43.2.4.1. Numbers (including booleans)#

There are three numeric types in Python:

  • int

  • float

  • complex

43.2.4.1.1. Integers#

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

positive_integer = 1
negative_integer = -3255522
big_integer = 35656222554887711

assert isinstance(positive_integer, int)
assert isinstance(negative_integer, int)
assert isinstance(big_integer, int)

43.2.4.1.2. Booleans#

Booleans represent the truth values False and True.

true_boolean = True
false_boolean = False

assert true_boolean
assert not false_boolean

assert isinstance(true_boolean, bool)
assert isinstance(false_boolean, bool)

# Let's try to cast boolean to string.
assert str(true_boolean) == "True"
assert str(false_boolean) == "False"

43.2.4.1.3. Floats#

Float, or “floating point number” is a number, positive or negative, containing one or more decimals.

float_number = 7.0
# Another way of declaring float is using float() function.
float_number_via_function = float(7) 
float_negative = -35.59

assert float_number == float_number_via_function
assert isinstance(float_number, float)
assert isinstance(float_number_via_function, float)
assert isinstance(float_negative, float)

Float can also be scientific numbers with an “e” to indicate the power of 10.

float_with_small_e = 35e3
float_with_big_e = 12E4

assert float_with_small_e == 35000
assert isinstance(12E4, float)

43.2.4.1.4. Complexes#

A complex number has two parts, a real part and an imaginary part.

complex_number_1 = 5 + 6j
complex_number_2 = 3 - 2j

assert isinstance(complex_number_1, complex)
assert isinstance(complex_number_2, complex)
assert complex_number__1 * complex_number_2 == 27 + 8j

43.2.4.1.5. Number operation#

# Addition.
assert 2 + 4 == 6

# Multiplication.
assert 2 * 4 == 8

# Division always returns a floating point number.
assert 12 / 3 == 4.0

# Modulo operator returns the remainder of the division.
assert 12 % 3 == 0

# Floor division discards the fractional part.
assert 17 // 3 == 5

# Raising the number to specific power.
assert 5 ** 2 == 25  # 5 squared

# There is full support for floating point; operators with mixed type operands convert the integer operand to floating point.
assert 4 * 3.75 - 1 == 14.0

43.2.4.2. Strings and their methods#

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes '' or double quotes "" with the same result.

# String with double quotes.
name_1 = "John"

# String with single quotes.
name_2 = 'John'

assert name_1 == name_2
assert isinstance(name_1, str)
assert isinstance(name_2, str)

43.2.4.2.1. String type#

\ can be used to escape quotes. Use \' to escape the single quote or use double quotes instead.

single_quote_string = 'doesn\'t'
double_quote_string = "doesn't"

assert single_quote_string == double_quote_string

Strings can be indexed, with the first character having index 0. Note that since -0 is the same as 0, negative indices start from -1.

import pytest
word = 'Python'
assert word[0] == 'P'  # First character.
assert word[5] == 'n'  # Fifth character.
assert word[-1] == 'n'  # Last character.
assert word[-2] == 'o'  # Second-last character.
assert word[-6] == 'P'  # Sixth from the end or zeroth from the beginning.

assert isinstance(word[0], str)

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring.

assert word[0:2] == 'Py'  # Characters from position 0 (included) to 2 (excluded).
assert word[2:5] == 'tho'  # Characters from position 2 (included) to 5 (excluded).
assert word[:2] + word[2:] == 'Python'
assert word[:4] + word[4:] == 'Python'
assert word[:2] == 'Py'  # Character from the beginning to position 2 (excluded).
assert word[4:] == 'on'  # Characters from position 4 (included) to the end.
assert word[-2:] == 'on'  # Characters from the second-last (included) to the end.

Attempting to use an index that is too large will result in an error.

with pytest.raises(Exception):
    not_existing_character = word[42]
    assert not not_existing_character

Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:

with pytest.raises(Exception):
    # pylint: disable=unsupported-assignment-operation
    word[0] = 'J'

If you need a different string, you should create a new one.

assert 'J' + word[1:] == 'Jython'
assert word[:2] + 'py' == 'Pypy'

The built-in function len() returns the length of a string.

characters = 'supercalifragilisticexpialidocious'
assert len(characters) == 34

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. The end of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

multi_line_string = '''\
    First line
    Second line
'''

assert multi_line_string == '''\
    First line
    Second line
'''

43.2.4.2.2. String operations#

Strings can be concatenated (glued together) with the + operator, and repeated with *.

assert 3 * 'un' + 'ium' == 'unununium'
assert 'Py' 'thon' == 'Python'

This feature is particularly useful when you want to break long strings:

text = (
    'Put several strings within parentheses '
    'to have them joined together.'
)
assert text == 'Put several strings within parentheses to have them joined together.'

If you want to concatenate variables or a variable and a literal, use +:

prefix = 'Py'
assert prefix + 'thon' == 'Python'

43.2.4.2.3. String methods#

hello_world_string = "Hello, World!"

The strip() method removes any whitespace from the beginning or the end.

string_with_whitespaces = " Hello, World! "
assert string_with_whitespaces.strip() == "Hello, World!"

The replace() method replaces a string with another string.

assert hello_world_string.replace('H', 'J') == 'Jello, World!'

The split() method splits the string into substrings if it finds instances of the separator.

assert hello_world_string.split(',') == ['Hello', ' World!']

The find() method searches the string for a specified value and returns the position of where it was found.

assert 'Hello, welcome to my world'.find('welcome') == 7

The replace() method returns a string where a specified value is replaced with a specified value.

assert 'I like bananas'.replace('bananas', 'apples') == 'I like apples'

The join() method joins the elements of an iterable to the end of the string.

my_tuple = ('John', 'Peter', 'Vicky')
assert '-'.join(my_tuple) == 'John-Peter-Vicky'

43.2.4.2.4. String formatting#

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.

43.2.4.2.4.1. Formatted string literals#

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.

An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal.

pi_value = 3.14159
assert f'The value of pi is {pi_value:.3f}.' == 'The value of pi is 3.142.'

Passing an integer after the : will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

table_data = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
table_string = ''
for name, phone in table_data.items():
    table_string += f'{name:7}==>{phone:7d}'

assert table_string == ('Sjoerd ==>   4127'
                        'Jack   ==>   4098'
                        'Dcab   ==>   7678')
43.2.4.2.4.2. The string format() method#

Basic usage of the str.format() method looks like this:

assert 'We are {} who say "{}!"'.format('knights', 'Ni') == 'We are knights who say "Ni!"'

The brackets and characters within them (called format fields) are replaced with the objects passed into the str.format() method. A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

assert '{0} and {1}'.format('spam', 'eggs') == 'spam and eggs'
assert '{1} and {0}'.format('spam', 'eggs') == 'eggs and spam'

If keyword arguments are used in the str.format() method, their values are referred to by using the name of the argument.

formatted_string = 'This {food} is {adjective}.'.format(
    food='spam',
    adjective='absolutely horrible'
)

assert formatted_string == 'This spam is absolutely horrible.'

Positional and keyword arguments can be arbitrarily combined.

formatted_string = 'The story of {0}, {1}, and {other}.'.format(
    'Bill',
    'Manfred',
    other='Georg'
)

assert formatted_string == 'The story of Bill, Manfred, and Georg.'

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets [] to access the keys.

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
formatted_string = 'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)

assert formatted_string == 'Jack: 4098; Sjoerd: 4127; Dcab: 8637678'

This could also be done by passing the table as keyword arguments with the ** notation.

formatted_string = 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)

assert formatted_string == 'Jack: 4098; Sjoerd: 4127; Dcab: 8637678'

43.2.4.3. Lists and their methods (including list comprehensions)#

Python knows several compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets.

43.2.4.3.1. List type#

Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner.

Here is an example of how to build a list.

squares = [1, 4, 9, 16, 25]

assert isinstance(squares, list)

Like strings (and all other built-in sequence types), lists can be indexed and sliced:

assert squares[0] == 1  # indexing returns the item
assert squares[-1] == 25
assert squares[-3:] == [9, 16, 25]  # slicing returns a new list

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:

assert squares[:] == [1, 4, 9, 16, 25]

Lists also support operations like concatenation:

assert squares + [36, 49, 64, 81, 100] == [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:

cubes = [1, 8, 27, 65, 125]  # something's wrong here, the cube of 4 is 64!
cubes[3] = 64  # replace the wrong value
assert cubes == [1, 8, 27, 64, 125]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = ['C', 'D', 'E']  # replace some values
assert letters == ['a', 'b', 'C', 'D', 'E', 'f', 'g']
letters[2:5] = []  # now remove them
assert letters == ['a', 'b', 'f', 'g']

Clear the list by replacing all the elements with an empty list.

letters[:] = []
assert letters == []

The built-in function len() also applies to lists.

letters = ['a', 'b', 'c', 'd']
assert len(letters) == 4

It is possible to nest lists (create lists containing other lists), for example:

list_of_chars = ['a', 'b', 'c']
list_of_numbers = [1, 2, 3]
mixed_list = [list_of_chars, list_of_numbers]
assert mixed_list == [['a', 'b', 'c'], [1, 2, 3]]
assert mixed_list[0] == ['a', 'b', 'c']
assert mixed_list[0][1] == 'b'

43.2.4.3.2. List methods#

list.remove(x) removes the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

assert fruits == ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana', 'grape']

fruits.remove('grape')
assert fruits == ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

with pytest.raises(Exception):
    fruits.remove('not existing element')

list.insert(i, x) inserts an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

fruits.insert(0, 'grape')
assert fruits == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

list.index(x[, start[, end]]) returns a zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item. The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

assert fruits.index('grape') == 0
assert fruits.index('orange') == 1
assert fruits.index('banana') == 4
assert fruits.index('banana', 5) == 7  # Find next banana starting a position 5

with pytest.raises(Exception):
    fruits.index('not existing element')

list.count(x) returns the number of times x appears in the list.

assert fruits.count('tangerine') == 0
assert fruits.count('banana') == 2

list.copy() returns a shallow copy of the list. Equivalent to a[:].

fruits_copy = fruits.copy()
assert fruits_copy == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

list.reverse() reverses the elements of the list in place.

fruits_copy.reverse()
assert fruits_copy == [
    'banana',
    'apple',
    'kiwi',
    'banana',
    'pear',
    'apple',
    'orange',
    'grape',
]

list.sort(key=None, reverse=False) sorts the items of the list in place. (The arguments can be used for sort customization, see sorted() for their explanation.)

fruits_copy.sort()
assert fruits_copy == [
    'apple',
    'apple',
    'banana',
    'banana',
    'grape',
    'kiwi',
    'orange',
    'pear',
]

list.pop([i]) removes the item at the given position in the list and returns it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position.)

assert fruits == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
assert fruits.pop() == 'banana'
assert fruits == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple']

list.clear() removes all items from the list. Equivalent to del a[:].

fruits.clear()
assert fruits == []

43.2.4.3.3. The del statement#

There is a way to remove an item from a list given its index instead of its value: the del statement.

import pytest

numbers = [-1, 1, 66.25, 333, 333, 1234.5]

del numbers[0]
assert numbers == [1, 66.25, 333, 333, 1234.5]

del numbers[2:4]
assert numbers == [1, 66.25, 1234.5]

43.2.4.3.4. List comprehensions#

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

squares = []
for number in range(10):
    squares.append(number ** 2)

assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named “number” that still exists after the loop completes. We can calculate the list of squares without any side effects using:

squares = list(map(lambda x: x ** 2, range(10)))
assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Or, equivalently (which is more concise and readable):

squares = [x ** 2 for x in range(10)]
assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

For example, this list comprehension combines the elements of two lists if they are not equal:

combinations = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
assert combinations == [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

And it’s equivalent to:

combinations = []
for first_number in [1, 2, 3]:
    for second_number in [3, 1, 4]:
        if first_number != second_number:
            combinations.append((first_number, second_number))

assert combinations == [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized. Let’s see some more examples:

vector = [-4, -2, 0, 2, 4]

Create a new list with the values doubled.

doubled_vector = [x * 2 for x in vector]
assert doubled_vector == [-8, -4, 0, 4, 8]

Filter the list to exclude negative numbers.

positive_vector = [x for x in vector if x >= 0]
assert positive_vector == [0, 2, 4]

Apply a function to all the elements.

abs_vector = [abs(x) for x in vector]
assert abs_vector == [4, 2, 0, 2, 4]

Call a method on each element.

fresh_fruit = ['  banana', '  loganberry ', 'passion fruit  ']
clean_fresh_fruit = [weapon.strip() for weapon in fresh_fruit]
assert clean_fresh_fruit == ['banana', 'loganberry', 'passion fruit']

Create a list of 2-tuples like (number, square).

square_tuples = [(x, x ** 2) for x in range(6)]
assert square_tuples == [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

Flatten a list using a list comprehension with two for.

vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flatten_vector = [num for elem in vector for num in elem]
assert flatten_vector == [1, 2, 3, 4, 5, 6, 7, 8, 9]

43.2.4.3.5. Nested list comprehensions#

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]

The following list comprehension will transpose rows and columns:

transposed_matrix = [[row[i] for row in matrix] for i in range(4)]
assert transposed_matrix == [
    [1, 5, 9],
    [2, 6, 10],
    [3, 7, 11],
    [4, 8, 12],
]

As we saw in the previous section, the nested list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:

transposed = []
for i in range(4):
    transposed.append([row[i] for row in matrix])

assert transposed == [
    [1, 5, 9],
    [2, 6, 10],
    [3, 7, 11],
    [4, 8, 12],
]

Which, in turn, is the same as:

transposed = []
for i in range(4):
    # the following 3 lines implement the nested listcomp
    transposed_row = []
    for row in matrix:
        transposed_row.append(row[i])
    transposed.append(transposed_row)

assert transposed == [
    [1, 5, 9],
    [2, 6, 10],
    [3, 7, 11],
    [4, 8, 12],
]

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case.

assert list(zip(*matrix)) == [
    (1, 5, 9),
    (2, 6, 10),
    (3, 7, 11),
    (4, 8, 12),
]

43.2.4.4. Dictionaries#

A dictionary is a collection that is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values.

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key-value pairs within the braces adds initial key-value pairs to the dictionary; this is also the way dictionaries are written on output.

fruits_dictionary = {
    'cherry': 'red',
    'apple': 'green',
    'banana': 'yellow',
}

assert isinstance(fruits_dictionary, dict)

You may access set elements by keys.

assert fruits_dictionary['apple'] == 'green'
assert fruits_dictionary['banana'] == 'yellow'
assert fruits_dictionary['cherry'] == 'red'

To check whether a single key is in the dictionary, use the keyword in.

assert 'apple' in fruits_dictionary
assert 'pineapple' not in fruits_dictionary

Change the apple color to “red”.

fruits_dictionary['apple'] = 'red'

Add new key/value pair to the dictionary.

fruits_dictionary['pineapple'] = 'yellow'
assert fruits_dictionary['pineapple'] == 'yellow'

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order. (If you want it sorted, just use sorted(d) instead.)

assert list(fruits_dictionary) == ['cherry', 'apple', 'banana', 'pineapple']
assert sorted(fruits_dictionary) == ['apple', 'banana', 'cherry', 'pineapple']

It is also possible to delete a key-value pair with del.

del fruits_dictionary['pineapple']
assert list(fruits_dictionary) == ['cherry', 'apple', 'banana']

The dict() constructor builds dictionaries directly from sequences of key-value pairs.

dictionary_via_constructor = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

assert dictionary_via_constructor['sape'] == 4139
assert dictionary_via_constructor['guido'] == 4127
assert dictionary_via_constructor['jack'] == 4098

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

dictionary_via_expression = {x: x**2 for x in (2, 4, 6)}
assert dictionary_via_expression[2] == 4
assert dictionary_via_expression[4] == 16
assert dictionary_via_expression[6] == 36

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments.

dictionary_for_string_keys = dict(sape=4139, guido=4127, jack=4098)
assert dictionary_for_string_keys['sape'] == 4139
assert dictionary_for_string_keys['guido'] == 4127
assert dictionary_for_string_keys['jack'] == 4098

43.2.4.5. Type casting#

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions.

  • int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number) literal, or a string literal (providing the string represents a whole number)

  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)

  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

Type casting to integer.

assert int(1) == 1
assert int(2.8) == 2
assert int('3') == 3

Type casting to float.

assert float(1) == 1.0
assert float(2.8) == 2.8
assert float("3") == 3.0
assert float("4.2") == 4.2

Type casting to string.

assert str("s1") == 's1'
assert str(2) == '2'
assert str(3.0) == '3.0'

43.2.5. 4. Your turn! 🚀#

Python programming basics - Your turn

43.2.6. 5. References#

  1. Python programming basic