There are two major categories of programming languages: compiled and interpreted.
A compiled language is a language that is turned by a compiler into direct machine code that runs upon the CPU. (Or it might run on a virtual machine stack like the JavaVM or the .NET runtime.)
An interpreted language is a language that is read in its raw form and executed a statement at a time without being first compiled.
Python is an interpreted language.
A notebook contains cells, each cell is a logically separate and independent information.
There are 2 main type of cells:
Note: you can find a User Interface Tour in the Help menu.
Literals are constants primitive values. They can be e.g. numbers or strings (texts). Strings are surrounded with quotation marks or apostrophes.
"Hello World"
'Hello Earth'
42
Syntax: print
is a function, which has an argument. The argument is surrounded by parentheses.
print('Hello World')
print("Hello Earth")
print(4)
Task: what is the problem with the following codes?
print(Hello ELTE!)
print "Hello Faculty of Informatics!"
Lines starting with the %
symbol are not regular Python instructions, instead they are special commands for the Jupyter Notebook.
We can load the content of an external file with the special %load
command:
# %load ../data/01_outerfile.py
print('Great! This line was print from an external file!')
Note that after the loading the original %load
command is commented out and instead the content of the external file is loaded.
We can execute the content of an external file with the special %run
command.
Specifying the -i
flag is important, so the file is executed in the same environment with the Jupyter notebook. Therefore, if we e.g. declare a variable in the external script, it will be accessible in the code cells of the notebook.
If the -i
flag is not specified, the external Python file is evaluated in a separate environment.
%run -i ../data/01_outerfile.py
Variables can be considered containers. You can put anything inside a container, without specifying the size or type, which would be needed in e.g. Java, C++ or C#. Note that Python is case-sensitive. Be careful about using letters in different cases.
When assigning values, we put the variable to be assigned to on the left-hand side (LHS), while the value to plug in on the right-hand side (RHS). LHS and RHS are connected by an equal sign (=
), meaning assignment.
x = 3 # integer
y = 3.1 # floating point number
z = "Hello!" # strings
Z = "Wonderful!" # another string, stored in a variable upper-case z.
print(x)
print(y)
print(z)
print(Z)
You can do operations on numeric values as well as strings.
sum_ = x + y # int + float = float
print(sum_)
v = "World!"
sum_string = z + " " + v # concatenate strings
print(sum_string)
There are two commonly used naming style in programming:
All variable (function and class) names must start with a letter or underscore (_). You can include numbers.
myStringHere = 'my string'
myStringHere
x = 3 # valid
x_3 = "xyz" # valid
3_x = "456" # invalid. Numbers cannot be in the first position.
You can choose either camel case or snake case. Always make sure you use one convention consistently across one project.
In this section, we go over some common primitive data types in Python. While the word primitive looks obscure, we can think of it as the most basic data type that cannot be further decomposed into simpler ones.
For numbers without fractional parts, we say they are integer. In Python, they are called int
.
x = 3
print(type(x))
For numbers with fractional parts, they are floating point numbers. They are named float
in Python.
y = 3.0
print(type(y))
We can apply arithmetic to these numbers. However, one thing we need to be careful about is type conversion. See the example below.
z = 2 * x
print(type(z))
z = y + x
print(type(z))
In Python, we use str
type for storing letters, words, and any other characters.
To initialize a string variable, you can use either double or single quotes.
my_word = "see you"
print(type(my_word))
Unlike numbers, str
is an iterable object, meaning that we can iterate through each individual character.
You can think of strings as a sequence of characters (or a list of characters, which we will cover later). In this case, indices and bracket notations can be used to access specific ranges of characters.
print(my_word[1]) # character with index 1; Python starts with 0 NOT 1
print(my_word[2:6]) # [start, end), end is exclusive
print(my_word[-1]) # -1 means the last element
We can also use +
to concatenate different strings
my_word + ' tomorrow'
Print with formatting with the format()
function and using placeholders:
print("The sum of x and y is {0}".format(sum_))
print("The string `sum_string` is '{0}'".format(sum_string))
print("The sum of x and y is {0} and the string `sum_string` is '{1}''".format(sum_, sum_string))
Boolean type comes in handy when we need to check conditions. For example:
my_error = 1.6
compare_result = my_error < 0.1
print(compare_result)
print(type(compare_result))
There are two and only two valid Boolean values: True
and False
. We can also think of them as 1
and 0
, respectively.
print(my_error > 0)
When we use Boolean values for arithmetic operations, they will become 1 / 0
implicitly.
print((my_error > 0) + 2)
Since variables in Python are dynamically typed, we need to be careful about type conversion.
When two variables share the same data type, there is not much to be worried about:
s1 = "no problem. "
s2 = "talk to you later"
s1 + s2
But be careful when we are mixing variables up:
a = 3 # recall that this is an ____?
b = 2.7 # how about this?
c = a + b # what is the type of `c`?
print(c)
print(type(c))
To make things work between string and numbers, we can explicitly convert numbers into str
:
print(s1 + 3)
print(s1 + str(3))
We may also convert strings to numbers:
s3 = "42"
d = int(s3)
print(type(s3), type(d))
User input can be easily requested in Python:
k = input('Question')
The question text is arbitrary. The user will see a console input prompt. The typed input will be stored in the k
variable by Python. Example:
k = input('What is your name? ')
print('Hello ' + k)
Question: what is the type of the value in variable k
?
print(type(k))
Task: Query the height of the user.
Print afterward that Your height is XXX centimeter.
Print the type of the variable storing the height of the user.
height = input("What is your height? ")
print("Your height is {0} centimeters.".format(height))
print(type(height))
Variables assigned by the input function will always contain strings. (We will cover error handling later.)
Task: Question the user for the amount of days he/she works a week and his/her gross salary per hour (in euro).
Calculate and print the monthly gross salary of the user.
Calculate and print the monthly net salary of the user, assuming that the net salary is 65% of the gross salary.
Assume that a month consists of 4 weeks and a working day consists of 8 working hours.
work_days = int(input("Number of work days per week? "))
salary_hour = int(input("Salary per hour? "))
salary_gross = 4 * work_days * 8 * salary_hour
salary_net = salary_gross * 0.65
print("Gross salary: {0} euros / month".format(salary_gross))
print("Net salary: {0} euros / month".format(salary_net))