Types and variables

Author

Ludovic Deneuville

Before starting

Introduction

In this notebook, we will discover the basic types in Python:

  • numeric
    • int: integers
    • float: decimals
  • character strings: str
  • booleans: bool

1 Variable assignment

# Create variable a and assign it the value 8
a = 8

# Create variable b and assign it the string "texte"
b = "texte"

# Create variable c and assign it the boolean True
c = True
# Display the content of a
a

Note: A notebook only displays the last value requested from it. To display several values, you must use the print method.

print(a+1)
print(b)
print(c)

Python is a dynamically typed language. This means that it is possible to modify the type of a variable without constraints. If the variable a contains text, it is possible to assign it an integer afterwards.

print(a)
a = "abcd"
print(a)
a = False
print(a)

Tip: To display all created variables and their values, you can use the %whos command.

%whos

2 Numbers

The type function allows you to know the type.

a = 8
type(a)
b = 33.5
type(b)
float('inf')

2.1 Conversions

The float and int functions can be used to switch from one type to another.

# Conversion to float
float(a)
# Conversion to int (integer part)
int(b)
# Scientific notation
2.1e3

2.2 Basic arithmetic operations

# Addition
1 + 1
# Subtraction
6 - 2
# Multiplication
3 * 4
# Division
11 / 5
# Euclidean division: quotient
11 // 5
# Euclidean division: remainder (modulo)
11 % 5
# Power
2 ** 10
# Square root
36 ** 0.5

3 Character strings

Character strings (strings) are used to store textual information.

A string is defined by putting the information between single quotes ' or double quotes ".

3.1 Definition

a = 'a string defined with single quotes'
a
b = "a string defined with double quotes"
b
# To include an apostrophe inside the string
"j'inclus l'apostrophe"
# To include double quotes inside the string
'les "guillemets" sont là'

3.2 Useful methods

Here is an overview of some useful methods. Many others exist (see official documentation)

# String length (number of characters)
len("J'ai 18 caractères")
# Concatenation
"I am" + "your father"
" ".join(["I am", "your father"])
# Concatenation with a number
year = 2
"je suis en " + year + "ème année"

Problem: the number must first be converted into a string. The str method does the job.

# Concatenation with a number - after converting the number to a string
year = 2
"je suis en " + str(year) + "ème année"
# Repetition
"hop " * 5
# Convert to uppercase
"C'est OK".upper()
# Convert to lowercase
"C'est OK".lower()
# Count the number of occurrences
"Mangez cinq fruits et légumes par jour".count("a")
# Create a list of words
"Mangez cinq fruits et légumes par jour".split()
# Split words according to a specific character
"un-deux-trois-soleil".split("-")
# Use strings as templates
"mon numéro est : {}".format("06 12 34 56 78")
# Starts with ?
"vélo".startswith("vé")
# Ends with ?
"vélo".endswith("lo")

3.3 Extracting substrings

A string is considered in Python as a list of characters. It is therefore possible to extract different elements from this list.

# First element
"c'est de toute beauté"[0]
# Second element
"c'est de toute beauté"[1]
# Last element
"c'est de toute beauté"[-1]
# From a specific character
"c'est de toute beauté"[6:]
# Up to a specific character
"c'est de toute beauté"[:8]
# Extract a substring
"c'est de toute beauté"[9:14]
# Extract every 2 characters, starting from the 4th position
"c'est de toute beauté"[4::2]
# Reverse a string
"c'est de toute beauté"[::-1]

Special characters

To insert special characters within a string, you must use the escape character \.

Character Description

Escape character
' Apostrophe
" Double quotes
New line
Horizontal tab
Carriage return
c = "une chaîne\nsur 2 lignes"
print(c)
# Define a string over multiple lines
d = """une autre \"possibilité\" pour
avoir une chaîne sur 2 lignes"""
print(d)

4 Booleans

Booleans can only take two values: True and False Be careful to respect the notation with the first letter uppercase and the others lowercase.

type(True)

4.1 Comparison operators

Operator Meaning
== Equal to
!= Not equal to
< Strictly less than
> Strictly greater than
<= Less than or equal to
>= Greater than or equal to
8 > 5
1+1 == 2
[1, 2, 3] == [1, 2, 3]
"girafe" != "gnou"
# Chained operators
1 < 2 == 2 >= 1 != 2

4.2 and, or, not operators

a = True
b = False

a and b
a or b
not a
(a or b) and (a and not b)

5 Exercises

5.1 Exercise 1

Calculate the sum of the lengths of the following three strings:

  • “une première chaîne”
  • “et une deuxième”
  • “jamais deux sans trois”
# Type your answer in this cell

5.2 Exercise 2

What is the appropriate type for defining a postal code?

Try defining the following postal codes in int format and string format:

  • 92120
  • 02350

What do you conclude?

# Type your answer in this cell

5.3 Exercise 3

Count the number of times the letter e appears in the following string: Je compte le nombre de e dans cette chaîne de caractères

# Type your answer in this cell

5.4 Exercise 4

Find the first position where the letter e appears in the following string: “Je fais un comptage des e.”

Hint: you can use the built-in find method.

# Type your answer in this cell

5.5 Exercise 5

Remove unnecessary spaces at the beginning and end of the following string:

Hint: you can use the built-in strip method.

# Type your answer in this cell
a = "    Un string très mal formatté.         "

5.6 Exercise 6

Perform the following operations using increment operators, and print the final value:

  • initialize a variable to 1
  • subtract 5 from it
  • multiply it by 4
  • add 22 to it
# Type your answer in this cell

5.7 Exercise 7

Consider the following two sequences:

  • “nous sommes en”
  • “2022”

Using the tutorial, find two different ways to use them to compose the sequence “nous sommes en 2022”.

# Type your answer in this cell