First steps in Python¶

Karën Fort (CC BY-NC-SA) -- 2024

This notebook corresponds to your first lecture and covers :

  • elementary data types: str, int, float, bool
  • basic input/output functions: print and input
  • basic good practices (naming, indentation, errors)
  • some tiny bits about Strings.

It is inspired from different sources:

  • Loic Grobol's material
  • Gaël Guibon's slides and lab material from Master TAL (Univ. de Lorraine)
  • W3School tutorial

Let's play!¶

Python allows you to perform simple (or complex) operations, like a calculator:

In [ ]:
6+6
In [ ]:
50 - 5*6
In [ ]:
(50 - 5*6) / 4

We can also compute powers:

In [ ]:
5 ** 2

⚠️ Beware of the difference between the division and the modulus (le reste):

In [ ]:
17 / 3
In [ ]:
17 % 3

There is another operator that extracts the quotient:

In [ ]:
17 // 3

🔆 Some operations run on things that are not numbers:

In [ ]:
3 * "toto"
In [ ]:
"this"+"is"+"a"+"test"

🥳 What do I need to add so that it forms a correct sentence?

In [ ]:
# TODO: code me!!

About elementary types¶

What is the difference between "this"+"is"+"a"+"test" and 1+1?

These are different "types" of data: text and numbers (among others).

We use markers to tell Python which is which. Without them...

In [ ]:
This+is+a+test

This is an error message, displayed by Python's interpreter. It's informative, once you get use to it ;-) Here, we have a problem with our syntax. is appears in a special color, because it's a reserved word for Python (it MEANS something to it).

In [ ]:
I+need+to+do+a+test

Ah! It says that "I" is not defined. In the language (Python). So it expects words from its own language, not words from English. We need to tell it that we're using English here. To do so, we need to use ""

In [ ]:
"I"+"need"+"to"+"do"+"a"+"test"

Or rather:

In [ ]:
"I need to do a test"

🥳 In the long geek tradition, display "Hello, world!", but in a language that is not English:

In [ ]:
# TODO: code me!!

There are other types in Python, we'll come to them later:

Types in Python

Source

About variables¶

Variables are containers to store values/data.

In Python, the variable is created when you assign it a value:

In [ ]:
Nb_Apples=12
print(Nb_Apples)
In [ ]:
Sentence="I have many apples in my bag"
print(Sentence)
In [ ]:
nb_pers = "one hundred and thirteen"
nb_pers = 113
print(nb_pers)
another_variable = None
print(another_variable)

In Python:

  • no need to explicitely add a type (vs Java): it automatically deduces the type from the value itself (and the "")
  • the type of a variable can be changed in time (nb_pers)
  • an empty variable is assigned the value None

Python is a:

  • strong: no implicit conversion of types (you have to explicit it)
  • dynamic: variable type is determined by the interpreter (compiler)
  • typed language

Types and how to change them¶

You can merge things that are of different types:

In [ ]:
print(Sentence)
print(Nb_Apples)

but you cannot print two different types together with a + (you can using other formatting, though):

In [ ]:
print(Sentence+Nb_Apples)

But you can cast (modify) the type of a variable:

In [ ]:
print(Sentence+str(Nb_Apples))
In [ ]:
print("I have "+str(Nb_Apples)+" apples in my bag.")

⚠️ You can make other kinds of type change, some of them will erase some data:

In [ ]:
yet_another_variable= 20 / 3
print(yet_another_variable)
print(int(yet_another_variable))

If you want to know exactly what is the type identified by Python, just ask:

In [ ]:
my_variable="For sure, this is a string"
type(my_variable)
In [ ]:
my_other_variable=42
type(my_other_variable)
In [ ]:
type(yet_another_variable)

Beware, some numbers can be characters (and not integers or floats) and they cannot be used to calculate:

In [ ]:
"5"+"3"

🥳 What is the type of nb_pers below?

In [ ]:
nb_pers = "one hundred and thirteen"
nb_pers = 113
nb_pers = str(113)

Booleans¶

We've seen str (strings), int (integers) and floats.

Another very common and useful type is bool (boolean), which can be either true or false:

In [ ]:
superior=10 > 2
print(superior)
print(type(superior))
print(bool("The sky is blue"))

Any string is True, except "" (empty string).

Any number is True, except 0.

Boolean operators¶

Boolean operators allow to test the truth value of an expression:

== allows to test if a value equals another value:

In [ ]:
print(10==5)

Conversely, != allows to test if a value is not equal to another:

In [ ]:
print(10!=5)

⚠️ Being equal (==) does not mean being the same object (is)

In [ ]:
a = 1000
b = 10**3

print(a==b) #Returns True if both are of the same value
print(a is b) #Returns True if both are the same object in memory

print(id(a)) #Returns the unique id for the specified object
print(id(b))

in checks the inclusion:

In [ ]:
my_string = "Demain dès l'aube, à l'heure où blanchit la campagne"
"Demain" in my_string

Conversely, not in allows to test if a value is not included in another:

In [ ]:
my_string = "Demain dès l'aube, à l'heure où blanchit la campagne"
"Pouet" not in my_string

Documentation¶

Apart from what you'll find online (I recommend this), note that some documentation is directly accessible:

In [ ]:
help(print)

Comments:

In [ ]:
6+9 #this is a comment on a single line (this is not executed)

A bit about functions¶

print() and help() are functions.

In print("Hello, world!"), print is a function call and "Hello, world!" is its argument.

In Python, functions can be thought of as the description of actions that we ask the computer to perform: here "print the message I gave you as argument".

Arguments (or parameters) of a function are used to specify the elements on which the action is called. There can be just 1, several, or zero.

Another function that can be useful rapidly is input(), which prompts the user to enter a string (sent by pressing entry) and returns this string to the program:

In [ ]:
print("What's your name?")
my_name=input()
print('Hello, ' + my_name) 
In [ ]:
my_name=input("What's your name? ")# This is also possible (and cleaner)
print('Hello, ' + my_name) 

The print function now allows to get fancy outputs using formatted string litterals:

In [ ]:
my_name=input("What's your name? ")
print(f"Hello, nice to meet you {my_name}")# This is also possible

A bit about strings¶

Strings in Python are arrays (?) of bytes (?) representing Unicode (?) characters.

This means characters in the string can be accessed like elements in an array:

In [ ]:
my_name[1]

and yes, in Python, we count from 0... So:

In [ ]:
my_name[0]

Note: "unicode" means that you can use any natural language in a string:

In [ ]:
a_name_in_russian="мишка"
print(a_name_in_russian)
print("I can even write in Russian: "+a_name_in_russian) # you can mix languages

🥳 A useful function for strings is len(), but what does it do?

In [ ]:
len(a_parameter)

⚠️ indentation is part of Python!

In [ ]:
print("What's your name?")
    my_name=input()
print('Hello, ' + my_name) 

Good Practices¶

Variable names¶

  • have to be clear and understandable
  • only alpha-numeric characters and underscores (no space)
  • case sensitive (nb is not the same as Nb)
  • cannot start with a number
  • cannot be any of the Python keywords:
In [ ]:
import keyword #this allows to use a standard library (piece of code)
print(keyword.kwlist)

Multi words variable names¶

There are different ways of writing multi words variable names

Pick yours, stick to it

In [ ]:
myVariableName = "ma variable" #Camel Case
MyVariableName = "ma variable" #Pascal Case
my_variable_name = "ma variable" #Snake Case

Documenting your code¶

Why you should document your code

Recommendations¶

  • breathe
  • read (carefully) the error messages
  • proceed step by step (do not rush it)
  • write clear code

Going further¶

  • Booleans: Loic Grobol's exercices