Python Programming Language
Python Programming Language
Halil Özmen
These Python notes are a brief summary of Python programming language, and contains information
about some of the features of Python. These notes are intended to be used as a check list by the
instructor who teaches programming courses to students.
The first ten chapters can be used in an introduction to programming course targetting students who
has no programming knowledge, and the last four chapters can be used in more advanced Python
programming courses.
TABLE OF CONTENTS
1. Introduction to Computers and Programming ...............................................................................2
1.1. Introduction to Computers .......................................................................................................2
1.2. Introduction to Computer Programming ..................................................................................3
2. Introduction to Python ..................................................................................................................4
2.1. Installation of Python...............................................................................................................4
2.2. Running Python Environment .................................................................................................4
2.3. Basic Python Syntax ...............................................................................................................5
2.4. Data Types .............................................................................................................................5
2.5. Variables.................................................................................................................................6
2.6. Assignments ...........................................................................................................................7
2.7. Type Conversion .....................................................................................................................7
2.8. Basic Input and Output ...........................................................................................................8
3. Operators and Control Flow Structures ........................................................................................8
3.1. Operators................................................................................................................................8
3.2. Selection Statements ..............................................................................................................9
3.3. Loop Statements...................................................................................................................12
3.3.1. range() Function ................................................................................................................12
3.3.2. for Loops ...........................................................................................................................12
3.3.3. while Loops .......................................................................................................................14
3.3.4. break and continue Statements .........................................................................................15
4. Functions ...................................................................................................................................16
4.1. Basics of Functions ...............................................................................................................16
4.2. Built-in Python Functions ......................................................................................................16
4.3. Defining Functions ................................................................................................................17
5. Strings .......................................................................................................................................19
5.1. String Indexing ......................................................................................................................20
5.2. String Slicing .........................................................................................................................20
5.3. String Methods......................................................................................................................21
5.4. String Formatting ..................................................................................................................23
6. Lists ...........................................................................................................................................24
7. Tuples........................................................................................................................................29
8. Sets ...........................................................................................................................................30
9. Dictionaries ................................................................................................................................31
10. File Input and Output .................................................................................................................33
11. NumPy Arrays............................................................................................................................35
12. 2D Graphics in Python with Matplotlib ........................................................................................38
13. Classes and Objects ..................................................................................................................43
14. Python GUI Programming ..........................................................................................................45
A. Random Number Generation .....................................................................................................50
1. Introduction to Computers and Programming
1.1. Introduction to Computers
Computer Components:
A computer consists of central processing unit (CPU), memory and input/output (IO) modules.
CPU controls the computer and instructions are run by the CPU.
CPU consists of control unit, arithmetic logic unit (ALU), registers and interconnections among
these units. The control unit controls the CPU.
Central Arithmetic
Processing Memory Control Unit Logic Unit
Unit Intercon- (ALU)
System
(CPU) Intercon- nection in
nection CPU
Input/
Output Registers
Modules
Input Devices: keyboard, mouse, harddisk, flash disk, microphone, modem, etc.
Output Devices: monitor, harddisk, flash disk, sound speaker, modem, printer, etc.
Fetch-Execute Cycle:
The execution of a machine code program on a von Neumann architecture computer occurs in a
process called fetch-execute cycle:
initialize the program counter
repeat forever
fetch the instruction pointed by the program counter
increment the program counter to point at the next instruction
decode the instruction
execute the instruction
end repeat
The programming languages are easier to understand and write than CPU instructions.
Computer programs need to be translated to CPU instructions for the CPU to understand them
and run them.
Python 2 Halil Özmen
1.2. Introduction to Computer Programming
Computer Program:
A computer program is a sequence or set of instructions in a programming language for a
computer to execute.
Programming Languages:
A programming language is a system of notation for writing computer programs.
Assembly Language is any low-level programming language with a very strong correspondence
between the instructions in the language and the architecture's machine code instructions.
A high-level language is any programming language that enables development of a program in a
much more user-friendly programming context and is generally independent of the computer's
hardware architecture.
Wing Personal IDE can be used to write and run Python programs, and can be downloaded from:
https://wingware.com/downloads/wing-personal.
In Wing Personal, click on to create a new Python program file, write the program in the program
window, then click on to run the program. Wing will first ask you to save this program file, (save it
to your Python program directory), then it will run and show the results in "Debug I/O" window.
The "Debug I/O" window may be moved to an appropriate position.
2.5. Variables
In Python, variable names must start with an alphabetical character (A-Z, a-z) or underscore '_', and
can contain alphanumeric character (A-Z, a-z, 0-9) or underscore '_'.
Variable names are case sensitive. Example: a and A are two different variables.
Variable names can not start with a digit and can not contain space or other special characters.
Valid variables: a z A Z a8 _a8 _ _0 a1 _1a c3po C3pO
Invalid variable names: 8a a-8 a8 a&b a^b
Good variable names make programs more readable by humans. Since programs often contain many
variables, well-chosen variable names can make a program more easily understandable.
a = 7
pi = 3.1415962535
city = "Ankara"
x = 10
print('x =', x)
x = 20 # value of x is changed
print('x =', x)
x = 3.14159 # value of x is changed again
print('x =', x)
x = 'Antalya' # x has been changed one more time
print('x =', x)
x = '30' + "4444" # x has been changed once more
print('x =', x)
Expressions:
An expression contains one or more variables or constants, and may contain operators and/or
parenteses.
7 + 8 10741 // (2 ** 8) a = b + (c * 2) / (a - 1)
7.2 ** 2 c = (a + 2) / b b * b – (4 % a * c / (d - 4)) ** 0.5
A user variable or function name can not be same as a Python keyword, or an existing Python
function name.
Python Keywords (Reserved Words):
False, None, True, and, as, assert, async, await, break, class,
continue, def, del, elif, else, except, finally, for, from,
global, if, import, in, is, lambda, nonlocal, not, or, pass,
raise, return, try, while, with, yield.
The input() function produces a string from the user's keyboard input. If we wish to treat that input as
a number, we can use the int or float function to make the necessary conversion:
a = input("Enter anything: ") # a is a string
n = int(input("Enter a number: ")) # an integer must be entered, error otherwise
x = float(input("Enter a number: ")) # a number must be entered, error otherwise
Arithmetic Operators: Addition (+), Subtraction (-) and Multiplication (*) performs as expected.
Division (/): always returns a floating point number. 20 / 5 4.0, 17 / 3 5.66666666666667
Floor division (//): discards the fractional part. Eg: 48 // 10 will yield 4; 4.8 // 2 2.0
Modulus operator (%): computes remainder of an integer division. 17 % 10 7, 28 % 2 0.
Power operator (**): computes power. Eg: 7 ** 2 49, 2 ** 3 8.
Precedence of Operators:
Level Operators Meaning
1 () Parentheses
2 ** Exponent (power)
3 +x -x ~x Unary plus, Unary minus, Bitwise NOT
4 * / // % Multiplication, Division, Floor division, Modulus
5 + - Addition, Subtraction
6 << >> Bitwise shift operators
7 & Bitwise AND
8 ^ Bitwise XOR
9 | Bitwise OR
10 ==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
11 not Logical NOT
12 and Logical AND
13 or Logical OR
Rules:
The condition must be followed by a colon ':'.
All statements in a block must be equally indented.
I.e. Equal indentation is mandatory inside the same block.
If the condition is True, then the block is executed, then execution continues after the block.
If the condition is False, the block is not executed, the execution continues directly after the block.
x = 1 if n >= 10 and n <= 99:
if x == 1: ....
print("x is 1.") ....
# some Python statements # After if statement
a = 24 if a >= b and c == d:
b = 60 ....
if a < b: .... if-block statements
a = b + 1 ....
print("a =", a, " b =", b) # After if statement
# some Python statements
Nested if Statement:
Nested if statements are structures where there is (inner) if-statement inside another (outer) if-
statement.
If there are nested if-statements only inside else-blocks, then if- elif statements can be used.
if - elif Statement:
The basic form of an if - elif - else statement is as follows:
if condition1: # Corresponding nested if.
block-1 if condition1:
elif condition2: block-1
block-2 else:
elif condition3: if condition2:
block-3 block-2
elif condition-n: else:
block-n if condition3:
....(a series of elif statements) block-3
else: else:
else-block else-block
........
The condition are checked sequentially until the first True condition is found, then the block of the
True condition will be executed, then the program will continue after the whole if-elif-else statement.
hour = int(input("Enter hour: "))
if hour < 12:
print("It is morning.", hour)
elif hour < 14: # hour >= 12
print("It is noon.", hour)
elif hour < 19:
print("It is afternoon.", hour)
elif hour < 23:
print("It is evening.", hour)
else:
print("It is night.", hour)
Exercices:
1) Write a Python program that inputs an integer number entered by user, and prints its double if it is less
than 1000, or print half of it otherwise.
2) Write a Python program that inputs an integer number, then checks if the number is even or odd, and
display an appropriate message.
3) Write a Python program that inputs two integer numbers, then checks if the first number is divisible by the
second number or not, and display an appropriate message.
4) Write a Python program that inputs two integer numbers, then checks if the first number is greater than
twice the second number or less than half of 2nd number, and display an appropriate message.
5) Write a Python program that inputs a grade entered by user, and then assign "A" to letter if grade ≥ 90, "B"
to letter if 75 ≤ grade < 90, "C" if 60 ≤ grade < 75, "D" if 45 ≤ grade < 60, and "F" if grade < 45.
6) Write a Python program that inputs an integer, and depending on the value of the number, display "<num>
has more than 6 digits", "<num> has 4 to 6 digits", "<num> has less than 4 digits".
7) Write a Python program than inputs an integer number, and prints an appropriate message for the
following ranges: < -999, between -999 and -1 (inclusive), between 0 and 999 (inclusive), and > 999.
Examples:
# Prints out the numbers 0,1,2,3,4
for x in range(5): # from 0 (inclusive) till 5 (exclusive)
print(x)
# Prints out 3,4,5
for x in range(3, 6): # from 3 (inclusive) till 6 (exclusive)
print(x)
# Prints out 4, 6, 8
for x in range(4, 10, 2): # from 4 till 10 (exclusive), 2 by 2
print(x)
# Prints out 10, 8, 6
for x in range(10, 4, -2): # from 10 till 4 (exclusive), by -2
print(x)
print ("loop for elements of a list:")
primes = [2, 3, 5, 7, 11, 13, 17, 19] # This is a list.
for prime in primes:
print(prime)
Find the sum of numbers divisible by n from n1 to n2 (both inclusive). n1, n2 and n are integers.
# Solution 1: Easy to think.
sum1 = 0
for k in range(n1, n2+1): # Generate all numbers from n1 to n2
if k % n == 0: # Check if number is divisible by n
sum1 += k # Add to sum
print(sum1)
# Solution 2: Have a much better performance
if n1 % n == 0: # If n1 is divisible by n,
k1 = n1 # then start number is n1
else: # Find smallest number greater than n1 and divisible by n.
k1 = n1 - n1 % n + n
sum2 = 0
for k in range(k1, n2+1, n):
sum2 += k
print(sum2)
for f in range(1,5):
print("f=", f, "start")
for n in range(1,4):
print("n=", n)
print("f=", f, "end")
print("Triangle of asterisks")
for r in range(1, 5): # r: 1, 2, 3, 4
for c in range(r):
print("*", end="")
print()
Examples:
# Sum of entered numbers until a non-positive number is entered.
sum1 = 0
n = int(input("Enter a number: "))
while n > 0:
sum1 += n
n = int(input("Enter a number: "))
print(sum1)
# while loop: prints out 0 1 2 3 4
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
print("After while loop: count =", count)
# Print 10 9 8 7 6 ... 0
print("Countdown:")
seconds = 10
while seconds >= 0:
print(seconds)
seconds -= 1 # seconds = seconds - 1
# For a group of bacteria, with a given increase rate,
# find the time that will take to double the population.
time = 0
population = 1000 # 1000 bacteria to start with
growth_rate = 0.21 # 21% growth per hour
print("Bacteria population =", population)
while population < 2000:
time += 1 # or: time = time + 1
population = int(population + growth_rate * population)
# print("Hour:", time, " Population:", population)
print("It took", time, "hours for the bacteria to double.")
print("After", time, "hours, there are", population , "bacteria.")
print("Fibonacci numbers < 100:")
fibo1 = 1
fibo2 = 1
print(fibo1, fibo2, end=" ")
fibo3 = fibo1 + fibo2
while fibo3 < 100:
print(fibo3, end=" ")
fibo1, fibo2 = fibo2, fibo3
fibo3 = fibo1 + fibo2
continue statement:
The continue statement causes Python to skip immediately the rest of the current iteration (stop the
current iteration), and continue with the next iteration.
for n in range(1, 10):
if n >= 5 and n <= 7:
continue # continue with next iteration
print(n)
for n in range(10, 41):
if n % 2 == 0: # if n is even
continue # then continue with next iteration
print(n)
str = 'Oz48gur19luk'
total = 0 # The sum of the digits seen so far.
count = 0 # The number of digits seen so far.
for c in str:
if not c.isdigit(): # If not digit,
continue # then continue with next character.
count = count + 1
total = total + int(c)
print("Number of digits =", count, " Sum of digits =", total)
Exercises:
1. Write a program that inputs two integer numbers (n1, n2), finds and prints the sum of numbers
between n1 and n2 (both inclusive).
2. Write a program that that inputs three integer numbers (n1, n2, n), prints the numbers divisible
by n between n1 and n2 (both inclusive).
3. Write a program that that inputs two integer numbers (n1, n2), prints the numbers divisible by 10
between n1 and n2 (both inclusive).
4. Write a program that inputs an integer number and print the first digit of that number.
5. Write a program that inputs n integer numbers and print their average. Input first n.
6. Write a program that inputs integer numbers until 0 (zero) is entered and print their average.
7. Write a program that inputs positive integer numbers until a non-positive number is entered and
prints the maximum number.
Function Call:
The general form of a function call is as follows:
function_name(arguments)
Function Arguments:
Arguments are placed between parentheses and separated by a comma.
An argument is an expression that appears between the parentheses of a function call.
int(7.8) print(a, b+c) abs(x) abs(n - 7) int(1.5**2) round(a - b / c, 2)
If a function returns a value, then its function call can be used in expressions:
aa = abs(-7 + 2) + abs(3.3 * -2) * 2 # 5 + 6.6 * 2 = 18.2
result = max(7, 12) * abs(-2) # 12 * 2 = 24
for k in range(1, 40, 7): # => [1, 8, 15, 22, 29, 36]
return Statement:
return expression
Returned value replaces the function call. def square(num):
Assume that a function named square is defined as: result = num * num
a = b * square(c+d) - e return result
In the above function call, argument (c+d) is evaluated first and becomes the value of the parameter of
square() function. square() function returns some value (e.g. the square of its parameter), and the
returned value replaces the function call in the expression: b * square(c+d) - e.
Local Variables:
Local variables are the variables used in functions.
They do not exist outside the function that they are used.
# quadratic: returns (a * x ** 2 + b * x + c)
def quadratic(a, b, c, x):
first_term = a * x ** 2 # local variable first_term
second_term = b * x # local variable second_term
third_term = c # local variable third_term
return first_term + second_term + third_term
q = quadratic(1, 2, 3, 4)
print(a) # ERROR: a is defined in function, not here
print(first_term) # ERROR: first_term is defined in function
Examples of function definitions and Python programs that uses defined functions:
def convert_to_celsius(fahrenheit):
return round((fahrenheit - 32) / 1.8, 2)
def quadratic(a, b, c, x):
return a * x ** 2 + b * x + c
Exercises:
1. Write a function that gets an integer as parameter and returns the factorial of the parameter.
2. Write a function that gets an integer as parameter and returns True if the parameter is a prime
number, and returns False otherwise.
3. Write a function that gets two integers as parameters, and returns the sum of all integer numbers
between these two numbers (both inclusive).
4. Write a function that gets three integers (say n1, n2, k) as parameters, and returns the sum of all
integer numbers divisible by k from n1 to n2 (both inclusive).
5. Write a function that gets three integers (say n1, n2, k) as parameters, and returns the average
of all integer numbers divisible by k from n1 to n2 (both inclusive).
6. Write a function that returns the list of prime factors of a given integer number.
7. Write a function that gets a string as parameter, and returns True if the alpha numeric characters
forms a palindrome. Example: "Madam, I'm Adam!" is a palindrome.
Hint: step 1: create a string that contains only alphanumeric characters; step 2: convert all to
uppercase; step 3: check if it is symmetric.
8. Write a function that returns the number of occurences of a number in a list.
9. Write a function that returns the number of peak (deep) values in a list.
Some important ASCII codes: ' ' (space): 32 (20H), '0' : 48 (30H), 'A': 65 (41H), 'a': 97 (61H).
' ' (space) < '0' .... '9' < 'A' .... 'Z' < 'a' .... 'z'
Strings can be assigned and can be compared to other strings.
String Constants
String constants are delimited with either a single quote ('), double quote ("), triple single quote (''') or
triple double quote ("""). The opening and closing quotes must match.
"" # Null string or empty string
"?" "k" "7" "\n" # Strings with a single character
'Antalya' "Antalya is beautiful"
"""Jane's friend asked:\n"Are you alien?".""" # \n : newline.
"René Descartes' # ERROR: opening and closing quotes do not match
print('That\'s beautiful.\n') # "That's beautiful.\n"
print("A single \\ back slash. Time is\nnot\t\"linear\".")
print(1, "\t", 2, "\n", 4, "\t", 8)
String Operators:
Operator Description Examples
+ Concatenation operator '+' concatenates two "I love" + " nature!"
strings. "Good" + " morning" + "!"
surname + ", " + name
* Repeats a string. "At" * 4 # "AtAtAtAt"
10 * '*' # "**********"
Comparing Strings:
Case Sensitive Comparison: (ASCII codes are used)
"ZZZ" < "aaa" "Abcd" < "Abcd "
"aaZZZZ" < "aaa" "CS99" > "CS8888"
"KZBZHGV" < "KZa" "CS9999" < "Cs88"
"abcd" > "ABCD" "ABA" > "AB9999"
Case Insensitive Comparison: (Upper and lower case of same letter are treated as equal.)
"ZZZ" > "aaa" "CS990a" == "Cs990A"
"KZZZH8" > "KZa" "CS990" > "Cs8888"
"abcd" == "ABCD" "CS990a " > "Cs990A"
Python 19 Halil Özmen
Concatenation with other data types, and str() function:
"Antalya" + 'is' + "beautiful!" # 'Antalyaisbeautiful!'
'Antalya' + 7 # ERROR: Can't convert 'int' object to str implicitly
9 + ' planets' # ERROR: unsupported operand type(s) for +: 'int' and 'str'
"How far is a " + str(7) + " minute walk?" # Number converted to string
"Use " + str(3.14159265359) + " as pi." # Number converted to string
"Alan Turing" + '' # 'Alan Turing'
"" + 'John von Neumann' # 'John von Neumann'
"At" * 4 # "AtAtAtAt"
Methods:
Methods are like functions, but they are associated with a data type/structure or object.
Called by putting a period (.) after the data item then the method name and any parameters.
cnt = string1.count(string2)
In IDLE, to learn all methods of a certain data type using:
dir(<<type>>) # E.g. dir(str)
In IDLE, to learn about a method using:
help(<<type>>.<<method>>)
Example:
help(str.isupper) # help about isupper string method
Return
Method Description
type
s.lower() Returns a copy of the string with all letters converted to lowercase. str
s.upper() Returns a copy of the string with all letters converted to uppercase. str
s.islower() Returns True if all letter characters in the string are lowercase bool
s.isupper() Returns True if all letter characters in the string are uppercase bool
s.isalpha() Returns True if all characters of s are alphabetic (letter characters) bool
s.isdigit() Returns True if all characters of s are digits (numeric characters) bool
s.isalnum() Returns True if all characters of s are alphanumeric (letter or digit) bool
s.isspace() Returns True if all characters of s are whitespace characters bool
s.startswith(s1) Returns True if s starts with s1 bool
s.endswith(s1) Returns True if s ends with s1 bool
s.swapcase() Returns a copy of the string with all letters swapped the case. str
s.count(s1) Returns the number of non-overlapping occurrences of s1 in the string s int
s.find(s1) Returns the index of the first occurrence of s1 in the string s, or -1 if s1 int
doesn't occur. (case sensitive)
s.find(s1, begin) Returns the index of the first occurrence of s1 at or after index begin in the int
string, or -1 if not found.
s.find(s1, begin, Returns the index of the first occurrence of s1 between index begin int
end) (inclusive) and end (exclusive) in the string, or -1 if not found.
s.index(..,..,..) Very similar to find() method. Returns the index of s1 in the string s if found; int
but it gives an error if s1 doesn't occur.
s.replace(f, r) Returns a copy of the string with all occurrences of substring f replaced with str
string r
s.strip() Returns a copy of the string with leading and trailing whitespace removed str
s.lstrip() Returns a copy of the string with leading whitespaces removed str
s.rstrip() Returns a copy of the string with trailing whitespaces removed str
s.strip(s2) Returns a copy of the string with leading and trailing characters in s2 str
removed. a = "aaaBolazaza"; x = a.strip("za") "Bol"
s.split(separator, Returns a list of strings after breaking the given string by the specified list
maxsplit) separator string. text.split() text.split(', ') text.split('\t')
Exercices:
1. Write a function countChar() that gets a string and a character as parameters, and returns the
number of occurences of that character in the string. Do not use count() method.
2. Write a function to determine if a given string contains a numeric type (either integer or decimal).
3. Count how many times a substring occurs in a string including overlapping occurences:
(“banana”, “ana”) -> 2.
4. Write a function that tests if a given string is a palindrome.
5. Write a function countUp() that returns the number of upper case letters in a given string.
6. Write a function upLow() that returns a new string made by converting all upper case letters to
lower and lower case letters to upper in a given string.
7. Write a function shuffle() that gets two strings as parameters, returns a new string made by
shuffling as follows: 1st char from string 1, then 1st char from string 2, then 2nd char from string
1, then 2nd char from string 2, etc. Remaining chars of longer string are placed at end.
format() method:
"...{}...{}...{}...{}...".format(a, b, c, d, ....) # a b c d
"...{0}...{1}...{2}...{3}...".format(a, b, c, d, ....) # a b c d
"...{0}...{2}...{1}...{2}...".format(a, b, c, ....) # a c b c
"...{:d}...{:10s}...{:.2f}...{:04d}...".format(a, b, c, d) # a b c d
Creating Lists:
listName = [] # Create empty list
listName = list() # Create empty list
listName = list(argument) # Create list from argument
listName = [expression1, expression2, ... , expressionN]
monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# indexes: 0 1 2 3 4 5 6 7 8 9 10 11
# indexes: -3 -2 -1
List Indexing: The index of list elements starts from 0 (zero). Negative indexes are used to refer to
elements at the end of a list: [-1] for the last element, [-2] for one before the last, etc.
values = [4, 10, 3, -6, 8] # Process each element with for loop:
print(values[3]) # will print -6 values = [4, 10, 3, -6, 8]
for j in range(len(values)): for n in values:
print(j, values[j]) print(n, n ** 2)
values[j] += 1 # changes list n += 1 # doesn't change list elements
Deleting Elements:
del construct is used to delete an element with a given index or slice.
del list1[2] # remove item with index 2
del list1[-1] # remove the last item.
del list1[2:5] # remove items with index 2, 3, 4
Functions:
Function Description Examples
len(L) Returns the number of items in list L n = len(list1)
list(seq) Creates a list from elements of a range or a tuple. a = list(range(10, 100, 2))
a = list((2, 3, 5, 7))
max(L) Returns the maximum value in list L nmax = max(list1)
min(L) Returns the minimum value in list L nmin = min(list1)
sum(L) Returns the sum of the values in list L sum1 = sum(list1)
sorted(L) Returns a copy of list L where the items are ascendingly list2 = sorted(list1)
sorted. (This does not mutate L.)
List Operators:
+ produces a new list composed by the concatenation of its argument lists. ls = ls1 + ls2
* produces a new list that consists of repeated elements of the multiplied list ls = ls1 * 4
List Slicing
Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Slicing returns a new list. However lists can be modified through slicing.
list1[2:5] = [10, 20] # replaces elements indexed 2-3-4 with [10, 20]
list1[2:5] = [] # removes elements indexed 2-3-4
list1[2:5] = [] # removes elements indexed 2-3-4
list1[:4] = [12, 16] # replaces first 4 elements with [12, 16]
list1[-3:] = [2, 7, 10, 8, 5] # replaces last 3 elements with 2, 7, 10, 8, 5
List Methods:
Method Description
L.append(v) Adds an element at the end of list L
L.insert(i, v) Inserts value v at index i in list L, shifting subsequent items to make room
L.extend(seq) Appends the items in seq to the end of L (seq can be a list)
L.count(v) Returns the number of occurrences of v in list L
L.index(v) Returns the index of the first occurrence of v in L - an error is raised if v doesn’t
occur in L.
L.index(v, beg) Returns the index of the first occurrence of v at or after index beg in L - an error
is raised if v doesn’t occur in that part of L.
L.index(v, beg, end) Returns the index of the first occurrence of v between indices beg (inclusive)
and end (exclusive) in L; an error is raised if v doesn’t occur in that part of L.
L.pop() Removes and returns the last item of L (which must be nonempty)
L.pop(index) Removes and returns item with given index of L (which must be nonempty)
L.remove(v) Removes the first occurrence of value v from list L
L.copy() Returns a copy of the list L
L.clear() Removes all items from list L
L.reverse() Reverses the order of the values in list L
L.sort() Sorts the values in list L in ascending order
L.sort(reverse=True) Sorts the values in list L in descending order
Examples:
lst = [72, 48, 96, 60, 77, 84, 41, 60, 80, 51]
lst.append(92) # add to end
lst.insert(4, 57) # insert to index 4
n = lst.count(60) # number of 60's in lst
j = lst.index(60) # index of first 60 in lst
k = lst.index(60,5) # index of first 60 at or after index 5 in lst
lst.remove(60) # removes first occurence of 60 in lst
x = lst.pop(6) # Deletes element with index 6 from list and returns it
lst2 = lst.copy() # create a copy of lst and assign it to lst2, lst and lst2 are two distinct lists
lst3 = [64, 86] # create a list named lst3
lst.extend(lst3) # add elements of lst3 at the end of lst
lst.reverse() # Reverses the order of elements of lst
lst.sort() # sort elements of lst in ascending order
lst.sort(reverse=True) # sort elements of lst in descending order
del lst[5] # removes lst[5]
del lst[-5:] # removes the last 5 elements of lst
lst.clear() # Removes all elements, i.e. it empties the list.
Examples:
squares = [x**2 for x in range(1, 11)] # 1 4 9 16 25 36 49 64 81 100
a = [-4, -2, 0, 2, 4]
print(a) # [-4, -2, 0, 2, 4]
# create a new list with the values doubled
b = [x*2 for x in a]
print(b) # [-8, -4, 0, 4, 8]
# filter the list to exclude negative numbers
c = [x for x in a if x >= 0]
print(c) # [0, 2, 4]
# apply a function to all the elements
d = [abs(x) for x in a]
print(d) # [4, 2, 0, 2, 4]
# nested for:
a = [x*y for x in [1, 2] for y in [7, 8]]
print(a) # [7, 8, 14, 16]
# nested for:
a = [(x, y) for x in [1, 2] for y in [10, 20]]
print(a) # [(1, 10), (1, 20), (2, 10), (2, 20)]
# is equivalent to:
a = []
for x in [1, 2]:
for y in [10, 20]:
a.append((x, y))
Matrices:
The general form of a matrix:
matrix = [[Row1], [Row2], [Row3], ...., [RowN]]
Examples
m1 = [[2, 4, 3, 7], [5, 1, 0, 6], [7, 9, 1, 3], [4, 8, 2, 3]]
m2 = [[6, 2, 0, 5], [4, 9, 1, 7], [8, 2, 3, 5], [7, 0, 5, 7]]
# Add two matrices:
m3 = m1.copy() # Assign copy of m1 to m3.
for row in range(len(m1)):
for col in range(len(m1[0])):
m3[row][col] += m2[row][col] # Add elements of m2 to m3
print(m3)
print("Matrix transpose:")
def transposeMatrix(m):
tm = []
for col in range(len(m[0])):
trow = []
for row in range(len(m)):
trow.append(m[row][col])
tm.append(trow)
return tm
Exercises:
1. Write a function that returns a new list containing non-negative items of a given list.
2. Write a function that gets as parameter a list and two values (v1 and v2), returns a new list that
contains the elements of the given list which are between v1 and v2 (both inclusive).
3. Write a function that gets as parameter a list and a value, returns a new list that contains the
elements of list which has the same type as value.
Tuple Operators:
+ operator produces a new tuple whose value is the concatenation of its arguments.
* operator produces a new tuple that consists of repeated elements of the multiplied tuple.
in operator checks if an item exists in a tuple.
tp3 = tp1 + tp2
tp4 = tp1 * 4
if x in tp1: # True if value of x exists in tuple tp1
Slicing Tuples:
Slicing tuples is very similar to slicing lists and strings.
print(tup1[2:]) # elements with index 2 to end.
print(tup1[::-1]) # reverse of the tuple.
print(tup1[0:3]) # elements with index 0 to 2.
tup2 = tup1[:3:-1] + tup1[:4] # new tuple
8. Sets
A set is an unordered and unindexed collection with no duplicate elements.
Basic uses include membership testing and eliminating duplicate entries. Sets cannot have two items
with the same value. If there are duplicate values, they will be ignored.
Curly braces or the set() function can be used to create sets.
Note: to create an empty set you have to use set(), not {}. Once a set is created, its items cannot be
changed, but new items can be added to a set, or items can be removed.
set1 = set() # Create an empty set
set2 = set(list1) # Create a set from elements of a list
set3 = set(range(4,9)) # Create a set from values generated by range
set4 = {"abc", 32, True, 4.8, "city"} # A set with different data types
set5 = {"apple", "banana", "cherry", "apple"} # Duplicates are ignored
print(set5) # will print: {'banana', 'cherry', 'apple'}
len() function returns the length of a set, i.e. the number of elements in a set.
n = len(set1)
Set Methods:
Set objects support mathematical operations like union, intersection, difference, and symmetric
difference.
Method Description
s.add(e) Adds an element to the set.
s.remove(e) Removes the specified element (returns None).
s.discard(e) Removes the specified element (returns None).
s.intersection(s2, ...) Returns a set, that is the intersection of two or more sets.
s.union(s2, ...) Return a set containing the union of sets. Set s is not modified.
s.difference(s2, ...) Returns a set containing the difference between two or more sets.
s.symmetric_difference(s2) Returns a set with the symmetric differences of two sets.
s.copy() Returns a copy of the set.
s.update(s2, ...) Update the set with the union of this set and others.
s.isdisjoint(s2) Returns True if intersection is empty (i.e. no common elements).
s.issubset(s2) Returns True if this set is a subset of another set.
s.issuperset(s2) Returns True if this set is a superset of another set.
s.clear() Removes all the elements from the set.
s.difference_update(s2) Removes the items in this set that are also included in another set.
s.intersection_update(s2, ...) Removes the items in this set that are not present in other set(s).
s.pop() Removes randomly an element from the set and returns it.
Examples:
set1 = {2, 4, 8, 16}
set1.add(32)
s1 = {"apple", "banana", "cherry"}
s2 = {"banana", "apricot", "carrot"}
s1.update(s2) # Add elements of s2 to s1 (duplicates ignored)
s1.remove("carrot") # Remove "carrot" from s1
s4 = s1.union(s2) # union of s1 and s2
s5 = s1.intersection(s2) # intersection of s1 and s2
if s1.issubset(s2): # True if all elements of s1 exist in s2
if "banana" in s1: # True if "banana" exists in s1
Functions:
Function Description
len(D) Returns the number of key+value pairs (elements) in dictionary D.
max(D) Returns the maximum key in dictionary D if all keys are numeric or string. Error otherwise.
min(D) Returns the minimum key in dictionary D if all keys are numeric or string. Error otherwise.
sum(D) Returns the sum of the keys in dictionary D if all keys are numeric. Error otherwise.
sorted(D) Returns a list containing the keys of D where the keys are in order from smallest to largest,
if all keys are numeric or string.
Dictionary Methods:
Method Description
D.keys() Returns an immutable object containing all the keys of D.
D.values() Returns an immutable object containing all the values of D.
D.copy() Returns a copy of dictionary D.
D.update(d) Adds element(s) of d to the dictionary D if the key is not in the dictionary.
If the key is in the dictionary D, it updates the element with the new value.
D.get(key, value) If key exists in D then returns D[key], otherwise returns value.
a = dd.get(k, x) # is identical to:
if k in dd: # if k is a key in dd
a = dd[k] # then get the value of that element
else: # otherwise (no key is equal to k)
a = x # get 2nd argument
D.items() Can be used to iterate a dictionary to get both key and value pairs.
for key, value in myDict.items():
print (key, value)
D.popitem() Removes the last key-value pair, returns (key,value) tuple.
D.pop(key) Removes the element with the specified key, returns value of removed element.
del D[key] Removes element with the given key
D.clear() Removes all elements
Examples:
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun',
7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
for key in monthDict:
print(key, monthDict[key]) # Alternative:
mdkeys = monthDict.keys() for key, value in monthDict.items():
print(mdkeys) print(key, value)
mdvals = monthDict.values()
print(mdvals)
monthDay={'Jan':31, 'Feb':28, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30,
'Jul':31, 'Aug':31, 'Sep':30, 'Oct':31, 'Nov':30, 'Dec':31}
for mon in monthDay: | for mon, day in monthDay.items():
print(mon, monthDay[mon]) | print(mon, day)
months={1:['Jan', 31], 2:['Feb', 28], 3:['Mar', 31], 4:['Apr', 30],
5:['May', 31], 6:['Jun', 30], 7:['Jul', 31], 8:['Aug', 31],
9:['Sep', 30], 10:['Oct', 31], 11:['Nov', 30], 12:['Dec', 31]}
for j in months: | for k, v in months.items():
print(j, months[j]) | print(k, v)
for j in months: | for k, v in months.items():
print(j, months[j][0], months[j][1]) | print(k, v[0], v[1])
a1 = {'a': 100, 'b': 200} def mergeDict(d1, d2):
a2 = {'x': 300, 'y': 200} d = d1.copy()
newd = mergeDict(a1, a2) d.update(d2)
print(newd) return d
Dictionaries as counters:
Dictionaries can be used as counters of occurences of values.
# Use dictionary as counter:
votes = ["Kemal", "Raquel", "Ali", "Raquel", "Raquel", "Jane", "Jane",
"Kemal", "Jane", "Kemal", "Raquel", "Jane", "Kemal", "Raquel", "Ali"]
counts = {} # Create an empty dictionary
for name in votes:
if name in counts: # if name exists as key in dict. counts,
counts[name] += 1 # then increment that counter,
else: # if name doesn't exist as key in counts,
counts[name] = 1 # then add new element to counts.
print(counts) # print the dictionary
for name in counts:
print("%-12s :%3d" % (name, counts[name])) # print nicely
# First for loop can be changed with the following:
cnt = {} # Create an empty dictionary
for name in votes:
cnt[name] = cnt.get(name, 0) + 1 # Add or update elements.
print(cnt) # print the dictionary
Opening Files:
In order to read from or to write to a file, that file must be opened.
file = open(filename, mode) # This is the general form.
file = open("data.txt", "r") # Open file data.txt for reading
file = open("data2.txt", "w") # Open file data2.txt for writing
file = open("data3.txt", "a") # Open file data3.txt for appending
File modes:
"r" Read mode. The file must exist.
"w" Write mode. If the file exists then the file will be overwritten. I.e. the previous contents of the
file will be destroyed, and the file will be re-created.
"a" Append to the end of the file. Writes will write to the end of the file.
Closing Files:
When a file will not be processed anymore, then it must be closed.
file.close()
File Methods:
Method Description
F.read() Reads all contents of the file and returns as a string.
F.read(n) Reads n characters from the file and returns as a string.
F.readlines() Reads all lines of the file and returns the lines as a list.
F.readline() Reads one line from the file and returns as a string.
F.write(string) Writes a string to file. Argument must be a string.
F.writelines(list) Writes a list of strings to the file by concatenating all.
F.close() Closes the file.
Examples:
file = open("data.txt", "r") # Open file data.txt
contents = file.read() # Store all content into a string
file.close() # Close file
upcount = 0 # Counter
for c in contents: # for each character of the string
if c.isupper(): # if character is uppercase
upcount += 1 # then increment the counter
print(upcount) # print counter
fp = open("data.txt", "r") # Open file data.txt
lines = fp.readlines() # Read all lines into a list
fp.close() # Close file
for line in lines: # for each line in the list
print(line.rstrip()) # right strip whitespaces and then print
file = open("data.txt", "r") # Open file data.txt
for line in file: # Read each line including \n at end of line
print(line.rstrip()) # rstrip whitespaces and then print.
file.close() # Close file
Python 33 Halil Özmen
file = open ("data.txt", "r")
contents = file.read() # Store all content into a string
file.close() # Close file
strnums = contents.split() # Split contents by whitespaces
total = 0
for s in strnums: # for each element of list of strings
total += float(s) # convert element to number, add to total
print(total) # print total
Writing to Files:
F.write() method can be used to write to text files.
# Create new file or if file exists then overwrite the file:
file1 = open('topics.txt', 'w')
file1.write('Computer Science')
file1.close()
# Append to end of file: lst = ["Aa", "777", "x"]
with open('topics.txt', 'a') as output_file: f1 = open("aa.txt", "w")
output_file.write('Software Engineering') f1.writelines(lst)
with open("numbers.txt", 'w') as output_file: f1.close()
a, b, c = 88, 7, 1.618
File content will be:
line = '|%4d|%2d|%8.4f|\n' % (a, b, c)
output_file.write(line) Aa777x
Exercises:
1. Write a function dispfile() that takes a file name as parameter, reads all lines from this file and
displays them on screen and returns the number of lines displayed.
2. A file contains only integer and float numbers. Write a function that takes a file name as
parameter, reads all numbers in the file, returns the sum of the numbers.
3. Write a function writeNumbers() that takes a file name as parameter, write to the file each on a
different line, the numbers from 100 to 1000 (100 200 ... 1000) incremented by 100.
4. The lines of a file contains only letters, digits, spaces, dot ('.') and comma (',') characters. Write a
function findNums() that takes a file name as parameter, reads the contents of this file, replaces
dots and commas with space, finds and prints the words that consists only of digits.
NumPy Methods:
Method Description
array() Constructor. Can be used to convert a list or tuple to NumPy array (ndarray).
arange() Similar to Python range() function. Accepts int and float parameters.
reshape() Reshape a NumPy array. Used to create multi dimensional arrays.
zeros(n) zeros((r, c)) Array of zeros (0.0). (Can be one or more dimensional.)
ones(n) ones((r, c)) Array of 1.0's. (Can be one or more dimensional.)
full(n, v) full((r, c), v) Array of v values. (Can be one or more dimensional.)
identity(n) or eye(n) Identity matrix of n x n dimensions
transpose() Returns a new matrix that is transpose of a matrix
dot() Returns result of matrix multiplication
tile(arr, n) Tile array elements. np.tile(np.arange(1, 5), 2) --> [1 2 3 4 1 2 3 4]
repeat(arr, n) Repeat array elements. np.repeat(np.arange(1, 5), 2) --> [1 1 2 2 3 3 4 4]
append(arr, arr2, Returns a new array by appending values (or another array) to the end of an
axis=None) array (at the given axis). Example for 1D arrays: ar3 = np.append(ar1, ar2)
insert(arr, idx, arr2, Returns a new array by inserting values (or another array) at the given index
axis=None) to an array, along the given axis. Example (1D): ar3 = np.insert(ar1, 4, ar2)
delete(arr, obj, Return a new array with sub-arrays along an axis deleted.
axis=None) For a 1-D array, this returns those entries not returned by arr[obj].
sum(axis=None) Returns sum of values (along the given axis)
max(axis=None) Returns maximum of values (along the given axis)
min(axis=None) Returns minimum of values (along the given axis)
copy() Returns a copy of the array.
random.randint(n, Returns an array containing random numbers from 0 to (n-1).
size=() ) a = np.random.randint(100, size=(3, 4)) # 3x4 matrix filled with values 0-99.
random.choice(iterable, Returns an array containing randomly selected numbers from the iterable.
size=() ) x = np.random.choice(range(10, 101, 10), size=(4, 5)) # This gives
4x5 matrix consisting of randomly selected numbers from 10, 20, ..., 100
random.rand(n) Returns an array of n random numbers from 0.0 to 1.0 (1.0 excluded).
Examples:
ls = [42, 7, 84, 5, 12, 24] [42, 7, 84, 5, 12, 24]
a = np.array(ls) [42 7 84 5 12 24]
a = np.array(ls).reshape(2, 3) [[42 7 84]
[ 5 12 24]]
a = np.arange(1, 9) [1 2 3 4 5 6 7 8]
a = np.arange(1.0, 9) # default increment = 1 [1. 2. 3. 4. 5. 6. 7. 8.]
a = np.arange(10, 21, 2) [10 12 14 16 18 20]
a = np.arange(1.2, 2.5, 0.2) [1.2 1.4 1.6 1.8 2. 2.2 2.4]
a = np.arange(1, 13).reshape(3, 4) [[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
a = np.arange(1, 13).reshape(3, 4) * 10 [[ 10 20 30 40]
[ 50 60 70 80]
[ 90 100 110 120]]
b = a[1] # Indexing [ 50 60 70 80]
c = a[1:, 2:] # Slicing [[ 70 80]
[110 120]]
a = np.arange(10, 130, 10).reshape(3, 4) [[ 10 20 30 40]
[ 50 60 70 80]
[ 90 100 110 120]]
a = np.arange(1, 13).reshape(4, 3).transpose() [[ 1 4 7 10]
[ 2 5 8 11]
[ 3 6 9 12]]
a = np.eye(3) [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
a = np.eye(2, dtype=int) [[1 0]
[0 1]]
a = np.ones(4, dtype=int) [1 1 1 1]
a = np.ones((2,3)) [[1. 1. 1.]
[1. 1. 1.]]
a = np.full((2,3), 7) # or: [[7 7 7]
a = np.ones((2,3), dtype=int) * 7 [7 7 7]]
a1 = np.arange(1, 5) [1 2 3 4]
a2 = np.arange(24, 19, -2) [24 22 20]
a3 = np.append(a1, a2) [ 1 2 3 4 24 22 20]
print(a3)
a4 = np.insert(a1, 1, a2) [ 1 24 22 20 2 3 4]
print(a4)
import numpy as np
m1 = np.arange(1, 7).reshape(2, 3) # matrix 2x3: [[1 2 3] [4 5 6]]
m2 = m1.reshape(3, 2) # matrix 3x2: [[1 2] [3 4] [5 6]]
m3 = np.array([[1,2,3],[4,5,6]]) # convert nested list to numpy matrix
zz = np.zeros((2, 3), dtype=int) # 2 x 3 matrix of 0's
a1 = np.ones((3, 4)) # 3 x 4 matrix of 1.0's
a1 = np.ones((3, 4), dtype=int) # 3 x 4 matrix of 1's
im = np.identity(4) # 4 x 4 identity matrix
a1 = a1 + 7 # add a number to every element of array
m4 = 4 * m2 # multiply every element of array by a number
m4 = m2 ** 2 # square of every element of array
m7 = m5 + m6 # element-by-element addition (equal dimensions)
m7 = m5 * m6 # element-by-element multiplication (equal dimensions)
m7 = m5 // m6 # element-by-element floor division (equal dimensions)
m7 = m5 % m6 # element-by-element modulus (equal dimensions)
mc = ma.dot(mb) # matrix multiplication of ma and mb
md = ma.transpose() # Transpose of a matrix
Matplotlib is a low level graph plotting library in Python that serves as a visualization utility.
Matplotlib was created by John D. Hunter.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is very
easy. Install it using this command in command line under Windows cmd:
pip install matplotlib
If this command fails, then use a python distribution that already has Matplotlib installed, like
Anaconda, Spyder etc.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module statement:
import matplotlib
Matplotlib Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Draw a line:
To draw a line, plot() method is used with two lists or NumPy arrays as parameters, the first
contains the start and end x values, and the second contains the start and end y values.
Draw a line in a diagram from x-y position (4, 7) to x-y position (12, 20):
import matplotlib.pyplot as plt
xpoints = [1, 2, 6, 8]
ypoints = [3, 8, 1, 10]
plt.plot(xpoints, ypoints)
plt.show() # Display graph window
plt.plot(ypoints)
plt.show()
plt.title("Travel Statistics")
plt.xlabel("Days")
plt.ylabel("Distance Covered (km)")
x = list(range(1, 6))
y = [240, 100, 288, 0, 160]
plt.plot(x, y)
plt.show()
Markers:
The keyword argument marker can be used to emphasize each point with a specified marker:
Mark each point with a circle:
import matplotlib.pyplot as plt
plt.title("Marker")
xp = list(range(1, 5))
yp = [3, 8, 1, 10]
plt.plot(xp, yp, marker = 'o')
plt.show()
Grid:
With Pyplot, grid() function is used to add grid lines to the plot. best 0
upper right 1
Legend: upper left 2
To place a legend: lower left 3
lower right 4
• labels need to be specified in plot() method calls,
right 5
• plt.legend() must be called to display those labels.
center left 6
• to choose legend location, use plt.legend(loc=....).
center right 7
See the example in "Multiple Lines" below. lower center 8
Ref: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html upper center 9
center 10
Multiple Lines:
You can plot as many lines as you like by simply adding more plt.plot() functions:
Draw three lines by specifying a plt.plot() function for each line:
import matplotlib.pyplot as plt
plt.title("Multiple Lines")
plt.xlabel("Days")
plt.ylabel("Km")
x1 = list(range(1, 5))
y1 = [3, 8, 1, 10]
x2 = x1
y2 = [6, 2, 7, 11]
Plotting Functions:
A function can be plotted by creating y-points of the function for given x points.
# Draw an x-y plot of a function.
# Function: y = x^2 - 7x + 1
def func1(xs):
return [(x**2 - 7*x + 1) for x in xs]
plt.title("Sin")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.plot(x, y, "o--")
plt.show()
Pie Charts:
With Pyplot, the pie() function is used to draw pie charts.
# Pie chart
import matplotlib.pyplot as plt
plt.title("Fruits")
# Pie chart
import matplotlib.pyplot as plt
plt.title("Fruits")
References:
https://www.w3schools.com/python/matplotlib_intro.asp
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.html (complete list of methods)
Class
A Class is a "blueprint" for creating objects. To create a class, the keyword class is used:
class MyClass:
Object
Objects can be created from defined classes.
p1 = MyClass() # Create an object named p1 from class MyClass
class Student:
def __init__(self, id, name, dept): # Constructor method (function)
self.id = id # Assignment to object attribute
self.name = name # Assignment to object attribute
self.dept = dept # Assignment to object attribute
# Main:
s1 = Student(200201777, "Jane Fonda", "CS") # Create a Student object
print(s1) # automatically calls s1.__str__()
Object Methods
Classes can also contain methods.
Methods in classes are functions that belong to the objects of that class.
class Person:
perCount = 0 # Class Attribute. Number of Person objects
# Main:
p1 = Person("Jane", 1987, 56)
p1.greet() # Call an object method
p1.weight = 58 # Change an attribute
age = p1.getAge() # Call an object method to get age
print(p1.name, "is", age, "years old.") # Print name attribute and age
print(p1) # Print string representation of object
# Main:
cars = [] # List of Car objects, initially empty
cars.append(Car("07ABC124", "Renault", 2016)) # Create a Car obj and append to list
cars.append(Car("35KML24", "Audi", 2019)) # Create a Car obj and append to list
Pack:
This geometry manager organizes widgets in blocks before placing them in the parent widget.
• Places each widget below the previous one.
• pack(side = TOP), pack(side = LEFT), pack(side = RIGHT), pack(side = BOTTOM) can be used
for alignment.
• To make the widgets as wide as the parent widget, use the fill=X option.
Grid:
This geometry manager organizes widgets in a table-like structure in the parent widget.
• The widgets are placed in a matrix-like structure in rows and columns.
win1.mainloop()
with ...pack(fill=X)
# Grid
win1 = Tk() # Create window
win1.title("grid") # Set window name
#win1.geometry("300x88") # Set window size
win1.mainloop()
win1.mainloop()
Tkinter Widgets:
Widgets are elements in a window. The most frequently used widgets are:
Widget Description
Frame Frame widget is used as a container widget to organize other widgets.
Label Label widget is used to provide a single-line caption for other widgets. It can also
contain images.
To create a label widget: lbl1 = Label(win, text="Student Name:")
To get label text: str2 = lbl1["text"]
To change text in a label widget: lbl1["text"] = str1
Entry Entry widget is used to display a single-line text field for accepting values from a user.
To create an entry widget: ent1 = Entry(win, width=10)
To get string entered to entry widget: str1 = ent1.get()
To change text in an entry widget: ent1.insert(0, str1)
To clear contents of an entry widget: ent1.delete(0, END)
Text Text widget is used to display or get text in multiple lines.
To create a text widget: txt1 = Text(win, height=3, width=40)
To get contents of a text widget: str1 = txt1.get("0.0", END) # ......, tk.END)
To change text in a text widget: txt1.insert("0.0", contents)
To clear contents of a text widget: txt1.delete("0.0", END)
Combobox A combobox allows user to select one value in a list of values. In addition, it allows to
enter a custom value. It is in ttk in tkinter: from tkinter import ttk
To create a combobox: combo1 = ttk.Combobox(win, width=8)
To set values of a combobox: combo1["values"] = ("...", "...", "...", "...")
To get value from a combobox widget: current_value = combo1.get()
Button Button widget is used to display buttons in a window.
To create a button: btn1 = Button(win, text="Do ....", command=func1)
Canvas Canvas widget is used to display images or to draw shapes, such as lines, ovals,
polygons and rectangles, in your application.
Checkbutton Checkbutton widget is used to display a number of options as checkboxes. The user
can select multiple options at a time.
Listbox Listbox widget is used to provide a list of options to the user.
Menubutton Menubutton widget is used to display menus in an application.
Menu Menu widget is used to provide various commands to a user. These commands are
contained inside Menubutton.
Message Message widget is used to display multiline text fields for accepting values from a user.
Radiobutton Radiobutton widget is used to display a number of options as radio buttons. The user
can select only one option at a time.
Scrollbar Scrollbar widget is used to add scrolling capability to various widgets, such as list
boxes.
def save():
stuid = ent1.get().replace(";", "")
name = ent2.get().replace(";", ",")
dept = lst3.get()
address = txt1.get("1.0", END).replace(";", ",").replace("\n", " ")
if len(stuid) == 0 or len(name) == 0 or len(dept) == 0 or len(address) < 2:
lbl4["text"] = "Missing data."
return
line = stuid + ";" + name + ";" + dept + ";" + address + "\n";
file1 = open("stu.txt", "a") # append mode
file1.write(line) # append line to file
file1.close()
lbl4["text"] = "Student record is added to stu.txt"
# Main:
def main():
global ent1, ent2, lst3, txt1, lbl4
win = Tk() # Create window
win.title("Add record to file") # Set window name
Arial11 = ("Arial", 11, "normal") # Font tuple
# Run main
if __name__ == '__main__':
main()
References:
https://www.edureka.co/blog/tkinter-tutorial/ http://www.pythonlake.com/python/tkinter
https://www.python-course.eu/python_tkinter.php
https://realpython.com/python-gui-tkinter/
https://www.tutorialspoint.com/python/python_gui_programming.htm
Example:
import random
s = "abcdefgh12345678"
c = random.choice(s) # A random char from string s