2019 Python Basic
2019 Python Basic
Python Notes
JC van Staalduinen 2019
IDLE
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.
Hello World
>>>
PyCharm IDE
As an easier alternative to creating Python programs download the PyCharm IDE from
[Link].
➢ 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
Type
print(“Hello World”)
This IDE will help you avoid compile type errors in your code.
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
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
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),
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.
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.
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
print([Link](12.67)) 12
print([Link](-12.67)) -12
print([Link](x)) 3.559494346111537
#trig functions
x = 2.5 # radians
y = 90 #degrees
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](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
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
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
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.
%s or formatting
numStudents = 300
classNumber = 2
stringClass = "class"
outputLineStudents = "There are %s students"
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
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
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet1 = "abcdeabcdeabcdeabcde"
alphabet3 = "ABCabc"
alphanum = "123abc"
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
print([Link]()) True
print([Link]()) False
print([Link]()) True
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([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([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]("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]("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
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
print([Link](36,"*")) *****abcdefghijklmnopqrstuvwxyz*****
print([Link](36,"*")) abcdefghijklmnopqrstuvwxyz**********
print([Link](35,"*")) *********abcdefghijklmnopqrstuvwxyz
#print([Link](35,"@#")) error:fill #fill must be only 1 character
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.
#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]
#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)
#reset oceans
del oceans[2]
['Pacific', 'Atlantic', 'Indian', 'Arctic', 'Total', 'new Oceans']
[1,2,3,4]
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)
#combine lists
comb = zip(oceans,sizeSqKm)
print(list(comb))
['Pacific', 'Atlantic', 'Indian', 'Antarctic', 'Arctic', 10911, 8376, 7258, 7236,
5450]
Separate lists
a1, a2, a3 = [1, 2, 3]
print(a1, a2, a3) 1 2 3
separate = list("abc")
print(separate) ['a', 'b', 'c']
Copy lists
#Be careful when assigning lists to other lists. Rather use copy.
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']
List functions
numbers = [1,1,2,3,5,1,4,2,5,1]
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]
[5, 4, 1, 3, 2, 1, 1]
[1, 1, 1, 2, 3, 4, 5]
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')
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"))
print(daysOfMonths)
[Link]() #remove last item
print(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'}
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}
{}
timestr1 = [Link]("%H:%M:%S")
print("time:", timestr1) time: 14:20:18
today = [Link]()
print(today) 2019-07-22
#time = [Link](hour = 25, minute = 65, second = 65) # error out of bounds
22:30:10
2017-11-28 23:55:59.342380
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
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