0% found this document useful (0 votes)
5 views

E22 - Lecture 3 - Notes - Python Basics_3c679fc57499154f4d8f12cb3f2bd3dd

CS1301 is an introductory course on computer programming fundamentals using Python. It covers the basics of programming, the advantages of Python for beginners, and how to install the Python interpreter. The document also explains variables, operators, and provides guidance on writing and executing Python programs.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

E22 - Lecture 3 - Notes - Python Basics_3c679fc57499154f4d8f12cb3f2bd3dd

CS1301 is an introductory course on computer programming fundamentals using Python. It covers the basics of programming, the advantages of Python for beginners, and how to install the Python interpreter. The document also explains variables, operators, and provides guidance on writing and executing Python programs.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CS1301 – Introduction to computing (E22)

Introduction to Computer Programming Fundamentals


using Python

What is Computer Programming?


Computer programming is the process of writing instructions that get executed by computers.
The instructions, also known as code, are written in a programming language which the
computer can understand and use to perform a task or solve a problem.
Basic computer programming involves the analysis of a problem and development of a logical
sequence of instructions to solve it. There can be numerous paths to a solution and the computer
programmer seeks to design and code that which is most efficient.
A set of rules that provides a way of telling a computer what operations to perform is called a
programming language. There is not just one programming language; there are many.
Programming languages pretty much do the same thing, but they are just different ways of
expressing the same instructions to a computer. Once you've grasped the concepts and
fundamentals of one programming language, the learning curve for learning another language
won't be as steep.

What are the fundamentals of a programming language?


There are some basic elements which are commonly featured. This includes variables, loops,
conditional statements, data structures and algorithms. These are the building blocks of most
programming languages.

Why should beginners learn Python?

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

Why Learn Python?


There are a large number of high level programming languages available, such as C, C++, and
Java. The good news is all high level programming languages are very similar to one another.
If you are new to programming, Python is a great place to start. One of the key features of
Python is its simplicity, making it the ideal language for beginners to learn. Most programs in
Python require considerably fewer lines of code to perform the same task compared to other
languages such as C. This leads to fewer programming errors and reduces the development
time needed. In addition, Python comes with an extensive collection of third party resources
that extend the capabilities of the language. As such, Python can be used for a large variety of
tasks, such as for desktop applications, database applications, network programming, game
programming and even mobile development. Last but not least, Python is a cross platform
language, which means that code written for one operating system, such as Windows, will work
well on Mac OS or Linux without making any changes to the Python code.

Convinced that Python is THE language to learn? Let’s get started...

Installing the Python Interpreter


• Before we can write our first Python program, we have to download the appropriate
interpreter for our computers.
• We’ll be using Python 3 in this course.
• To install the interpreter for Python 3, head over to https://www.python.org/downloads/.
The correct version should be indicated at the top of the webpage. Click on the version for
Python 3 and the software will start downloading.
• Choose the correct installer for your computer. The installer to use depends on two factors:

2
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)

1. The operating system (Windows, Mac OS, or Linux) and


2. The processor (32-bit vs 64-bit) that you are using.

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.

Using the Python Shell, IDLE and Writing our FIRST


Program
We’ll be writing our code using the IDLE program that comes bundled with our Python
interpreter.

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.

Variables and Operators

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.

What are variables?


Variables are names given to data that we need to store and manipulate in our programs. For
instance, suppose your program needs to store the age of a user. To do that, we can name this
data userAge and define the variable userAge using the following statement.

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.

The Assignment Sign


Note that the = sign in the statement userAge = 0 has a different meaning from the = sign
we learned in Math. In programming, the = sign is known as an assignment sign. It means we
are assigning the value on the right side of the = sign to the variable on the left.

The statements x = y and y = x have very different meanings in programming. An example


will clear this up.

Type the following code into your IDLE editor and save it.

Now run the program. You should get this output:

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.

Run the second program. You will now get

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

1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations


like addition, subtraction, multiplication and division.

OPERATOR DESCRIPTION SYNTAX

+ Addition: adds two operands x + y

- Subtraction: subtracts two operands x - y

* Multiplication: multiplies two operands x * y

/ Division (float): divides the first operand by the second x / y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when first operand is


% divided by the second x % y

** Power : Returns first raised to power second x ** y

Type the following code into your IDLE editor and save it.

7
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)

Now run the program. You should get this output:

2. Relational Operators: Relational operators compares the values. It either


returns True or False according to the condition.

OPERATOR DESCRIPTION SYNTAX

> 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)

== Equal to: True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to: True if left operand is greater


>= than or equal to the right x >= y

Less than or equal to: True if left operand is less than or


<= equal to the right x <= y

Type the following code into your IDLE editor and save it.

Now run the program. You should get this output:

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)

OPERATOR DESCRIPTION SYNTAX

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if operand is false not x

Type the following code into your IDLE editor and save it.

Now run the program. You should get this output:

4. Assignment operators: Assignment operators are used to assign values to the variables.

OPERATOR DESCRIPTION SYNTAX

Assign value of right side of expression to left side


= operand x = y + z

Add AND: Add right side operand with left side


+= operand and then assign to left operand a+=b a=a+b

Subtract AND: Subtract right operand from left


-= operand and then assign to left operand a-=b a=a-b

Multiply AND: Multiply right operand with left


*= operand and then assign to left operand a*=b a=a*b

Divide AND: Divide left operand with right


/= operand and then assign to left operand a/=b a=a/b
10
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)

Modulus AND: Takes modulus using left and right


%= operands and assign result to left operand a%=b a=a%b

Divide(floor) AND: Divide left operand with right


operand and then assign the value(floor) to left a//=b
//= operand a=a//b

Exponent AND: Calculate exponent(raise power)


value using operands and assign value to left a**=b
**= operand a=a**b

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.

OPERATOR DESCRIPTION SYNTAX

is True if the operands are identical x is y

is not True if the operands are not identical x is not y

Type the following code into your IDLE editor and save it.

Now run the program. You should get this output:

6. Membership operators: in and not in are the membership operators; used to test
whether a value or variable is in a sequence.

OPERATOR DESCRIPTION SYNTAX

in True if value is found in the sequence x in y

not in True if value is not found in the sequence x not in y

11
Department of Computer Science and Engineering/SEUSL
CS1301 – Introduction to computing (E22)

Type the following code into your IDLE editor and save it.

Now run the program. You should get this output:

Data Types in Python


Here, we look at some basic data types in Python, specifically the integer, float and string.
Next, we’ll explore the concept of type casting. We will discuss more advanced data types later
in the course.

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.

To declare a float in Python, we write variableName = initialvalue

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.

We can combine multiple substrings by using the concatenate sign (+).

For instance, “Peter” + “Lee” is equivalent to the string “PeterLee”.

Making Your Program Interactive


Now that we’ve covered the basics of variables, let us write a program that makes use of them.
We’ll revisit the “Hello World” program we wrote earlier in the lecture note, but this time we’ll
make it interactive. Instead of just saying hello to the world, we want the world to know our
names and ages too. In order to do that, our program needs to be able to prompt us for
information and display them on the screen.

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.

myName = input("Please enter your name: ")

myAge = input("What about your age: ")

print ("Hello World, my name is", myName, "and I am", myAge,


"years old.")

The program should prompt you for your name.

Please enter your name:

Supposed you entered James. Now press Enter and it’ll prompt you for your age.

What about your age:

Say you typed in 20. Now press Enter again. You should get the following statement:

Hello World, my name is James and I am 20 years old.

input()

In the example above, we used the input() function twice to get our user’s name and age.

myName = input("Please enter your name: ")

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?

print ("Hello World, my name is", myName, "and I am", myAge,


"years old.")

The first is the string “Hello World, my name is”

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

finally the string “years old.”.

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

Hello World, my name is myName and I am myAge years old.

instead, which is obviously not what we want.

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,

will give you

This helps to increase the readability of your message.

--------------------- END -----------------------

14
Department of Computer Science and Engineering/SEUSL

You might also like