0% found this document useful (0 votes)
41 views20 pages

Introduction To Python

The document introduces Python as a programming language that is easier to write and understand than languages like C/C++. It provides examples of simple Python code that is shorter and clearer than the equivalent C/C++ code. The document then covers basic Python concepts like variables, data types, printing, mathematical operations, conditionals, loops, functions and more in a tutorial-style format.

Uploaded by

Sebastian Oglage
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
41 views20 pages

Introduction To Python

The document introduces Python as a programming language that is easier to write and understand than languages like C/C++. It provides examples of simple Python code that is shorter and clearer than the equivalent C/C++ code. The document then covers basic Python concepts like variables, data types, printing, mathematical operations, conditionals, loops, functions and more in a tutorial-style format.

Uploaded by

Sebastian Oglage
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

Introduction to Python

Part 0: What is Python?

Short answer: Python is a programming language, like C/C++.

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++.

But then WHY is Python needed? Why is Python even a thing?


Why is it so liked by programmers and why do you hear every 3 rd tech blog you come across mentioning
it?

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.

This is a classic “Hello World” in C++ and in Python:

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

In python you don’t need to declare 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++.

Also, a variable can change its type.

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

Pretty much anything can be printed.


The print function takes any number of argument and prints them all, one after another, separated by a
single space, then prints a newline.

You can see the type of a variable using the type function:
Part 3: Ints, Floats, Numerical Operations

Python has mostly the same numerical operations as C/C++:

Python also has some additional operations that are missing from C/C++.
One of them is the “power” operation:

Another new operation is the “floor division”.


This is just division followed by approximation to the next lowest int.

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

Pretty much anything can be printed.


The print function takes any number of argument and prints them all, one after another, separated by a
single space, then prints a newline.

You can see the type of a variable using the type function:
Part 4: Booleans, Logical Operations

In Python Boolean are either “True” or “False”.


The first letter is uppercase, do not use “true” and “false” because you will get errors.

Logical operations like AND (&&), OR (||), NOT (!) from C/C++ are replaced with the actual words and,
or, not in Python.

Use parentheses to control what operations are evaluated first.

Numeric comparisons are almost the same as in C/C++:


You can cast variables to bool using the bool function:

Part 5: Strings

Strings can be delimited by both “ and ‘ but ‘ is recommended because it looks better.

Strings can be concatenated and even multiplied using + and *:

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:

Strings can be easily compared for equality:

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.

Part 6: If, While, For Statements

Statements and code in general look different in Python.

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:

This is an “if” statement with an “else” statement:

Python also has something does not exist in C/C++.


It’s called the “elif” statement (short for “else if”) and it look like this:

The “elif” statement can be used to mimic the “switch” statement from C/C++ if you need it:

Also, as you can see, the final “else” is not mandatory.

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 the above example the loop will exit when x becomes 5.


The “continue” statement simply “jumps” to the next iteration 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:

Actually, the Python “for” iterates trough a list of values:


(lists will be explained in part 8)

Part 7: Functions

You can define functions using the “def” keyword:

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:

Functions can even return more than 1 value.


Either assign the result of that function to the corresponding number of variables or assign it to a single
variable and that variable will receive an array (tuple, explained in part 8) with all of the return values:

Global variables are not automatically available in functions like in C/C++. The following code will
produce an error:

To make x available in the function we use the “global” statement:


The “global” statement tells Python to look for the global variable x and
use it whenever we ask for a variable named x in our function.

Similar to C/C++ we can give function parameters “default” values:

NOTE: If you give an argument a default value, you need to give ALL the arguments after it default
values.

It is a VERY GOOD practice to document your functions.


When you write a function, the first thing in the function should be a string created using 3 quote
symbols (“), in this string give a short description of the function:
Part 8: Lists, Tuples

In Python we need to store multiple values we have 2 options: Lists and Tuples.

Lists are (ironically) arrays or values.


These values do NOT need to be of the same type.
It is perfectly OK to have a list with ints, float and strings in it, Python can figure it out!
The same is also true for 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:

Also, lists and tuples can’t be concatenated to each other:

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.

There are many other methods or funtions that modify lists:

 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.remove(value) removes the first occurrence of value from lst.


 del lst[i] / del lst[i:j] removes the elemnent/slice at the given position.

 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.

 lst.reverse() / reversed(lst) reverses the order of elements in 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.

WARNING: Assigning a list only creates a pointer to that list.


Multiple variables can accidentally point to the same list and any modifications on that list will be seen
by all variables.
Use lst.copy() or list(lst) to create a copy of your list.

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.

 lst.index(value) returns the index of the first occurrence of value in lst.


 lst.count(value) returns the number of times value appears in lst.

 The in operator (value in lst) if value is in lst.

 max(lst) returns the biggest element in lst.


NOTE: max(lst) can also take any number of arguments and returns the largest one.

 min(lst) returns the smallest element in lst.


NOTE: min(lst) can also take any number of arguments and returns the smallest one.

 sum(lst) return the sum of the elements in lst.

Part 9: Exercises

1. To be discussed during the laboratory. 😊

You might also like