Introduction to Python
2. Lecture: First steps
Dr. Annika Bork-Unkelbach, Dr. Jutta Vüllers, Dr. Julia Fuchs |
KIT – Die Forschungsuniversität in der Helmholtz-Gemeinschaft [Link]
Overview
1. Introduction
Python interactive
Run a simple python program from file
2. Variables and data types
Numeric data types
Text types: Strings
Set types
3. Comments
4. Code styling
5. How to work with this exercise
Introduction Variables and data types Comments Code styling How to work with this exercise
2/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Python interactive
After successfully installing python on your machine, we are now ready to use python as a calculator: Open the
Anaconda prompt (Windows) or a terminal (Ubuntu)
python
Now you can try different calculations:
3+5
4*8
365/12
In order to leave python, type:
exit()
Introduction Variables and data types Comments Code styling How to work with this exercise
3/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Arithmetric Operators
Arithmetic operators are: + , − , ∗ , ∗∗ , / // , %
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x ** y exponential calculation of x and y (x y )
x / y quotient of x and y
x // y integer division of x and y. Result is rounded down to a whole number.
x % y returns the remainder of dividing x and y
Introduction Variables and data types Comments Code styling How to work with this exercise
4/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Python interactive: Print output
Output can be printed to the user with the (build in) print function:
print("Hi, welcome to the python course")
print(3+8+2)
Introduction Variables and data types Comments Code styling How to work with this exercise
5/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Run a simple python program from file
As your programming task might become more complex, you can save the code to a file and execute it. Open a
text editor and write down the following commands:
print("Hi, welcome to the python course")
print("Let's get started")
Save everything to a python file using an appropriate name ([Link]). Next, open the Anaconda prompt
(Windows) or terminal (Ubuntu) and navigate to the folder containing your python file.
python [Link]
Introduction Variables and data types Comments Code styling How to work with this exercise
6/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Python IDE: Jupyter
For more complex programming tasks, it is convinient to use an Integrated Development Environment (IDE). In
the last lecture we introduced Jupyter Lab, which can be started like this:
Open the Anaconda prompt (Windows) or a terminal (Ubuntu) and acitvate your Anaconda environment:
activate name_of_environment (Windows)
source activate name_of_environment (Ubuntu)
Afterwards, start Jupyter Lab and click on the link:
jupyter lab
Introduction Variables and data types Comments Code styling How to work with this exercise
7/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Introduction to variables: What is a varaible?
Print a greeting message to the user:
print("Hello user 1")
print("Hello user 2")
Variables make your code shorter and more flexible:
name = "user name"
print("Hello ", name)
name = input("What is your name: ")
print("Hello ", name)
Introduction Variables and data types Comments Code styling How to work with this exercise
8/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Introduction to variables: Naming convention
Variable names can contain letters, numbers and underscores
NameOfVariable = 123 #Pascal case
nameofVariable = 123 #Camel case
name_of_variable = 123 #Snake case
name_of_variable_1 = 123
Variable names can not start with a number
Varaible names can not contain spaces
Avoid python key words in variable names
Try to make your variable names short but descriptive
v_n = 123 #ok
variable_name = 123 #much better!
Introduction Variables and data types Comments Code styling How to work with this exercise
9/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Introduction to data types
Variables describing a car:
year_of_construction = 2023
cubic_capacity = 2.5
brand = 'best car ever'
new_car = True
print("year of construction: ", year_of_construction, "new car: ", new_car
print("brand: ", brand, "cubic capacity: ", cubic_capacity)
year_of_construction = 2023.2
cubic_capacity = "enormous"
brand = 425
new_car = "yes"
print("year of construction: ", year_of_construction,"new car: ", new_car)
print("brand: ", brand, "cubic capacity: ", cubic_capacity)
Introduction Variables and data types Comments Code styling How to work with this exercise
10/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Python data types
Numeric Types: int, float, complex
Text Type: str
Boolean Type: bool
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Binary Types: bytes, bytearray, memoryview
Note Type: NoneType
Find out about the data type of a variable:
print(type(variable))
Introduction Variables and data types Comments Code styling How to work with this exercise
11/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Numberic data types
data type explanation examples
int signed integer 10, −13, 3745786067
float floating point real values 0.0, -24.6, 56.3e18
complex complex numbers 5.4-3j, 6j, -84j
Type conversion can be performed using the int() , float() , complex() method.
Keep in mind: int() will simply cut the decimals so e.g. 2.7 will be converted to 2.
float_variable = 2.7
int variable = int(float_variable)
_
Introduction Variables and data types Comments Code styling How to work with this exercise
12/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Text types: Strings
'This is a string'
"This is also a string"
Strings are continuous set of characters.
Strings are surrounded by single or double quotation marks.
Strings can be used to read in text from user / data file.
Can be processed, saved or used for output.
Subsets of strings can be taken using the slice operator ( [ ] and [:] ).
Indices starting at 0 for the beginning of the string and ending with -1 for the end. Negative indices
possible.
String concatenation with the plus (+) sign, repetition with the asterisk (*)
Introduction Variables and data types Comments Code styling How to work with this exercise
13/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Text types: Strings
str = 'Hello World!'
str2 = " Nice to meet you. "
str # Prints complete string
str[0] # Prints first character of the string
str[2:] # Prints string starting from 3rd character
str * 2 # Prints string two times
str + str2 # Prints concatenated string
'Hello World!'
'H'
'llo World!'
'Hello World!Hello World!'
'Hello World! Nice to meet you.'
Introduction Variables and data types Comments Code styling How to work with this exercise
14/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Set types: Lists
Lists are used to store multiple items which can be of different data types.
List items are ordered, changeable and allow duplicates
To create a list we use square brackets and items are separated by comma.
Introduction Variables and data types Comments Code styling How to work with this exercise
15/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Set types: Lists
list1=[2,6,7,3]
list2=['Hello',list1,485.3]
print(list1) # Prints complete list
print(list2[0]) # Prints first element of list
print(list1 + list2) # Concatenates list
print(list2[1][0]) # Prints first element of the second element
Output:
[2,6,7,3]
'Hello'
[2,6,7,3,'Hello',[2,6,7,3],485.3]
2
Introduction Variables and data types Comments Code styling How to work with this exercise
16/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Set types: Tuple
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable. I.e. the order cannot be changed and we
cannot add or remove items from a tuple.
Tuples are written with round brackets and comma separated.
To change a tuple you have to convert it to a list, change it and then convert it back to a tuple.
To add items to a tuple you have to convert it to a list or add a tuple to a tuple.
tpl1=('tom','alice',4)
#if you have a single item as a tuple, you have to add a comma
tpl2=('tennis',)
Introduction Variables and data types Comments Code styling How to work with this exercise
17/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Set types: Sets
Sets are unordered
Set elements are unique. Sets do not allow duplicate elements.
A set itself may be modified, but the elements contained in the set must be of an immutable data type:
integer
float
complex
boolean
string
bytes
tuple
color_set = set(['green', 'red', 'blue', 'yellow', 'red']) # recommended way
color_set = {'green', 'red', 'blue', 'yellow', 'red'} # allowed, but not recommended
Introduction Variables and data types Comments Code styling How to work with this exercise
18/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Set types: Frozensets
A frozenset is Python build-in data type which is almost identical to the set data type, except that it is immutable.
This means, you can only perform non-modifying operations on a frozenset:
color_set = frozenset(['green', 'red', 'blue', 'yellow', 'red']) # recommended way
Introduction Variables and data types Comments Code styling How to work with this exercise
19/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Comments
In Python, comments are indicated by the hash mark # . Any text or code following the hash mark in this line is
ignored by the Python interpreter:
# print a greeting message
print("Hello ")
Comments are useful to ...
increase the readability of your code
explain your code to others (teammates, python tutors)
help you understand your own code after some time
Introduction Variables and data types Comments Code styling How to work with this exercise
20/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
Code styling: Python Enhancement Proposals (PEP)
Python is open source and hence used and developed by many people / teams. Differences in coding style or
module implementation can cause problems in collaborating and contributing to other projects.
The Python Enhancement Proposals (PEPs) is a set of design documents including guidlines on how to style
code or implement new modules.
Please write your code according to the guidelines provided in the PEP8- Style Guide for Python Code:
[Link]
Introduction Variables and data types Comments Code styling How to work with this exercise
21/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF
How to work with this exercise
The examples and exercises in todays Jupyter Notebook are intended to WORK with. Please always...
... read the instructions carefully
... copy an example cell and paste it below
... run the code and see what happens
... modify the code and run it again
... document your findings in an additional Markdown cell below
... make sure to answer all the questions
... make comments
Introduction Variables and data types Comments Code styling How to work with this exercise
22/22 Annika Bork-Unkelbach, Jutta Vüllers, Julia Fuchs : Scientific programming IMK-ASF