Lab-02 Basics in Python Language: Objectives

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Lab-02
Basics in Python language

Objectives:
The purpose of this lab is to get you familiar with the basics in Python (Learning
Input / Output handling, typing things, optional arguments, variables, comments and built in data
types).

Apparatus:
Hardware Requirement
Personal computer.
Software Requirement
Anaconda, Jupyter Notebook/ Spyder
Theory:
A first program

Start any IDE and open up a new window. Type in the following program.

Each IDE uses different colors to make your program easier to read.
Once you run the program, the program will ask you for a temperature. Type in any number i.e.
20 and press enter. The program’s output looks something like this:

Let’s examine how the program does what it does. The first line asks the user to enter a
temperature. The input function’s job is to ask the user to type something in and to capture
what the user types. The part in quotes is the prompt that the user sees. It is called a string and it
will appear to the program’s user exactly as it appears in the code itself. The eval function is

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

something we use here, but it won’t be clear exactly why until later. So for now, just remember
that we use it when we’re getting numerical input.

We need to give a name to the value that the user enters so that the program can remember it and
use it in the second line. The name we use is temp and we use the equals sign to assign the user’s
value to temp.
The second line uses the print function to print out the conversion. The part in quotes is another
string and will appear to your program’s user exactly as it appears in quotes here. The second
argument to the print function is the calculation. Python will do the calculation and print out the
numerical result.

This program may seem too short and simple to be of much use, but there are many websites that
have little utilities that do similar conversions, and their code is not much more complicated than
the code here.

A second program

Here is a program that computes the average of two numbers that the user enters:

For this program we need to get two numbers from the user. There are ways to do that in one
line, but for now we’ll keep things simple. We get the numbers one at a time and give each
number its own name. The only other thing to note is the parentheses in the average calculation.
This is because of the order of operations. All multiplications and divisions are performed
before any additions and subtractions, so we have to use parentheses to get Python to do the
addition first.

Typing Things In
Case
Case matters to Python, print, Print, and PRINT are all different things. For now, stick with
lowercase as most Python statements are in lowercase.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Spaces
Spaces matter at the beginning of lines, but not elsewhere. For example the code below

Python uses indentation of lines for things we’ll learn about soon. On the other hand, spaces in
most other places don’t matter. For instance, the following lines have the same effect:

Basically, computers will only do what you tell them, and they often take things very literally.
Python itself totally relies on things like the placement of commas and parentheses so it knows
what’s what. It is not very good at figuring out what you mean, so you have to be precise. It will
be very frustrating at first, trying to get all of the parentheses and commas in the right places, but
after a while it will become more natural. Still, even after you’ve programmed for a long time,
you will still miss something. Fortunately, the Python interpreter is pretty good about helping
you find your mistakes.

Getting input

The input function is a simple way for your program to get information from people using your
program. The basic structure is
variable name = input(message to user)
Here is an example to get text from the user:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

To get numbers from the user to use in calculations, we need to do something extra. Here is
another example:

The eval function converts the text entered by the user into a number. One nice feature of this is
you can enter expressions, like 3*12+5, and eval will compute them for you.

Note: If you run your program and nothing seems to be happening, try pressing enter. There is a bit of a
glitch in IDLE that occasionally happens with input statements.

Printing
Here is a simple example:

The print function requires parenthesis around its arguments. In the program above, its only
argument is the string 'Hi students'. Anything inside quotes will (with a few exceptions) be printed
exactly as it appears. In the following, the first statement will output 3+4, while the second will
output 7.
To print several things at once, separate them by commas. Python will automatically insert spaces
between them. Below is an example and the output it produces.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Optional arguments
There are two optional arguments to the print function. They are not overly important at this stage
of the game, so you can safely skip over this section, but they are useful for making your output
look nice.

sep
Python will insert a space between each of the arguments of the print function. There is an optional
argument called sep, short for separator, that you can use to change that space to some- thing else.
For example, using sep=':' would separate the arguments by a colon and sep='##' would separate the
arguments by two pound signs.
One particularly useful possibility is to have nothing inside the quotes, as in sep=''. This says to put
no separation between the arguments. Here is an example where sep is useful for getting the output
to look nice:

end
The print function will automatically advance to the next line. For instance, the following will print
on two lines:

There is an optional argument called end that you can use to keep the print function from
advancing to the next line. Here is an example:

Of course, this could be accomplished better with a single print, but we will see later that there
are interesting uses for the end argument.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Variables

Variables are nothing but reserved memory locations to store values. It means that when you
create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to the variables, you
can store integers, decimals or characters in these variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator is the value stored in the variable. For example −

Looking back at our first program, we see the use of a variable called temp:

One of the major purposes of a variable is to remember a value from one part of a program so
that it can be used in another part of the program. In the case above, the variable temp stores the
value that the user enters so that we can do a calculation with it in the next line.

A third example
Here is another example with variables. Before reading on, try to figure out what the values of x
and y will be after the code is executed.

After these four lines of code are executed, x is 4, y is 5 and z is 8. One way to understand
something like this is to take it one line at a time. This is an especially useful technique for trying

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

to understand more complicated chunks of code. Here is a description of what happens in the
code above:
1. x starts with the value 3 and y starts with the value 4.
2. In line 3, a variable z is created to equal x+y, which is 7.
3. Then the value of z is changed to equal one more than it currently equals, changing it
from 7 to 8.
4. Next, x is changed to the current value of y, which is
5. Finally, y is changed to 5. Note that this does not affect x.
6. So at the end, x is 4, y is 5, and z is 8.
Variable names
There are just a couple of rules to follow when naming your variables.
 Variable names can contain letters, numbers, and the underscore.
 Variable names cannot contain spaces.
 Variable names cannot start with a number.
 Case matters—for instance, temp and Temp are different.
It helps make your program more understandable if you choose names that are descriptive, but
not so long that they clutter up your program.

Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters
after the #, up to the end of the physical line, are part of the comment and the Python interpreter
ignores them. You can also type a comment on the same line after a statement or expression −

Python does not have multiple-line commenting feature. You have to comment each line
individually as follows −

Built-in Data Types in Python


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Python has five standard data types −


 Numbers
 String
 List
 Tuple
 Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −

Python supports three different numerical types −


 int (signed integers)
 float (floating point real values)
 complex (complex numbers)
All integers in Python3 are represented as long integers. Hence, there is no separate number type
as long.

Examples
Here are some examples of numbers −
int float complex

10 0.0 3.14j

100 15.20 45.j

-786 -21.9 9.322e-36j

080 32.3+e18 .876j

-0490 -90. -.6545+0J

-0x260 -32.54e100 3e+26J

0x69 70.2-E12 4.53e-7j

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj,
where x and y are real numbers and j is the imaginary unit.

A fourth example
Here is another example with variables in which different types of numbers are assigned to
variable and the data type is assigned to variable as per type of data.

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks.
Creating a string
A string is created by enclosing text in quotes. You can use either single quotes, ', or double
quotes, ''. A triple-quote can be used for multi-line strings. Here are some examples:

Indexing
We will often want to pick out individual characters from a string. Python uses square brackets
to do this. The table below gives some examples of indexing the string S='Python'.

Statement Result Description


S[0] P First character of S
S[1] y Second character of S
S[-1] n Last character of S
S[-2] o Second last character of S

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

 The first character of S is S[0], not S[1]. Remember that in programming, counting
usually starts at 0, not 1.
 Negative indices count backwards from the end of the string.

A common error
Suppose S='Python' and we try to do S[12]. There are only six characters in the string and
Python will raise the following error message:

You will see this message again. Remember that it happens when you try to read past the end of a string.

Slices
A slice is used to pick out part of a string. It behaves like a combination of indexing and the
range function. Below we have some examples with the string s='abcdefghij'.

index: 0 1 2 3 4 5 6 7 8 9 letters:
abcdef gh i j
Code Result Description
s[2:5] cde characters at indices 2, 3, 4
s[ :5] abcde first five characters
s[5: ] fghij characters from index 5 to the end
s[-2: ] ij last two characters
s[ : ] abcdefghij entire string
s[1:7:2] bdf characters from index 1 to 6, by twos
s[ : :-1] jihgfedcba a negative step reverses the string

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

 The basic structure is


string_name[starting location : ending location+1]
Slices have the same quirk as the range function in that they does not include the ending
location. For instance, in the example above, s[2:5] gives the characters in indices 2, 3, and
4, but not the character in index 5.

 We can leave either the starting or ending locations blank. If we leave the starting location
blank, it defaults to the start of the string. So s[:5] gives the first five characters of s. If we
leave the ending location blank, it defaults to the end of the string. So s[5:] will give all the
characters from index 5 to the end. If we use negative indices, we can get the ending
characters of the string. For instance, s[-2:] gives the last two characters.

 There is an optional third argument, just like in the range statement, that can specify the
step. For example, s[1:7:2] steps through the string by twos, selecting the characters at
indices 1, 3, and 5 (but not 7, because of the aforementioned quirk). The most useful step is
-1, which steps backwards through the string, reversing the order of the characters.

Example

Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

C. One of the differences between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. For example –

Example

Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.
The main difference between lists and tuples are − Lists are enclosed in brackets " [ ] ", and their
elements and size can be changed, while tuples are enclosed in parentheses " ( ) ", and cannot be
updated. Tuples can be thought of as read-only lists. For example −

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). For example –

Exercises
512−282
1. Write a program that computes and prints the result of .It is roughly .1017.
47,48+5

2. Ask the user to enter a number. Print out the square of the number, but use the sep optional
argument to print it out in a full sentence that ends in a period. Sample output is shown below.

3. Write a program that asks the user for a weight in kilograms and converts it to pounds.
(Hint: There are 2.2 pounds in a kilogram.)
4.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Write a program that asks the user to enter three numbers (use three separate input
statements). Create variables called total and average that hold the sum and average of
the three numbers and print out the values of total and average.

IQRA University, North Campus, Karachi

You might also like