Basics of Programming with Python#
of
Syntax
Order of execution
Variables
Data types
Syntax#
In Python, every line is a new statement. It’s not possible to have multiple statements in one line.
print('(Un)Creative ')
print('Coding ')
print('with Python')
(Un)Creative
Coding
with Python
print('(Un)Creative ') print('Coding ') print('with Python')
Cell In[8], line 1
print('(Un)Creative ') print('Coding ') print('with Python')
^
SyntaxError: invalid syntax
When writing code, we’ll often receive an SyntaxError
, meaning that the code is not executable.
The ^
indicates the position of the error.
Order of execution#
The code is executed from top to bottom. Later we’ll see that it’s possible (and common) to write code that’s less linear.
Variables#
A very powerful concept in programming is the variable
. We can store data in variables and use it multiple times through the program, but also change it during the process of execution.
Variables are created through a name of your choice followed by =
followed by the data you want to store in it. Allowed characters for variable names: characters, numbers, ‘_’ (underscore). It’s not allowed to start a name with a number. In Python it’s convention to write regular variables in lowercase characters and separate them with _.
s1 = '(Un)Creative'
s2 = 'Coding'
s3 = 'with Python'
print(s1, s2, s3)
print(s2, s3)
print(s1)
(Un)Creative Coding with Python
Coding with Python
(Un)Creative
The data inside variables is not fixed. We can override or modify it.
a = 7
print(a)
a = a * 2
print(a)
a *= 2
print(a)
a /= 2
print(a)
b = 4
a += b
print(a)
7
14
28
14.0
18.0
Data types#
We’ve got in touch with 3 different types
of data already:
String (text)
Integer (whole numbers)
Float (floating point numbers)
We can check the type of data with the function type()
.
# String
s = 'Some text.'
print(type(s))
# Integer
n1 = 58626
print(type(n1))
# Float
n2 = -25.66
print(type(n2))
<class 'str'>
<class 'int'>
<class 'float'>
Variables do not need to be created with a specific data type (as in some other programming languages). It’s also possible to change the type (it’s done automatically) according to the data we put into it.
a = 'Some text'
a = 4
a = 0.2
Converting data types (casting)#
It’s easy to convert data into a specific type with built-in methods. This is called casting.
str(4.2)
'4.2'
str(5)
'5'
int('7')
7
int(7.4)
7
float('7')
7.0
float(4)
4.0