Introduction To Python
Introduction To Python
It has variables with values in them, it has an “if” instruction, a “while” instruction, libraries you can
include to use their functions, and so on.
We can make in Python any algorithm we could make in C/C++.
For several reasons, but the main reason is that the code is much shorter, faster to write and easier to
understand.
A Python program is usually at least 3-5 times shorter than the same C/C++ program.
C++ Python
One thing you might notice is that there is much less setup, no including things for a simple print
function, no “main” function, no braces, the file IS the “main” function.
Another cool thing about Python is that it offers us quite a few more functions and possibilities than C++
so we end up with less code that is also easier to read.
Let’s say you have a list of numbers and you want to have another list, containing the doubles of only
the odd numbers.
Let’s compare the C++ and Python codes:
C++ Python
Don’t worry if you don’t completely understand the Python code. It’s still just a “for” and an “if”, but the
people who made Python knew
that lots of times a “for” and an “if” are used together to transform one list of numbers into another, so
python has a way to create
a list (or array) of numbers using “for” and “if” all in 1 instruction!
It’s the same code, but it’s simpler and shorter in Python!
NOTE:
This is not a complete Python course.
This is a quick introduction that should prepare you for most things you will see in the laboratories.
Some Python tricks and features will be omitted to keep things simple.
If you see something online that is not explained here this is probably the reason why.
Part 1: Variables
If you assign a value to a variable called X and that variable does not exist, Python knows
that you probably want to declare that variable, so it does that for you!
Python can also figure out the type of a variable based on what value you are assigning.
NOTE 1: Comments are done using the “#” symbol just like we use “//” in C/C++.
NOTE 2: Strings are delimited by either “ or ‘ but ‘ recommended because it’s easier to read.
NOTE 3: “None” is the closest thing to “NULL” from C/C++.
Python can figure out that if you assign a “string” to a variable that contains and “int”
then the type of that variable should probably change!
Python does not have 8-10 types of int, 4-6 types of float and a couple types of string like C/C++.
In Python the main types are:
int – A whole number. From -infinity to +infinity. Python can handle any limits in the
background, 2^1000 is no problem! (but it might be slow to calculate)
float – A C/C++ “double” (or float64).
bool – True or False
string – A sequence of characters. It can have 0, 1 or any number of characters.
Part 2: Printing
You can see the type of a variable using the type function:
Part 3: Ints, Floats, Numerical Operations
Python also has some additional operations that are missing from C/C++.
One of them is the “power” operation:
You can also use assignment-operations with any other operation just like in C/C++:
You can cast variables to int and float using the int and float functions:
Part 3: Printing
You can see the type of a variable using the type function:
Part 4: Booleans, Logical Operations
Logical operations like AND (&&), OR (||), NOT (!) from C/C++ are replaced with the actual words and,
or, not in Python.
Part 5: Strings
Strings can be delimited by both “ and ‘ but ‘ is recommended because it looks better.
If you want to put the value of a variable in a string you need to put an “f” in front of the string,
then the variable can be placed between “{}” inside the string:
You can also check if a string exists in another string using the in and not in operators:
You can cast variables to string using the str function:
You can get specific characters of a string by indexing it just like any other array.
If your index is a negative number then the indexing starts from the end of the string.
You can also slice a string using s[a:b]. You will get the substring starting at s[a] and ending just before
s[b].
If a is missing (s[:b]) the slicing will start from the beginning of the string.
If b is missing (s[a:]) the slicing will start at a and will continue to the end of the string.
You can also add a 3rd component to slicing. s[a:b:c] will give you the first char in s[a:b] and every cth
character after that.
You can get the length of the string using the len function:
A string is a class, and it has methods (or member functions), for working with strings:
The string class has many more methods and several different ways to use most methods.
To see the documentation of a method in PyCharm highlight that method in your auto-complete list and
press Ctrl+Q,
or click on a function or method in your code and press Crtl+Q.
One difference is that we do not use “{}” to delimit our blocks of code, instead, we use indentation (see
above).
If a bunch of statements are indented under the same “if“ statement then they should all probably be
executed if that “if“ statement executes (see above).
It is heavily recommended to use 4 spaces as indentation.
NOTE: PyCharm knows to insert 4 spaces by default when you press the “tab” key.
However we have to put a “:” after a while/if/for to tell it that the code inside the while/if/for is next
(see above).
When you are just starting out in Python you are going to forget the “:” a lot. Don’t worry about it, you’ll
get used to it!
Another difference is that we do not use “()” to delimit logical conditions. We can if we want to but it
looks nicer with no “()” (see above).
IF Statements:
This is a simple “if” statement:
The “elif” statement can be used to mimic the “switch” statement from C/C++ if you need it:
WHILE Statements:
A “while” statement looks just like you would expect it to:
Python also supports break and continue just like C/C++.
The “break” statement breaks out of the loop:
In this case when x is 3, 6, 9 the number will not be printed, x will just be increased
and then the loop will immediately start the next iteration.
In Python we don’t have “do…while” statement but we can easily create one:
Be careful to not forget a “break” statement in this case or your “while” will run forever!
FOR Statements:
The “for” statement is a little different in Python.
If you want to emulate a C/C++ “for” then the function “range” can let you iterate trough consecutive
numbers.
“range(n)” will give you all the numbers from 0 to n-1:
“range(n, m)” will give you all the numbers from n to m-1:
“range(n, m, k)” will give you every k’th number from n to m-1 starting with n:
Part 7: Functions
As usual, python can figure out the types of the arguments and the type of the return value.
To make a function that returns a value simply add a “return” statement:
Functions with no “return” statement always return None. If you want you can treat them like “void”
functions from C/C++.
Functions can also have more than 1 return statement:
Global variables are not automatically available in functions like in C/C++. The following code will
produce an error:
NOTE: If you give an argument a default value, you need to give ALL the arguments after it default
values.
In Python we need to store multiple values we have 2 options: Lists and Tuples.
The difference between lists and tuples is that we can change the value of an element
in a list but tuples are immutable, they are “const arrays”.
To create a list/tuple we can either use the list()/tuple() function or we can use square brackets (“[]”)
for lists or parenthesis for tuples (“()”):
Lists can be indexed and concatenated and multiplied just like strings:
But only elements of a list can be reassigned:
To convert between list and tuple you can use the list() and tuple() functions:
Both lists and tuples can be used with the for statement:
Both lists and tuples can contain other lists and tuples (we can simulate matrices this way):
To get the length of a list or tuple use the len function (just like with strings):
There are several ways of adding elements to lists and tuples:
NOTE:
Lists can be modified. Appending to the list changes the list itself.
Tuples can’t be modified. Appending to a tuple creates an entirely new tuple and assigns it to x.
lst.insert(i, value) inserts value into lst at position i pushing the old element at position i (and all
the elements after it) to the right by 1 position.
Assigning a list to a slice of another list replaces all the elements of the slice.
lst.pop(i) removes the value as position i from lst and returns that value.
lst.clear() / del lst[:] removes all the elements from the list lst.
NOTE: reversed() returns a new list instead of modifying the existing one so the result has to be
asigned to a variable.
NOTE: Because reversed() doesn’t change lst but creates an entirely new list it also works on
tuples.
lst.sort() / sorted(lst) sorts the elements in the list lst.
NOTE: sorted() returns a new list instead of modifying the existing one so the result has to be
asigned to a variable.
NOTE: Because sorted() doesn’t change lst but creates an entirely new list it also works on
tuples.
There are also several functions and methods to get information on lists:
NOTE: Since these methods and functions do not modify the list, they also work on tuples.
Part 9: Exercises