0% found this document useful (0 votes)
4 views19 pages

2019 Python Basic

This document provides an introduction to programming in Python, including resources for learning, installation instructions, and basic programming concepts. It covers the use of IDEs like IDLE and PyCharm, the importance of problem-solving and pseudo-code, and introduces fundamental programming constructs such as variables, calculations, and data types. Additionally, it emphasizes the necessity of practice and offers examples of simple programs to help beginners get started with coding in Python.

Uploaded by

agrawalvibhor108
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

2019 Python Basic

This document provides an introduction to programming in Python, including resources for learning, installation instructions, and basic programming concepts. It covers the use of IDEs like IDLE and PyCharm, the importance of problem-solving and pseudo-code, and introduces fundamental programming constructs such as variables, calculations, and data types. Additionally, it emphasizes the necessity of practice and offers examples of simple programs to help beginners get started with coding in Python.

Uploaded by

agrawalvibhor108
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Week 2 – Algorithmics Python Notes

Python Notes
JC van Staalduinen 2019

Useful web sites to learn Python: [Link]


[Link]/python-programming
[Link]/python
[Link]
Tutorial and experiment with Python
[Link]

Install Python development environment:


[Link] and download python 3 for your computer.

IDLE

You can now use IDLE to program your Python programs.

When you open the IDLE you get a Python Shell. Click on File > New File
Type the following in this file

print(“HelloWorld”)

Decide where you want to save. Easiest option is to create a folder for all your Python programs.
Save your first Python program in the folder and call it [Link]
Note the extension .py which tells your computer that this will be a python program.

Click on Run > Run Module (or F5 key)

Look at your Python Shell – it should show

Hello World
>>>

Congratulations, you have run your first python program.

PyCharm IDE

As an easier alternative to creating Python programs download the PyCharm IDE from

[Link].

Click on JetBrains > PyCharm to open this IDE

➢ Create New Project navigate to a folder in which you want to create your programs
➢ Create

Your IDE window should open with a Project in your project window with a folder with your folder’s
name.

Right click on the Folder and select > New > Python File > Type in HelloWorld > OK

A [Link] file is created in your work screen

JC van Staalduinen 2019 1


Week 2 – Algorithmics Python Notes

Type
print(“Hello World”)

Run > Run ‘HelloWorld’ (or Shift + F10)

Your output will appear in a window at the bottom of your screen.

This IDE will help you avoid compile type errors in your code.

Congratulations, you have run your first python program.

Onto the next programs.

1. Your first programs

Program 1: Additional prints.

Create a new file called [Link]


Create more print statements.

print("My name is Joke")


print("Good morning")
print("How are you")

From now on, for each new program create a new File with a different name. The example programs
are basic programs to show you how problems are solved and implemented in Python. There are two
thing you need to learn.

First, you need to learn to solve problems. Often this is done using pseudo-code where you do not
need to consider specific language features. Pseudo-code can be written in any language comfortable
to you and is your attempt to solve a problem at a computer level, i.e. using variables, read/print
statements, calculations, decisions, and loops. Later some more statements like linking to databases,
etc. will be added. This is the most difficult part of programming and needs years of practice, so the
more you practice, the better you will get. Without practice you will not be able to learn to program.
This is also the fun and challenging part of programming and the main reason so many real life
systems do not work properly. This can become so absorbing that you will want to spend hours and
hours programming and forget to eat and sleep. You will start with little programs and with other
courses and teaching yourself you will learn to design more and more complex systems.

Program design does not have to be in pseudo-code. More difficult designs or parts of designs are
done using diagrams such as flow charts and structured diagrams, and later you will progress to use
cases, and UML diagrams. Anything goes as long as you are able to break down your own high level
thoughts into computer level instructions. Not an easy task! So again, you will only master this if you
practice and practice and practice writing your own programs. It is a new way of thinking.

The second thing you need to learn is a computer language. Your pseudo-code or diagrams are used to
help you think in computer instructions, but now it needs to be translated into a language where an
interpreter or compiler can recognize your instructions and translate it into instructions understood by
the computer. We will start with Python and then progress to Java. As you will see, once you have
your design into pseudocode, it can be easily translated into any computer language you have
mastered. This is the easy part.

Each language has its own rules. Remember the interpreter/compiler is also a program written in
some language often C or C++ that will read your Python/Java statements as input and translate them
with output either the machine code of your program, or some intermediate code that can easily be

JC van Staalduinen 2019 2


Week 2 – Algorithmics Python Notes

translated to machine code by a virtual machine. Therefore, your statements have to be written
according to the strict language rules.

Your written program will first be compiled with the compiler throwing errors where your program did
not stick to the language rules. Fortunately many IDE’s have been written such as PyCharm for Python,
and IntelliJ, Eclipse, and Netbeans for Java which will show you language errors as you type in your
program and some logic errors it can determine such as not initializing your variables. When your
program has no more language errors, the compiler translates it into machine code or intermediate
code. Now the fun part begins, as now the logic you developed in your pseudo-code/diagrams/other
methods is tested. Often your output will not be what you intended it to be and you need to go back
and determine where your high level thinking was translated into the wrong sequence of computer
level instructions. Always remember: the computer is very dumb and can only executes the
instructions one by one in the sequence you have coded them. It does not have its own logic and will
do exactly as you instruct it to do. These instructions might not be what you intended to tell the
computer to do.

Once you have mastered some coding in Python register yourself on codewars
[Link] Choose Python and start coding. If you are new to coding start by clicking
on kata in the left bar and choose 8 kyu. Choose from the hundreds of possible programs to write.
Those with some coding experience can start at a higher kyu. You get a description of a program and a
window to write your own solution. You can test your attempt to see whether your logic is right,
submit your attempt and have a look at other solutions to broaden your coding expertise. You can
unlock solutions, discuss your solutions, and you can compete with fellow students on the number of
kyu questions you have completed. Codewars gives you a fun way to practice. Without practicing to
solve problems you will not learn to code.

There are many tutorials and youtube videos on learning to code in Python on the internet. Explore
and have fun.

Program 2: Calculations

Python can be used to calculate formulas. Note a * is used for multiplication and a / for division.
Normal scientific order of calculations are used. BODMAS - Brackets, order (powers and square roots),
multiplication and division from left to right, addition and subtraction from left to right.

Calculations can be executed in the Python shell. When you put several calculations in a file, though,
they need a print statement.

print(2+5*3) 17
print((2+5) *3) 21
print(20/4) 5.0
print(20/3) 6.666666666666667
print(20%3) 2 #remainder
print(10//3) 3 #integer division

Program 3: Using variables

Variables are temporary storage spaces and can hold only one value at a time. If assigned a new value
it overwrites the previous value.
Language rule: The = sign means the expression to the right is calculated and the answer assigned to
the variable on the left.
Language rule: a line may only contain one statement
Language rule: variables must begin with a letter or _ (to distinguish from numbers),

JC van Staalduinen 2019 3


Week 2 – Algorithmics Python Notes

Other characters can be letters or numbers or _


Case sensitive (username, userName and Username are three different variables)
Can be any reasonable length
Should not be Python reserved words

value1 = 2+5*3
print(value1) 17
value2 = (value1+5)*3
print(value2) 66
value2 = value2 + 1
print(value2) 67

Python has several types of numbers that can be temporarily stored in variables. When the type of
number is not specified, Python determines the type for you. This means Python is loosely typed,
which has its advantages and disadvantages. It allows for great flexibility and ease of use, but requires
the programmer to be aware of possible unintended interpretations by the Python compiler.

• int – positive and negative integers, for example, 3, -500, +36, 0b110 (binary for 6), 0o71
(octal for 57) 0xF2 (hexadecimal for 242)
• float – positive and negative decimal numbers. They can be specified as , for example,
12.3487, or in scientific notation 1.23487e1. They are only relatively accurate to 15 digits. For
most calculations the little inaccuracy of float is acceptable.
Problem 1: Some decimal values such as 1.1 cannot be stored accurately in binary.
Problem 2: Internal storage has a finite length, so only a finite number of decimal digits can
be represented. Very small numbers should not be added to very large numbers.

val = 1.1
print(val) 1.1
val = val+1.1
print(val) 2.2
val = val+1.1
print(val) 3.3000000000000003
val = val+1.1
print(val) 4.4
val = val+1.1
print(val) 5.5
val = val+1.1
print(val) 6.6
val = val+1.1
print(val) 7.699999999999999

val3 = 0.0000000000000001234
val4 = 0.0000000000000004321
print(val3 + val4) 5.555000000000001e-16
print(val3 + 2.0) 2.0
val5 = 1234000000000000000.0
val6 = 4321000000000000000.0
print(val5 + val6) 5.555e+18
print(val5 + 2.0) 1.234e+18

• complex numbers – a + bj
• decimal numbers – can be used when working with money or numbers where more accuracy
is required. They are not totally accurate in Python either, so better to convert the numbers
to integers and change the coding to accommodate this.

Computers store these different types of numbers differently and the calculations are done in
different ways. It is important to be aware of the different types and the conversions that are done.

JC van Staalduinen 2019 4


Week 2 – Algorithmics Python Notes

Integers are internally converted to float numbers if the calculations warrant a float answer, or
contains float numbers. On the other hand, float numbers need to be explicitly converted to integers
by using the int() function.

intNum = int(-12.67) #note, truncated, not rounded


print(intNum) -12

num = 20/3 # num taken to be float


print(num) 6.666666666666667
intNum = int(20/3)
print(intNum) 6
print(int("1")) 1
print(float("12")) 12.0

print(divmod(10,3)) (3, 1) # integer division and remainder


print(divmod(10.5,3)) (3.0, 1.5)

print (bin(20)) 0b10100


print(bool(20)) True
print(bool (0)) False
print(bool(-2)) True
print(chr(65)) A #internal code for A is 65
print(chr(65+1)) B #internal code for B is 66
print(ord(‘A’) 65 # gives char’s internal code
print(hex(35)) 0x23
print(oct(-35)) -0o43

Python has many predefined maths functions for numbers. You need to import the math module for
those starting with math. …

x = 12.67
y = -12.67
print(abs(y)) 12.67
print(round(x,1)) # round x to 1 digit 12.7
print(round(y,1)) -12.7
print(pow(x,3)) # x**3 2033.901163
val1 = 10
val2 = 5.5
val3 = -1.7
val4 = 150
print(max(val1, val2, val3, val4)) 150
print(min(val1, val2, val3, val4)) -1.7

#need to import the Math module


import math

# smallest integer not less than x


print([Link](x), [Link](y)) 13 -12 # integer just larger than x
# largest integer not greater than x
print([Link](x), [Link](y)) 12 -13 # integer just smaller than x

print([Link](12.67)) 12
print([Link](-12.67)) -12

print([Link](x)) # e**x 318061.4875033354


print([Link](x)) # natural logarithm of x 2.5392369943330477
print(math.log10(x)) # log base 10 of x 1.1027766148834413
print(math.log2(x)) # log base 2 of x 3.663344619366085

print([Link](x)) 3.559494346111537

#trig functions
x = 2.5 # radians
y = 90 #degrees

print([Link](x)) #converts to degrees 143.2394487827058


print([Link](y)) #converts to radians 1.5707963267948966
# trig functions angles in radians
print([Link](x)) 0.5984721441039564
print([Link](1)) 0.7853981633974483

JC van Staalduinen 2019 5


Week 2 – Algorithmics Python Notes

Random numbers – often used in developing games. These are pseudo random numbers – they are
not fully random like drawing a number form a hat, but they are random enough for all practical
purposes. When the random number is seeded the same numbers are generated each time the
program is run. This allows for debugging if you have an error in your logic.
(Python has functions for random numbers from other distributions than the uniform distribution. See
[Link] for statistics and random numbers if you need to use
them)
There is some confusion on the Internet about whether the upper and lower bounds are included. See
an example under programs lower down where the numbers generated by [Link](0, 5) was
tested to see whether 0 and 5 was included.
import random

print([Link](0, 5)) # number between 0 to 5, including 0 and 5


print([Link](0,5.0)) # number between 0.0 and 5.0, 0.0 and 5.0 included
print([Link]()) # number between 0.0 and 1.0. 0 included 1.0 not included
print(int([Link]()*100)) # number between 0 and 100, 0 included, 100 not.

months = ["Jan", "Feb", "Mar", "Apr", "May"]

print([Link](months))
print([Link](months,3))

[Link](months)

print(months)
print ([Link](0, 51, 5)) # range 0 to 51 steps of 5

[Link](10)
print([Link](1,10))
print([Link](1,10))
[Link](10)
print([Link](1,10))
print([Link](1,10))
Run 1: Run 2:
5 2
3.304072752912266 0.343787660480655
0.6369848536801846 0.3849693436050845
71 94
Mar May
['Mar', 'Feb', 'Jan'] ['Apr', 'Mar', 'Feb']
['May', 'Apr', 'Feb', 'Jan', 'Mar'] ['Jan', 'Mar', 'Feb', 'May', 'Apr']
45 20
10 10
1 1
10 10
1 1

Program 4: Swap the values of two variables x and y

x=2 2 3
y=3 3 3
print(x, y)
x=y
y=x
print(x, y)

Wrong logic. Program compiles so language is right, but there is a mistake in the logic. Once x has
received the value 3 from y, the previous value of 2 in x is overwritten by 3. So when x gives it’s value

JC van Staalduinen 2019 6


Week 2 – Algorithmics Python Notes

to y, y receives the current value from x which is 3. We temporarily need to remember the old value of
x.

x=2 2 3
y=3 3 2
print(x, y)
temp=x
x=y
y=temp
print(x, y)

Python does allow for multiple assignments, though, although this is peculiar to Python and not
available in most other programming languages.

x,y=2,3 2 3
a,b = x,y
print(a,b)

x,y = 2,3
print(x,y) 2 3
y,x = x,y
print(x,y) 3 2

x,y,z = 2,3,4
x,y,z = z,y,x
print(x,y,z) 4,3,2

Program 5 Using Strings

Comment lines – Multiple line comments are written between “”” and “””
Single line comments are prefixed by a #
These lines are ignored by the compiler and serve to explain the code to the
programmer.

Strings are distinguished from variables because they are enclosed in “…” or ‘…’. The compiler is not
interested in what you write between the quotes as long as it is not a “ when you use “ ” or a ‘ when
you use ‘ ’. In the rare cases where you might need ‘ ’ and “ ”, enclose the string in ‘ ’ ’ or use the
escape (\) character. Strings can be very long, but it makes the code unreadable. Rather split into
shorter strings and concatenate.

welcomeLine1 = "Hello World"


welcomeLine2 = 'We love you'
welcomeLine3 = "It's a lovely day"
welcomeLine4 = 'Your name is "..."'
welcomeLine5 = '''It's confusing, all these "" and ''s'''
welcomeLine6 = 'It\'s a lovely day, indeed'
print(welcomeLine1, welcomeLine2, welcomeLine3, welcomeLine4)
print(welcomeLine5)
print(welcomeLine6)
Hello World We love you It's a lovely day Your name is "..."
It's confusing, all these "" and ''s
It's a lovely day, indeed

Program 6: More Strings

%s or formatting

numStudents = 300
classNumber = 2
stringClass = "class"
outputLineStudents = "There are %s students"

JC van Staalduinen 2019 7


Week 2 – Algorithmics Python Notes

print(outputLineStudents % numStudents)
outputLine = "There are %s students in %s %s"
print(outputLine % (numStudents, stringClass, classNumber))
outputLine = "There are {} students in {} {}" #other print option
print([Link](numStudents, stringClass, classNumber))
There are 300 students
There are 300 students in class 2
There are 300 students in class 2

Multiply strings

stars = 10 * "*"
spaces = " " * 8
print(stars) **********
print("*%s*" % spaces) * *
print(stars) **********
question = 10 * "?*? "
print(question) ?*? ?*? ?*? ?*? ?*? ?*? ?*? ?*? ?*? ?*?

String formatting

member = "Mary"
age = 12
print("%s is %d years old" % (member, age)) #print integers
print("{} is {} years old".format(member, age))
print("{} is {:10d} years old".format(member, age))
print("{1} is {0:10d} years old".format(age, member))
Mary is 12 years old
Mary is 12 years old
Mary is 12 years old
Mary is 12 years old

prtFormat = "Binary format for {0} is {0:b} \nExponent format: {1:e} \


\nRounding off {2:.3f}".format(12, 12.5678957, 12.56788)
print(prtFormat)
print("Exponent {:.2e}".format(123.4567))

print("{0:d} - {0:x} - {0:o} - {0:b} ".format(21))

print(0b1010)
print(0xFA)
print(0O72)
Binary format for 12 is 1100
Exponent format: 1.256790e+01
Rounding off 12.568
Exponent 1.23e+02

21 - 15 - 25 – 10101

10
250
58

value = 123.4567
print("The value is:%3.2f" %value )
print("The value is:{:3.2f}".format( value ))
print("The value is:%10.2f" %value )
print("The value is:{:10.2f}".format(value))
print("The value is:%1.2f" %value )
print("The value is:%3.1f" %value ) #rounded off
The value is:123.46
The value is:123.46
The value is: 123.46
The value is: 123.46
The value is:123.46
The value is:123.5

valpos = 123.4567
valneg = -123.4567
age = 12

JC van Staalduinen 2019 8


Week 2 – Algorithmics Python Notes

print("The value is:{:+3.2f}".format( valpos ))


print("The value is:{:+3.2f}".format( valneg ))
print("The value is:{:3.2f}".format( valneg ))
print("The value is {:10.2f}".format(valpos))
print("The value is {:10.2%}".format(valpos))
print("The value is {:0>10.2f}".format(valpos)) #leftpad with 0
print("The value is {:0<10.2f}".format(valpos)) #rightpad with 0
print("Age is: {:10d} years".format(age))#right justified padded with spaces
print("Age is: {:<10d}years".format(age))#left justified padded with spaces
print("Age is: {:^10d}years".format(age))#center justified padded with spaces
pi = 3.1415926
precision = 3
print( "The value of Pi is {:.{}f}".format( pi, precision ) )
The value is:+123.46
The value is:-123.46
The value is:-123.46
The value is 123.46
The value is 12345.67%
The value is 0000123.46
The value is 123.460000
Age is: 12 years
Age is: 12 years
Age is: 12 years
The value of Pi is 3.142

prtOrder = "first {} second {} last {}".format(1, 2, 3)


print(prtOrder)
prtOrder = "first {0} second {2} last {1}".format(1, 2, 3)
print(prtOrder)
prtOrder = "first {o} second {z} last {t}".format(z=1, o=2, t=3)
print(prtOrder)
first 1 second 2 last 3
first 1 second 3 last 2
first 2 second 1 last 3

print("Hello\nWorld") # prints on 2 lines


print("Hello\tBeautiful\tWorld") # tab
print("Hello\\Beautiful\'World\"") # inserts a \ 'and "
print(r"Hello\nbeaut\iful'World") #raw string nothing is interpreted. Handy to use
when specifying file paths i.e. C:\\filename
Hello
World
Hello Beautiful World
Hello\Beautiful'World"
Hello\nbeaut\iful'World

prtAlign = "*{:<10}*{:^10}*{:>10}".format(1, 2, 3) # align substrings left,


middle, back
print(prtAlign)
*1 * 2 * 3

More string manipulation

alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet1 = "abcdeabcdeabcdeabcde"
alphabet3 = "ABCabc"
alphanum = "123abc"

#start counting from 0


print("The sixth letter is", alphabet[5]) The sixth letter is f
letter = alphabet[5]
print(letter) f
print(alphabet[0]) # starts from position 0 a
print(alphabet[-1]) #last character z

print(alphabet[0:3]) abc
print(alphabet[3:6])# pos 3 to one before 6 def
print(alphabet[:3]) abc
print(alphabet[-3:]) xyz
print(alphabet[:-3]) abcdefghijklmnopqrstuvw
print(alphabet[7:-2])#7 to 2 before the end hijklmnopqrstuvwx

JC van Staalduinen 2019 9


Week 2 – Algorithmics Python Notes

lengthWord = len (alphabet)#length of string


print(lengthWord) 26

print([Link]()) True
print([Link]()) False
print([Link]()) True

spaces = " "


oneSpace = " "
print([Link]()) True
print([Link]()) True

print(“123abc”.isalpha()) False # checks alphabetic characters


print(“123abc”.isalnum()) True # checks alphabetic and numeric

print(“1230”.isdigit()) True # checks numeric


print(“12.5”.isdigit()) False # contains a decimal point

print("1230".isdecimal()) True
print("-12".isdecimal()) False # there is a -
print("12.5".isdecimal()) False # there is a .
print("1230".isnumeric()) True
print("-12".isnumeric()) False
print("12.5".isnumeric()) False

print("a" in alphabet) True


print("fgh" in alphabet) True
print("fgi" not in alphabet) True

print([Link]("xyz")) True
print([Link]("cde",3,9)) False
print([Link]("cde",3,10)) True
print([Link](('abc', 'yes','wxyz'))) True #one of the options
print([Link](('abc','yes','xyz'))) True #one of the options

print([Link]()) Abcdefghijklmnopqrstuvwxyz
print(alphabet) abcdefghijklmnopqrstuvwxyz
print([Link]()) abcabc #all lower case for comparison
print([Link]()) abcABC
print([Link]()) abcabc
print([Link]()) ABCABC

print("my title is hello world".title()) My Title Is Hello World


print("My Title is Hello World".istitle()) False
print("My Title".istitle()) True

print([Link]("g")) # no g’s 0
print([Link]("b")) 4
print([Link]("b",2))#start from 2 3
print([Link]("b",2,6)#stop before 6 0
print([Link]("b",2,7)) 1
print([Link]("abc")) 4

print([Link]("i")) 8 # found in position 8 start at 0


print([Link]("a",6,10))#not found -1 # incidates not found
print([Link]("a",6,11)) 10
print([Link]("fgh")) 5 # start position of “fgh”
print([Link]("fgh",0,6)) -1 #not found
print([Link]("fgh",0,8)) 5
print([Link]("ab")) 15 #searches from the back

print([Link]("c")) 2
print([Link]("a", 5)) 5
print([Link]("a", 6)) 10
#print([Link]("a", 6, 10)) #error as “a" is not found
print([Link]("a", 6, 11)) 10

print([Link]("c")# last “c” 17


print([Link]("a",6,16)) 15

JC van Staalduinen 2019 10


Week 2 – Algorithmics Python Notes

#alphabet1[2]=" " error: item assignment not allowed

# a new string is created alphabet1 remains


unchanged

print([Link]("a","*"))
print(alphabet1) *bcde*bcde*bcde*bcde
alphabet5 = [Link]("de","^&*") Abcdeabcdeabcdeabcde # has not changed
print(alphabet5)
print([Link]("ab","*",2)) abc^&*abc^&*abc^&*abc^&*
*cde*cdeabcdeabcde # 2 times

newString = alphanum + "de" + "f"


print(newString) 123abcdef
print(alphabet3+"123") ABCabc123

#join has another function than concatenate


print(":".join(alphabet3)) A:B:C:a:b:c
print(" ".join(alphabet3)) A B C a b c
print([Link]("123")) 1ABCabc2ABCabc3
print("1234".join(["00", "ABC", "%%%", 001234ABC1234%%%123499
"99"]))

a1,a2,a3 = "abc" #splits a string into individual characters


print(a1,a2,a3)

a1,a2,a3 = "abcdef" # error, string too long


print(a1,a2,a3)

sentence1 = "this is beautiful"


sentence2 = "This is a beautiful day, today"

word1, word2, word3 = [Link]("is ") # splits string on "is "


print(word1, "*", word2, "*", word3)

word1, word2, word3 = [Link]("not ")


print(word1, "*", word2, "*", word3)

listWords="This is a lovely day, Mary".split() #default split on a space


print(listWords)

listWords="This is a lovely day, Mary".split(",") #split on ,


print(listWords)

w1, w2, w3, w4, w5, w6= "This is a lovely day, Mary".split() # can only use if you
# know exactly how many substrings you will have, too few
# or too many variables on the left will throw an error
print (w1, w2, w3, w4, w5, w6)
a b c

th * is * is beautiful # unexpected result if you wanted to split the words


# you will have to partition on " is " instead
this is beautiful * * # "not " does not appear in the string, so no partitioning,
# whole string and two empty strings are returned

['This', 'is', 'a', 'lovely', 'day,', 'Mary']

['This is a lovely day', ' Mary']


This is a lovely day, Mary

print([Link](36,"*")) *****abcdefghijklmnopqrstuvwxyz*****
print([Link](36,"*")) abcdefghijklmnopqrstuvwxyz**********
print([Link](35,"*")) *********abcdefghijklmnopqrstuvwxyz
#print([Link](35,"@#")) error:fill #fill must be only 1 character

print("*"+" Hello World ".strip()+"*") *Hello World*


print("*"+" Hello World ".lstrip()+"*") *Hello World *
print("*"+" Hello World ".rstrip()+"*") * Hello World*
print("Hello \nWorld\n".strip() + "*") Hello
World*

JC van Staalduinen 2019 11


Week 2 – Algorithmics Python Notes

Program 7 Lists

When you have the marks of 20 students in your class and their marks need to be added and the
average calculated, it becomes impractical to use mark1, mark2, mark3, … mark20. What if next year
you have 25 students, then the program will not work.

Python uses lists to solve this problem. Each item has an index by which it can be referred. Very
important – the index starts at 0 not 1. When you reference an element beyond the length of the list
you get a logic error picked up during execution.

oceans = ["Pacific", "Atlantic", "Indian", "Southern", "Arctic"]


sizeSqKm = [155557000, 76762000, 68556000, 0, 14056000]
deepestDepthMeter = [10911, 8376, 7258, 7236, 5450]
surfaceWorldPercent = [30, 21, 0, 0, 0]
earthCoverPercent = 71
print(oceans[0])
print(sizeSqKm[1])
print(deepestDepthMeter[2])
print(oceans[1:4])#print partial lists. Note oceans[4] is not printed
print(numbers * 3) # triplicates the list

"""" The following statement contains an error


be careful that your index is within list bounds """

print (surfaceWorldPercent[7]) #error


Pacific
76762000
7258
['Atlantic', 'Indian', 'Antarctic']
[1, 1, 1, 2, 3, 4, 5, 1, 1, 1, 2, 3, 4, 5, 1, 1, 1, 2, 3, 4, 5]

Traceback (most recent call last):


File "C:/UTPython/Introduction Programs/[Link]", line 13, in <module>
print (surfaceWorldPercent[7]) #error
IndexError: list index out of range

Change the value of a list item and print the list


#change the name of Southern to Antarctic
oceans[3] = "Antarctic"
print(oceans)

#calculate the world percentage of the Indian,


#Antarctic, and Arctic oceans
onePercentSize = sizeSqKm[0]/surfaceWorldPercent[0]
surfaceWorldPercent[2] = sizeSqKm[2]/onePercentSize
surfaceWorldPercent[4] = sizeSqKm[4]/onePercentSize
surfaceWorldPercent[3] = earthCoverPercent-surfaceWorldPercent[0] \
- surfaceWorldPercent[1] - surfaceWorldPercent[2] \
- surfaceWorldPercent[4]
#Calculate the size of the Southern/Antartic Ocean
sizeSqKm[3] = onePercentSize * surfaceWorldPercent[3]
#Print the results
print(oceans[0], sizeSqKm[0], deepestDepthMeter[0], surfaceWorldPercent[0])
print(oceans[1], sizeSqKm[1], deepestDepthMeter[1], surfaceWorldPercent[1])
print(oceans[2], sizeSqKm[2], deepestDepthMeter[2], surfaceWorldPercent[2])
print(oceans[3], sizeSqKm[3], deepestDepthMeter[3], surfaceWorldPercent[3])
print(oceans[4], sizeSqKm[4], deepestDepthMeter[4], surfaceWorldPercent[4])
['Pacific', 'Atlantic', 'Indian', 'Antarctic', 'Arctic']
Pacific 155557000 10911 30
Atlantic 76762000 8376 21
Indian 68556000 7258 13.221391515650213
Antarctic 21092666.66666666 7236 4.067833655830338
Arctic 14056000 5450 2.7107748285194497

Delete an item from a list and add an item to a list

JC van Staalduinen 2019 12


Week 2 – Algorithmics Python Notes

# some feel Antarctic Ocean is not an ocean - remove it from list


del oceans [3]
del sizeSqKm [3]
del deepestDepthMeter [3]
del surfaceWorldPercent [3]
print(oceans)

#note the previous oceans[4] now becomes oceans[3] etc.


print(oceans[3])

#add the total oceans to your list. Will be added to the end.
[Link]("Total")
[Link](sizeSqKm[0]+sizeSqKm[1]+sizeSqKm[2]+ sizeSqKm[3])
[Link](max(deepestDepthMeter))
[Link](71)

print(oceans)
print(sizeSqKm)
print(deepestDepthMeter)
print(surfaceWorldPercent)
['Pacific', 'Atlantic', 'Indian', 'Arctic']
Arctic
['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total']
[155557000, 76762000, 68556000, 14056000, 314931000]
[10911, 8376, 7258, 5450, 10911]
[30, 21, 13.221391515650213, 2.7107748285194497, 71]

Adding a list to another list and deleting the added list


#note the difference between .append and .extend when you use lists

# add an item to a list using append.


[Link]("new Oceans")
print(oceans)
[Link](sizeSqKm) # add a list. Added as one list item.
print (oceans)
del oceans [6]
print (oceans)

a = [1,2,3] # appended with a primitive value


[Link](4)
print (a)

#add an item to a list using extend


[Link] (sizeSqKm) #add another list’s items. Individual items are added
print (oceans)
del oceans[6]
print (oceans)

#reset oceans. Note that the items move to the left, so we need to delete item 6
every time
del oceans [6]
del oceans [6]
del oceans [6]
del oceans [6]
print (oceans)

a = [1,2,3] #error, cannot extend with a primitive value


[Link](4)
print (a)

a = ["1","2","3"] # can extend with a string which is not a primitive value


[Link]("4")
print (a)

#add an item to a list in between other items


#index of items changes
[Link](2,"****")
print (oceans, oceans[4])

#reset oceans
del oceans[2]
['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans']

JC van Staalduinen 2019 13


Week 2 – Algorithmics Python Notes

['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans', [155557000,


76762000, 68556000, 14056000, 314931000]]

['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans']

[1,2,3,4]

['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans', 155557000,


76762000, 68556000, 14056000, 314931000]
['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans', 76762000,
68556000, 14056000, 314931000]

['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans']

['1', '2', '3', '4']

['Pacific', 'Atlantic', '****', 'Indian', 'Arctic', 'Total', 'new Oceans'] Arctic

Combining lists
oceans = ["Pacific", "Atlantic", "Indian", "Antarctic", "Arctic"]
sizeSqKm = [155557000, 76762000, 68556000, 0, 14056000]
deepestDepthMeter = [10911, 8376, 7258, 7236, 5450]
surfaceWorldPercent = [30, 21, 0, 0, 0]
earthCoverPercent = 71

#Concatenate lists
printList = oceans + deepestDepthMeter
print(printList)

#Lists within Lists


ListsInList = [oceans, deepestDepthMeter]
print(ListsInList)

#combine lists
comb = zip(oceans,sizeSqKm)
print(list(comb))
['Pacific', 'Atlantic', 'Indian', 'Antarctic', 'Arctic', 10911, 8376, 7258, 7236,
5450]

[['Pacific', 'Atlantic', 'Indian', 'Antarctic', 'Arctic'], [10911, 8376, 7258, 7236,


5450]]

[('Pacific', 155557000), ('Atlantic', 76762000), ('Indian', 68556000), ('Antarctic',


0), ('Arctic', 14056000)]

Separate lists
a1, a2, a3 = [1, 2, 3]
print(a1, a2, a3) 1 2 3

separate = list("abc")
print(separate) ['a', 'b', 'c']

s1, s2, s3 = list("abc")


print(s1, s2, s3) a b c

print(list((1,2,3))) #tuples (discussed later) into list [1, 2, 3]

first, *rest = "abcd"


print(first, rest) a ['b', 'c', 'd']

first, *other, last = "abcd"


print (first, other, last) a ['b', 'c'] d

first, *rest = [1,2,3,4]


print(first, rest) 1 [2, 3, 4]

first, *other, last = [1,2,3,4]


print(first, other, last) 1 [2, 3] 4

first, [a,b,c] = [1, [2,3,4]]


print(first, a, b, c) 1 2 3 4

JC van Staalduinen 2019 14


Week 2 – Algorithmics Python Notes

Copy lists
#Be careful when assigning lists to other lists. Rather use copy.

# Using = to get to variables pointing to the same list


seas1 = oceans
print("oceans", oceans, "seas1", seas1)
seas1[0] = "****" # changes both oceans and seas1
print("oceans", oceans, "seas1", seas1)
oceans[1] = "1111" # changes both oceans and seas1
print("oceans", oceans, "seas1", seas1)

#Using copy to get a true copy of a list


oceans[0] = "Pacific"
oceans[1] = "Atlantic"

seas2 = [Link]()
print("oceans", oceans, "seas2", seas2)
oceans[0] = "****" # only changes oceans
seas2[1] = "1111" # only changes seas2
print("oceans", oceans, "seas2", seas2)
oceans ['****', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans'] seas1
['****', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans']
oceans ['****', '1111', 'Indian', 'Arctic', 'Total', 'new Oceans'] seas1 ['****',
'1111', 'Indian', 'Arctic', 'Total', 'new Oceans']

oceans ['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans'] seas2


['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans']
oceans ['****', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans'] seas2
['Pacific', '1111', 'Indian', 'Arctic', 'Total', 'new Oceans']

List functions
numbers = [1,1,2,3,5,1,4,2,5,1]

print([Link](1)) #count the number of 1's in the list

[Link]() #remove all items from the list


print (numbers)

numbers = [1,1,2,3,5,1,4,2,5,1]
num1 = [Link](1) #index of first 1
num2 = [Link](2) #index of first 2
num3 = [Link](1,2) #index of first 1 searching from position 2
#remember first position is position 0
num4 = [Link](1,1) #index of first 1 searching from position 1
#num5 = [Link](1,2,4) #index of first 1 searching from position 2
# to one before position 4 gives an error
# as 1 is not in the list
#num6 = [Link](1,2,5) #index of first 1 searching from position 2
# to one before position 5 gives an error
# as 1 is not in the list
num7 = [Link](1,2,6) # index of first 1 searching from position 2
# to one before position 6 (i.e. up to and including position 5)
print (num1, num2, num3, num4, num7)
4
[ ]
0 2 5 1 5

print(numbers)
[Link]() # removes last number from list
print(numbers)
[Link](7) # removes number from position 7
print(numbers)
[Link](5) # removes first 5 from the list
print(numbers)
[Link]() #reverses the list
print(numbers)
[Link]() #sorts the list
print(numbers)
[1, 1, 2, 3, 5, 1, 4, 2, 5, 1]
[1, 1, 2, 3, 5, 1, 4, 2, 5]
[1, 1, 2, 3, 5, 1, 4, 5]
[1, 1, 2, 3, 1, 4, 5]

JC van Staalduinen 2019 15


Week 2 – Algorithmics Python Notes

[5, 4, 1, 3, 2, 1, 1]
[1, 1, 1, 2, 3, 4, 5]

Two level lists


twodimList = [[1,2,3], [4,5,6], [7,8,9]] 6 # list 1 element 2 counting from 0
print(twodimList[1][2])

Program 8 Tuples
Looks like a list but cannot be changed after creation

months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
numDays = (31,28,31,30,31,30,31,31,30,31,30,31)

print(months[4],numDays[4])

print(sum(numDays))

print ([Link](31))
print([Link](28))

summerMonths = months[5:8]
print(summerMonths)
secondHalf = months[6:]
print(secondHalf)
May 31
365
7
1
('Jun', 'Jul', 'Aug')
('Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')

separate = tuple("abc")
print(separate) ('a', 'b', 'c')

a1,a2,a3 = ("a", "b", "c")


print(a1,a2,a3) a b c

s1, s2, s3 = tuple("abc")


print(s1, s2, s3) a b c

alist = tuple([1,2,3]) #change a list to a tuple


print(alist) (1, 2, 3)

Program 9 Dictionaries
Looks like lists, but each item has a key and a value
The items are referenced by the keys
daysOfMonths = {"Jan" : 31,"Feb" : 28,"Mar" : 31,"Apr" : 30,"May" : 31,"Jun" : 30,\
"Jul" : 31,"Aug" : 31,"Sep" : 30,"Oct" : 31,"Nov" : 30,"Dec" : 31}

print(daysOfMonths["Jan"])

print(len(daysOfMonths))

print([Link]())
print([Link]())

daysOfMonth1 = [Link]()
print(daysOfMonth3)

daysOfMonths2 = [Link]()

print([Link]("Mar", "Nov"))

print([Link]("Feb"))

[Link]("Jun") #remove Jun


print(daysOfMonths)
del daysOfMonths["Aug"] #another method to remove. Remove Aug

JC van Staalduinen 2019 16


Week 2 – Algorithmics Python Notes

print(daysOfMonths)
[Link]() #remove last item
print(daysOfMonths)

daysOfMonths["Dec"]=31 #add an item to the end


print(daysOfMonths)

print ("May" in daysOfMonths)

daysOfMonths["Feb"] = 29
print(daysOfMonths)

[Link]()
print(daysOfMonths)
31
12

dict_keys(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'])
dict_values([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
dict_items([('Jan', 31), ('Feb', 28), ('Mar', 31), ('Apr', 30), ('May', 31), ('Jun',
30), ('Jul', 31), ('Aug', 31), ('Sep', 30), ('Oct', 31), ('Nov', 30), ('Dec', 31)])
{'M': 'Nov', 'a': 'Nov', 'r': 'Nov'}

{'M': 'Nov', 'a': 'Nov', 'r': 'Nov'}

28

{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jul': 31, 'Aug': 31, 'Sep':
30, 'Oct': 31, 'Nov': 30, 'Dec': 31}

{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jul': 31, 'Sep': 30, 'Oct':
31, 'Nov': 30, 'Dec': 31}

{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jul': 31, 'Sep': 30, 'Oct':
31, 'Nov': 30}

{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jul': 31, 'Sep': 30, 'Oct':
31, 'Nov': 30, 'Dec': 31}

True

{'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jul': 31, 'Sep': 30, 'Oct':
31, 'Nov': 30, 'Dec': 31}

{}

Date and time Today


import datetime

#current date and time


now = [Link]()

print(now) 2019-07-22 14:20:18.991981


print([Link]) 2019
print([Link]) 7
print([Link]) 22
print([Link]) 14
print([Link]) 20
print([Link]) 18
print([Link]) 991981

timestr1 = [Link]("%H:%M:%S")
print("time:", timestr1) time: 14:20:18

timestr2 = [Link]("%d/%m/%Y, %H:%M:%S")


print("date and time", timestr2) date and time 22/07/2019, 14:20:18

today = [Link]()
print(today) 2019-07-22

JC van Staalduinen 2019 17


Week 2 – Algorithmics Python Notes

General times, formats, and calculations


dateOther = [Link](2019, 1, 28)
print(dateOther)

time = [Link](hour = 22, minute = 30, second = 10)


print(time)

#time = [Link](hour = 25, minute = 65, second = 65) # error out of bounds

time = [Link](2017, 11, 28, 23, 55, 59, 342380)


print(time)

time1 = [Link](year = 2018, month = 3, day = 10)


time2 = [Link](year = 2017, month = 6, day = 23)
time3 = time1 - time2
print(time1, time2, time3)

time1 = [Link](year = 2018, month = 3, day = 10, hour = 2, minute = 9, \


second = 30)
time2 = [Link](year = 2019, month = 2, day = 15, hour = 5, minute = 45, \
second = 40)
time3 = time1 - time2
print(time1, time2, time3)

time = [Link](days = 5, hours = 1, seconds = 33, microseconds = 233423)


print("total seconds =", time.total_seconds())
print("total days", [Link])
print("total microseconds",[Link])

time1 = [Link](weeks = 3, days = 1, hours = 5, seconds = 30)


time2 = [Link](days = 8, hours = 10, minutes = 20, seconds = 40)
time3 = time1 - time2
time4 = time1 + time2
time5 = time1/60
print(time1, time2, time3, time4, time5)
2019-01-28

22:30:10

2017-11-28 23:55:59.342380

2018-03-10 2017-06-23 260 days, 0:00:00

2018-03-10 02:09:30 2019-02-15 05:45:40 -343 days, 20:23:50

total seconds = 435633.233423


total days 5
total microseconds 233423

22 days, 5:00:30 8 days, 10:20:40 13 days, 18:39:50 30 days, 15:21:10 8:53:00.500000

Reading values

Input does not typecast your input values as stated on some websites. All values are read as strings
and you have to typecast them in the code. Input should be validated if you do not want your program
to end with errors due to a wrong character entered, i.e., accidentally typing a letter instead of a
number.
val1=input() #input a string abc
val2=input() #input an integer 34
val3=input() #input a float .67
print (type(val1), type(val2), <class 'str'> <class 'str'> <class 'str'>
type(val3))

# Calculate the price of an hamburger order. You get one hamburger for free

hamburgerPrice = 4.65

JC van Staalduinen 2019 18


Week 2 – Algorithmics Python Notes

x = input('Enter your name:')


print('Hello, ' + x)

num = int (input("How many hamburgers do you want?")) # input is read as a string,
# change to integer
discount = float(input("discount?")) # input is read as a string,
# change to floating point
totalPrice = num * hamburgerPrice
totalPrice = totalPrice - totalPrice*discount

print("Number of hamburgers: {:3d} Cost: {:5.2f}".format((num+1), totalPrice))


Enter your name:Peter
Hello,Peter
How many hamburgers do you want?3
discount?.05
Number of hamburgers: 4 Cost: 13.25

hamburgerPrices = input("Please enter values") # enter a list of values


print(hamburgerPrices)
Please enter values 3.75, 4.75, 3.50, 5.95, 10.30
3.75, 4.75, 3.50, 5.95, 10.30

JC van Staalduinen 2019 19

You might also like