Lab 1 Python
Lab 1 Python
1. Submission
Include the following in your lab report.
Your full names in the upper right corner of the first page in large print.
A cohesive summary of what you learned through the exercises in this lab. Try to get at
the main idea of the exercises, and write your answers to the questions.
2. Objectives
To describe the history of Python.
To learn about computers and programming
To write and run your first python program
To explain the basic syntax of a Python program.
To write and run a simple Python program.
To explain the differences between syntax errors, runtime errors, and logic errors.
To use the operators +, -, *, /, //, %, and **
To obtain input from a program’s user by using the input function.
3. Introduction
Prepared by Dawit H. 1|Page
Python is a powerful modern computer programming language. Python was developed by Guido
van Rossum, and it is free software. Python allows you to use variables without declaring them
(i.e., it determines types implicitly), and it relies on indentation as a control structure. You are
not forced to define classes in Python (unlike Java) but you are free to do so when convenient.
Python is an easy to learn, powerful programming language. It has efficient high-level data
structures and a simple but effective approach to object-oriented programming. Python’s elegant
syntax and dynamic typing, together with its interpreted nature, make it an ideal language for
scripting and rapid application development in many areas on most platforms.
The Python interpreter and the extensive standard library are freely available in source or binary
form for all major platforms from the Python Web site, https://www.python.org/ , and may be
freely distributed. The same site also contains distributions of and pointers to many free third
party Python modules, programs and tools, and additional documentation.
First install Python 3.6 (32 or 64 bits) on your computer. Assume you have Python installed on
the Windows OS. You can start Python in a command window by typing python at the command
prompt, or by using IDLE.
IDLE (Interactive DeveLopment Environment) is an integrated development environment (IDE)
for Python. You can create, open, save, edit, and run Python programs in IDLE. Both the
command-line Python interpreter and IDLE are available after Python is installed on your
machine.
In the User Variables section, we will need to either edit an existing PATH variable or
create one. If you are creating one, make PATH the variable name and add the following
Prepared by Dawit H. 3|Page
directories to the variable values section as shown, separated by a semicolon. If you’re
editing an existing PATH, the values are presented on separate lines in the edit dialog.
Click New and add one directory per line.
C:\Users\Kelemwa\AppData\Local\Programs\Python\Python36
C:\Users\Kelemwa\AppData\Local\Programs\Python\Python36\Lib\site-packages
C:\Users\Kelemwa\AppData\Local\Programs\Python\Python36\Scripts
Now, you can open a command prompt (Start Menu | Windows System | Command Prompt) and
type: python
That will load the Python interpreter:
After Python starts, you will see the symbol >>>. This is the Python statement prompt, and it is
where you can enter a Python statement. Now, type print("Welcome to Python") and press the
Enter key. The string Welcome to Python appears on the console. String is a programming term
meaning a sequence of characters.
Entering Python statements at the statement prompt >>> is convenient, but the statements are
not saved. To save statements for later use, you can create a text file to store the statements and
use the following command to execute the statements in the file:
python filename.py
The text file can be created using a text editor such as Notepad. The text file, filename, is called a
Python source file or script file, or module. By convention, Python files are named with the
extension .py.
Running a Python program from a script file is known as running Python in script mode.
Typing a statement at the statement prompt >>> and executing it is called running Python in
interactive mode.
print statement
By default, the print function starts a new line after its arguments are printed.
For example,
print("Hello")
print("World!")
prints two lines of text:
Hello
World
If no arguments are given to the print function, it starts a new line. This is similar to pressing the
“Enter” key in a text editor.
For example,
print("Hello")
print()
print("World")
prints three lines of text including a blank line:
Hello
World
3.5. Comment
A comment that documents what the program is and how it is constructed. Comments help
programmers communicate and understand a program. They are not programming statements
and thus are ignored by the interpreter. In Python, comments are preceded by a pound sign (#)
on a line, called a line comment, or enclosed between three consecutive single quotation marks
(''') or (“””)on one or several lines, called a paragraph comment.
Exercise 1
1. What does the following statement print?
print("My lucky numbers are", 3 * 4 + 5, 5 * 6 – 1)
2. What does this program print?
print("39 + 3")
print(39 + 3)
3. What does this program print? Pay close attention to spaces.
print("Hello", "World", "!")
4. What is the compile-time error in this program?
print("Hello", "World!)
A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.
Python does not use braces({}) to indicate blocks of code for class and function definitions or
flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. The
number of spaces in the indentation is variable (most common indent is 4 space), but all
statements within the block must be indented the same amount.
For example:-
if True:
print ("True")
else:
print ("False")
Number data types store numeric values. They are immutable data types, means that changing
the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
Python converts numbers internally in an expression containing mixed types to a common type
for evaluation. But sometimes, you need to coerce a number explicitly from one type to another
to satisfy the requirements of an operator or function parameter.
Random numbers are used for games, simulations, testing, security, and privacy applications.
Python includes following functions that are commonly used.
Function Description
choice(seq) A random item from a list, tuple, or string.
Prepared by Dawit H. 9|Page
randrange ([start,] stop
A randomly selected element from range(start, stop, step)
[,step])
random() A random float r, such that 0 is less than or equal to r and r is less than 1
Sets the integer starting value used in generating random numbers. Call this
seed([x])
function before calling any other random module function. Returns None.
shuffle(lst) Randomizes the items of a list in place. Returns None.
uniform(x, y) A random float r, such that x is less than or equal to r and r is less than y
Trigonometric Functions
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
Mathematical Constants
Constants Description
pi The mathematical constant pi.
e The mathematical constant e.
Prepared by Dawit H. 10 | P a g e
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as
simple as assigning a value to a variable. For example −
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation. An escape character gets interpreted; in a single quoted as well as double
quoted strings.
Backslash Hexadecimal
Description
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
Prepared by Dawit H. 11 | P a g e
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
Hexadecimal notation, where n is in the range 0.9, a.f, or
\xnn
A.F
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Prepared by Dawit H. 12 | P a g e
Escape characters. The syntax for raw strings is
exactly the same as for normal strings with the
exception of the raw string operator, the letter "r,"
which precedes the quotation marks. The "r" can
be lowercase (r) or uppercase (R) and must be
placed immediately preceding the first quote
mark.
% Format - Performs String formatting
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on
#
whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
Prepared by Dawit H. 13 | P a g e
m is the minimum total width and n is the number of digits to display after the decimal
m.n.
point (if appl.)
var = 100
Prepared by Dawit H. 14 | P a g e
Returns encoded string version of string; on error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string))
6 Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with suffix; returns true if so and false otherwise.
expandtabs(tabsize=8)
7 Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
find(str, beg=0 end=len(string))
8 Determine if str occurs in string or in a substring of string if starting index beg and ending
index end are given returns index if found and -1 otherwise.
index(str, beg=0, end=len(string))
9
Same as find(), but raises an exception if str not found.
isalnum()
10 Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise.
isalpha()
11 Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
isdigit()
12
Returns true if string contains only digits and false otherwise.
islower()
13 Returns true if string has at least 1 cased character and all cased characters are in lowercase
and false otherwise.
isnumeric()
14
Returns true if a unicode string contains only numeric characters and false otherwise.
isspace()
15
Returns true if string contains only whitespace characters and false otherwise.
istitle()
16
Returns true if string is properly "titlecased" and false otherwise.
isupper()
17 Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
join(seq)
18 Merges (concatenates) the string representations of elements in sequence seq into a string,
with separator string.
len(string)
19
Returns the length of the string
ljust(width[, fillchar])
20 Returns a space-padded string with the original string left-justified to a total of width
columns.
Prepared by Dawit H. 15 | P a g e
lower()
21
Converts all uppercase letters in string to lowercase.
lstrip()
22
Removes all leading whitespace in string.
maketrans()
23
Returns a translation table to be used in translate function.
max(str)
24
Returns the max alphabetical character from the string str.
min(str)
25
Returns the min alphabetical character from the string str.
replace(old, new [, max])
26
Replaces all occurrences of old in string with new or at most max occurrences if max given.
rfind(str, beg=0,end=len(string))
27
Same as find(), but search backwards in string.
rindex( str, beg=0, end=len(string))
28
Same as index(), but search backwards in string.
rjust(width,[, fillchar])
29 Returns a space-padded string with the original string right-justified to a total of width
columns.
rstrip()
30
Removes all trailing whitespace of string.
split(str="", num=string.count(str))
31 Splits string according to delimiter str (space if not provided) and returns list of substrings;
split into at most num substrings if given.
splitlines( num=string.count('\n'))
32 Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed.
startswith(str, beg=0,end=len(string))
33 Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
strip([chars])
34
Performs both lstrip() and rstrip() on string
swapcase()
35
Inverts case for all letters in string.
title()
36 Returns "titlecased" version of string, that is, all words begin with uppercase and the rest
are lowercase.
translate(table, deletechars="")
37 Translates string according to translation table str(256 chars), removing those in the del
string.
Prepared by Dawit H. 16 | P a g e
upper()
38
Converts lowercase letters in string to uppercase.
zfill (width)
39 Returns original string leftpadded with zeros to a total of width characters; intended for
numbers, zfill() retains any sign given (less one zero).
isdecimal()
40
Returns true if a unicode string contains only decimal characters and false otherwise.
Prepared by Dawit H. 17 | P a g e