Chapter 8:
Introduction to Python
Alex Kuhudzai
[email protected]
Cape Peninsula University of Technology,
Cape Town, South Africa
Ask
The art and science of asking questions is the source of all
knowledge.
- Thomas Berger
Do not hesitate to ask!
If something is not clear, stop me and ask.
During exercises (you can also ask others).
Image by mohamed Hassan from Pixabay
Failure
Coding is all about trial and error.
Don't be afraid of it.
Error messages aren't scary, they are useful.
Python natalensis by A. Smith on Wikimedia Commons
History
Started by Guido Van
Rossum as a hobby Guido Van Rossum
by Doc Searls
on Flickr CC-BY-
Now widely spread SA
Open Source! Free!
Versatile
Python today
Developed a large and active scientific computing and data
analysis community
Now one of the most important languages for
Data science
Machine learning
General software development
Packages: NumPy, pandas, matplotlib, SciPy, scikit-learn,
statsmodels
2 Modes
1. IPython
Python can be run interactively
Used extensively in research
2. Python scripts
What if we want to run more than a few lines of code?
Then we must write text files in .py
Time for a demo..
https://www.youtube.com/watch?v=BBwEF6WBUQs
Noteable (Jupyter notebooks)
Easy to use environment
Web-based
Combines both text and code
into one
Come with a great number of
useful packages
Noteable (Jupyter notebooks)
Easy to use environment
Web-based
Combines both text and code
into one
Come with a great number of
useful packages
Download the Python 3 Installer
Windows doesn’t typically come with a system Python. Fortunately,
installation involves little more than downloading and running the
Python installer from the Python.org website.
Step 1: Download the Python 3 Installer
If your system has a 32-bit processor, then you should choose the 32-bit installer. If you
aren’t sure if your computer is 32-bit or 64-bit, stick with the 64-bit installer mentioned
above.
Step 2 : Run the Installer
Open your Downloads folder in Windows Explorer and double-click
the file to run the installer. A dialog that looks like the following one
will appear:
Open IDLE
You can open the IDLE in two steps:
Click the start menu and locate the Python 3.9 folder
Open the folder and select IDLE (Python 3.9)
The python shell window looks like below
The fun stuff
We are now going to write our first python program
Learn what happens when you run a program with an error
Learn how to declare a variable and inspect its value
Learn how to write comments.
ARE YOU READY TO BEGIN YOUR PYTHON
CODING JOURNEY
The Interactive Window
IDLE’s interactive window contains a Python shell, which is a textual
user interface used to interact with the Python language. You can type a
bit of Python code into the interactive window and press Enter to
immediately see the results. Hence the name interactive window.
The interactive window opens automatically when you start IDLE.
You’ll see the following text, with some minor differences depending
on your setup, displayed at the top of the window:
The Interactive Window
Go ahead and type 1 + 1 at the prompt and press Enter :
The Interactive Window
Python evaluates the expression, displays the result (2), then displays another
prompt. Every time you run some code in the interactive window, a new prompt
appears directly below the result.
Executing Python in the interactive window can be described as a loop
with three steps:
1. Python reads the code entered at the prompt.
2. Python evaluates the code.
3. Python prints the result and waits for more input.
This loop is commonly referred to as a read-evaluate-print loop and is abbreviated
as REPL. Python programmers sometimes refer to the Python shell as the Python
REPL, or just “the REPL” for short.
Hello World
Type the following in the python console print (“Hello World”)
Before you run your program, you need to save it. Select File Save from the menu
and save the file as hello_world.py.
Mess Things Up
Everybody makes mistakes—especially while programming! In case you haven’t
made any mistakes yet, let’s get a head start and mess something up on purpose to
see what happens.
Mistakes in programs are called errors. You’ll experience two main types of
errors: syntax errors and runtime errors.
A syntax error occurs when you write code that isn’t allowed in the Python
language.
Let’s create a syntax error by removing the last quotation mark from the code in the
hello_world.py file that you created in the last section:
print("Hello, World)
Save the file and press F5 to run it. The code won’t run! IDLE displays an alert box
with the following message: EOL while scanning string literal.
Runtime Errors
IDLE catches syntax errors before a program starts running. In contrast, runtime
errors only occur while a program is running.
To generate a runtime error, remove both quotation marks in the hello_world.py
file:
print(Hello, World)
Did you notice how the text color changed to black when you removed the
quotation marks, IDLE no longer recognizes Hello, World as text.
What do you think will happen when you run the program? Press F5 to find out!
Whenever an error occurs, Python stops executing the program and displays
several lines of text called a traceback. The traceback shows useful information
about the error.
Create a Variable
In Python, variables are names that can be assigned a value and then used to refer to that value
throughout your code.
Variables are fundamental to programming for two reasons:
1. Variables keep values accessible: For example, you can assign the result of
some time- consuming operation to a variable so that your program doesn’t have to perform
the operation each time you need to use the result.
2. Variables give values context: The number 28 could mean lots of
different things, such as the number of students in a class, the
number of times a user has accessed a website, and so on. Giving the value 28 a name like
num_students makes the meaning of the value clear.
In this section, you’ll learn how to use variables in your code, as well as some of the conventions
Python programmers follow when choosing names for variables.
The Assignment Operator
An operator is a symbol, such as +, that performs an operation on one or more
values. For example, the + operator takes two numbers, one to the left of the
operator and one to the right, and adds them
together.
Values are assigned to variable names using a special symbol called the
assignment operator (=) . The = operator takes the value to the right of the
operator and assigns it to the name on the left.
Let’s modify the hello_world.py file from the previous section to assign some text
in a variable before printing it to the screen:
The Assignment Operator
On the first line, you create a variable named greeting and assign it the value
"Hello, World" using the = operator.
print(greeting) displays the output Hello, World because Python looks
for the name greeting, finds that it’s been assigned the value "Hello,
World", and replaces the variable name with its value before calling
the function.
If you hadn’t executed greeting = "Hello, World" before executing
print(greeting), then you would have seen a NameError
How to write a comment
The most common way to write a comment is to begin a new line in your code with the # character.
When you run your code, Python ignores lines starting with #.
Comments that start on a new line are called block comments. You can also write inline
comments, which are comments that appear on the same line as the code they reference. Just put a
# at the end of the line of code, followed by the text in your comment.
Here’s an example of a program with both kinds of comments: