E22 - Lecture 3 - Notes - Python Basics_3c679fc57499154f4d8f12cb3f2bd3dd
E22 - Lecture 3 - Notes - Python Basics_3c679fc57499154f4d8f12cb3f2bd3dd
• Easy to learn, read, and use: Unlike other languages, Python’s syntax is human readable
and it’s concise. As a beginner, this will allow you pick up the basics quickly and you can
level up to advanced topics quicker. With one glance at Python code, you can infer what
the code is doing. In contrast, most programming languages require more syntax (written)
code to accomplish similar tasks, and the syntax doesn’t mirror the human language.
• Easy to set up and run: With Python, all you have to do to get started is download and run
the installer, and run python <your-script>.py. No complicated directory structure to create
or compiling.
• A large, active community: Lots of third-party libraries and lots of people to help you.
• Python is an Object-Oriented Language: Every developer needs to know about Object-
Oriented Programming and it comes built into the Python language.
• In-demand language: Python is widely used in Data Science, Web Applications or Game
Development. Some of the top companies that utilize Python include Google, Facebook,
Dropbox, NASA, and IBM to name a few.
1
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
Python
Python is a widely used high-level programming language created by Guido van Rossum in
the late 1980s. The language places strong emphasis on code readability and simplicity, making
it possible for programmers to develop applications rapidly.
Like all high level programming languages, Python code resembles the English language which
computers are unable to understand. Codes that we write in Python have to be interpreted by a
special program known as the Python interpreter, which we’ll have to install before we can
code, test and execute our Python programs. We'll look at how to install the Python interpreter
in later section.
2
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
For instance, the yellow download button on the main download page (see Figure) gets you the
"x86 executable installer" choice. This is actually a fine choice: you don't need the 64-bit
version even if you have 64-bit Windows, the 32-bit Python will work just fine. If you
download and run the wrong installer, no worries. You will get an error message and the
interpreter will not install. Simply download the correct installer and you are good to go.
Once you have successfully installed the interpreter, you are ready to start coding in Python.
To do that, let’s first launch the IDLE program. You launch the IDLE program like how you
launch any other programs. For instance on Windows 10, you can search for it by typing
“IDLE” in the search box. Once it is found, click on IDLE (Python ……) to launch it. You’ll
be presented with the Python Shell shown below.
3
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
The Python Shell allows us to use Python in interactive mode. This means we can enter one
command at a time. The Shell waits for a command from the user, executes it and returns the
result of the execution. After this, the Shell waits for the next command.
Try typing the following into the Shell. The lines starting with >>> are the commands you
should type while the lines after the commands show the results.
When you type 2+3, you are issuing a command to the Shell, asking it to evaluate the value of
2+3. Hence, the Shell returns the answer 5. When you type 3>2, you are asking the Shell if 3
is greater than 2. The Shell replies True. Finally, print is a command asking the Shell to
display the line Hello World.
The Python Shell is a very convenient tool for testing Python commands, especially when we
are first getting started with the language. However, if you exit from the Python Shell and enter
it again, all the commands you type will be gone. In addition, you cannot use the Python Shell
to create an actual program. To code an actual program, you need to write your code in a text
file and save it with a .py extension. This file is known as a Python script.
To create a Python script, click on File > New File in the top menu of our Python Shell. This
will bring up the text editor that we are going to use to write our very first program, the “Hello
World” program. Writing the “Hello World” program is kind of like the rite of passage for all
new programmers. We’ll be using this program to familiarize ourselves with the IDLE
software.
Type the following code into the text editor (not the Shell).
You should notice that the line #Prints the Words “Hello World” is in red while the word
“print” is in purple and “Hello World” is in green. This is the software’s way of making our
code easier to read. The words “print” and “Hello World” serve different purposes in our
program, hence they are displayed using different colors. We’ll go into more details in later
sections.
The line #Prints the Words “Hello World” (in red) is actually not part of the program. It is a
comment written to make our code more readable for other programmers. This line is ignored
by the Python interpreter. To add comments to our program, we type a # sign in front of each
line of comment, like this:
4
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
Alternatively, we can also use three single quotes (or three double quotes) for multiline
comments, like this:
Now click File > Save As… to save your code. Make sure you save it with the .py extension.
Done? You have just successfully written your first Python program.
Finally click on Run > Run Module to execute the program (or press F5).
You should see the words Hello World printed on your Python Shell.
Now that we’re done with the introductory stuff, let’s get down to the real stuff. In this section,
you’ll learn all about variables and operators. Specifically, you’ll learn what variables are and
how to name and declare them. We’ll also learn about the common operations that we can
perform on them.
After you define the variable userAge, your program will allocate a certain area of your
computer's storage space to store this data. You can then access and modify this data by
referring to it by its name, userAge. Every time you declare a new variable, you need to
give it an initial value. In this example, we gave it the value 0. We can always change this
value in our program later.
We can also define multiple variables at one go. To do that simply write
5
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
This is equivalent to
Naming a Variable
A variable name in Python can only contain letters (a - z, A - B), numbers or underscores (_).
However, the first character cannot be a number. Hence, you can name your variables
userName, user_name or userName2 but not 2userName.
In addition, there are some reserved words that you cannot use as a variable name because they
already have preassigned meanings in Python. These reserved words include words like
print, input, if, while etc. We’ll learn about each of them in subsequent chapters.
Finally, variable names are case sensitive. username is not the same as userName.
There are two conventions when naming a variable in Python. We can either use the camel case
notation or use underscores. Camel case is the practice of writing compound words with mixed
casing (e.g. thisIsAVariableName). Alternatively, another common practice is to use
underscores (_) to separate the words.
Type the following code into your IDLE editor and save it.
6
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
Although x has an initial value of 5 (declared on the first line), the third line x = y assigns
the value of y to x (x <- y), hence changing the value of x to 10 while the value of y
remains unchanged.
Next, modify the program by changing ONLY ONE statement: Change the third line from x
= y to y = x. Mathematically, x = y and y = x mean the same thing. However, this is
not so in programming.
You can see that in this example, the x value remains as 5, but the value of y is changed to 5.
This is because the statement y = x assigns the value of x to y (y <- x). y becomes 5
while x remains unchanged as 5.
Basic Operators
Type the following code into your IDLE editor and save it.
7
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
> Greater than: True if left operand is greater than the right x > y
< Less than: True if left operand is less than the right x < y
8
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
Type the following code into your IDLE editor and save it.
3. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
9
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
and Logical AND: True if both the operands are true x and y
Type the following code into your IDLE editor and save it.
4. Assignment operators: Assignment operators are used to assign values to the variables.
5. Identity operators: is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.
Type the following code into your IDLE editor and save it.
6. Membership operators: in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
11
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
Type the following code into your IDLE editor and save it.
Integers
Integers are numbers with no decimal parts, such as -5, -4, -3, 0, 5, 7 etc. To declare an integer
in Python, simply write variableName = initial value
Example:
userAge = 20, mobileNumber = 12398724
Float
Float refers to numbers that have decimal parts, such as 1.234, -0.023, 12.01.
Example:
userHeight = 1.82, userWeight = 67.2
String
String refers to text. To declare a string, you can either use variableName = ‘initial
value’ (single quotes) or variableName = “initial value” (double quotes)
Example:
userName = ‘Peter’, userSpouseName = “Janet”, userAge = ‘30’
12
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
In the last example, because we wrote userAge = ‘30’, userAge is a string. In contrast,
if you wrote userAge = 30 (without quotes), userAge is an integer.
Two built-in functions can do that for us: input() and print().
For now, let’s type the following program in IDLE. Save it and run it.
Supposed you entered James. Now press Enter and it’ll prompt you for your age.
Say you typed in 20. Now press Enter again. You should get the following statement:
input()
In the example above, we used the input() function twice to get our user’s name and age.
The string “Please enter your name: ” is the prompt that will be displayed on the screen to
give instructions to the user. After the user enters the relevant information, this information is
13
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)
stored as a string in the variable myName. The next input statement prompts the user for his
age and stores the information as a string in the variable myAge.
print()
The print() function is used to display information to users. It accepts zero or more
expressions as parameters, separated by commas.
In the statement below, we passed 5 parameters to the print() function. Can you identify
them?
The next is the variable myName declared using the input function earlier.
Next is the string "and I am", followed by the variable myAge and
Note that we do not use quotation marks when referring to the variables
myName and myAge. If you use quotation marks, you’ll get the output
Triple Quotes
If you need to display a long message, you can use the triple-quote symbol (‘’’ or “””) to span
your message over multiple lines. For instance,
14
Department of Computer Science and Engineering/SEUSL