Python Programming Workbook 2022-2023
Python Programming Workbook 2022-2023
2023
Workbook
COMPUTING FOR ENGINEERING
Workbook
Table of contents
IINTRODUCTION.......................................................................................................................2
IINTRODUCTION.....................................................................................................................32
WIDGETS 33
CPLACE THE WIDGETS IN THE WINDOW35
1
Workbook
Objectives
Introduction
Python is a general-purpose programming language that can be said to be
multiparadigm, as it supports object-oriented, imperative programming, and to a lesser extent
measure, functional programming. It is an interpreted language, uses dynamic typing and is
multiplatform. It is a good language to dive into the world of programming because of its
Simplicity, versatility, and speed of development, this is thanks to the fact that its syntax is very simple.
Another advantage is that it has an open source license. To write programs in Python not
It takes more than downloading the language that has its own IDLE (Integrated Development Environment)
Development and Learning Environment
Python). This IDLE has two windows: the Shell window and the editor window. Here
we can enter the statements and see directly the result that it provides us with
interpreter. To download Python you can go to the page [Link] In the
exercises will use version 3.6.5 or later.
In addition to Python's own IDLE, there are more comprehensive tools for writing the
programs, what is commonly known as IDE (Integrated Development Environment).
Some options are paid and others are free. For this introductory programming course,
Thonny has been chosen. It is an easy-to-use, simple, free, and cross-platform IDE (Windows, Linux)
y Mac). The page where you can download it and get more information is: [Link]
Classwork
On the Thonny download page itself, there is a short video that lasts about five minutes.
and that are sufficient for you to know the main elements of this IDE. Here only you
We are going to present the main windows and the most common options.
2
Exercise Notebook
Thonny Environment
a. Menu bar:
• File. Options to Create, Save, Open or Print programs.
• Edit
• View. Show/Hide windows, change font sizes, etc.
• Run
• Tools. Add packages, OpenShell, etc.
b. Most common options
• Create a new program, open a program, save, run, options
debug stop.
c. Current program code. It allows having more than one window open with different
programs.
d. Shell can execute the instructions and see the result of them.
e. Different windows where the variables window stands out, allowing you to see the value
of the program variables.
f. Work with objects.
The shell window will be used to write commands. Position yourself in the prompt and write the
following sentences:
3
Exercise Notebook
Play with language and perform common mathematical operations, strings can be used
characters like in the example.
Programs are saved in files with the .py extension and are opened to modify or test them.
It simply explains how they work. They are written in the code window, on the left side.
the corresponding numbers appear for each line of the program. In our example, the
the program has five lines.
To see the execution of the program it is necessary to save it, Thonny does it in a way
automatically before its execution, and if the program has not been saved, it asks for the name
of the same. To save a program, simply select the option Save from the File menu.
press the button on the bar In this case, we have named the program '[Link]', and in
the window screen shows the name reflected in the tab.
To run the current program, it is necessary to select the option 'Run current script' from the menu.
Crea tres variables de tipo entero y asígnales los siguientes valores: 5, 14, 37. Escribe las
following statements:
4
Exercise Notebook
• Two sentences that applying the operators +, *, (, and ), and without changing the order of the
numbers obtain the following results: 703 and 523.
• Use an operator that indicates if it is true that 14 is less than 37.
• Show how many exact times 5 fits into 14.
• Haz una sentencia que calcule el resto de dividir 14 entre 5, y súmalo a 37.
• Raise 14 to the fifth power.
• What type of data do we get when we apply a relational operator?
• Write an expression in which you mix two different types of operators and it is
the result you obtain is valid.
Buenos
"days". Write the following statements:
abc
sentences that allow us to know if:
Given the following values: a = 20, b = 10, c = 15 and d = 5. Perform the following calculations:
• (a + b) * c / d
• ((a + b) * c) / d
• (a + b) * (c / d)
• a + (b * c) / d
Check the result and comment on how precedence is resolved.
5
Workbook
Given two points in space, calculate the distance that separates them (assign the values)
directly). The points will be defined by their three coordinates x, y, z. The formula to calculate
the distance is shown below.
The distance between the points (2.0, 3.0, 4.0) and (5.0, 6.0, 7.0) is:
5.196152422706632
Write four valid expressions, where you can identify in each of them two or more of
three different types of data, and two or more different types of operators.
Familiarize yourself with the Debug to check how the variables change as you go
running a program.
Complementary 1.1. Perform the Introduction to Python exercises from the notebook.
solved exercises.
Complementary 1.2. Search the web for known applications using the language of
Python programming.
6
Exercise Notebook
Objectives
Statements: Classwork
Exercise 2.1. Calculate the distance between two points given by the user.
Ask the user for the values of two points in space and calculate the distance that separates them.
Points will be defined by their three coordinates x, y, z. The formula to calculate the distance is
the one shown below.
• The values of (x, y, z) will be requested from the user and will be of float type.
• The import of the math module will be used for the square root and exponentiation.
• The result will be displayed rounded to two digits and using format.
= 1(− 2+ )12− 2(+ 1− )22 ( )2
Example of the result:
7
Exercise Notebook
• Ask the user for a landline phone number and check that the number is valid. It is
valid if it has the correct size and all characters are numbers.
• Ask for the street name and check that all the characters that make it up are
letters and/or spaces. It must have at least one character that cannot be blank.
• Ask for the ID number and indicate if it is correct. It must have 9 characters, the first 8 of
they are numbers and the last one is an uppercase letter.
• Ask for the age as an integer value and check if it is in the range of 18 to 81
both included.
Create three integer variables and initialize their value to zero. Generate three random numbers in
the range 1-100 inclusive and assign them to the already created variables:
• Multiply the first value by the constant PI, round the result to the number
nearest higher integer
• Check if the second value is an even number.
• Subtract the second number from the third.
• Concatenate the value obtained in the first point with the absolute value obtained in
the previous point and display it on the screen.
8
Workbook
Complementary work
Supplementary 2.1. Complete the string exercises from the solved exercise notebook.
9
Workbook
Objectives
Develop a program that requests two integer numeric data from the user. Check that
they are integers and visualize as a result a message indicating if any of the data is
multiple of the other.
Give me an integer: 9
Give me another integer: 36
36 is a multiple of 9
Design a program that, based on the radius of a circle, allows the calculation of its diameter.
perimeter and area. For this, a menu of possible options will be presented to the user. If he chooses one
A different option than the ones presented will show an error message (the option may be in
uppercase or lowercase) and the option will be asked again. The result will be displayed with three
decimals, and the received value can be either integer or floating.
Sum the digits of a positive integer previously entered by the user. Think
two different ways to do it.
10
Workbook
The program that is presented below indicates that it prints the print statement every time it
execute, if it is executed. If you have doubts about how the program behaves, use the Debug
to see how the variables change: i, j, k.
i, j, k = 0, 0, 0
while i < 3:
while j < 3:
while k < 3:
print(i,j,k)
k += 1
j += 1
k=0
i += 1
j=0
The program will automatically generate a number between 1-100. The user will try to guess it.
number and will have 5 attempts for that. For each attempt by the user, the program will indicate whether the
The number is greater than or less than the generated one. The program will end when the 5 are met.
attempts or when the number is guessed.
At the end, the number of attempts used and which numbers have been shown will be displayed.
introduced.
Guess 50
The number you have to guess is greater.
Guess 75
The number you have to guess is greater.
Guess 90
The number you have to guess is greater.
Guess 95
The number you have to guess is smaller.
Guess 93
The number you have to guess is smaller.
Intentos intento1 50 intento2 75 intento3 90 intento4 95 intento5 93
Number 92
You have lost
Introduce two positive integers and print if they are friends. Two friend numbers are
two positive integers a and b such that the sum of the proper divisors of one is equal to the
another number and vice versa.
11
Exercise Notebook
Enter a positive integer (N), and generate N pairs of twin prime numbers (two
numbers are twin primes if, in addition to being prime numbers, the difference between them is
exactly two).
Enter a number: 4.
Result:
Pairs of numbers are: 3 and 5, 5 and 7, 11 and 13, 17 and 19.
Enter a positive integer. Check the following equality, visualizing each one
of the terms:
1 3 +2 3+ 3 +⋯
3
= 1+( 2 + 3+. . )2
Example of the result:
Enter a number: 5
Result: 225. Correct statement.
Verification:
Equality 1: 1 + 8 + 27 + 64 + 125 = 225
Equality 2: 15^2 = 225
12
Exercise Notebook
Objectives
Develop a program that asks the user how many additions they want to perform to
approach the value of e. Print the result of each iteration. Show the calculated term
and the value of the summation and the difference of this with the value of the constant e of Python.
13
Workbook
The user will be asked for any sentence and the program will display that same sentence, but
removing the vowels, and displaying at the end the total number of letters, vowels, and spaces
sentence given by the user.
Ask the user for a sentence and create a list with it. Display the words on the screen that
form the list. Ask the user for a letter and remove that letter from all the words in the list
showing the position of the word in the list and the position of the letter in the word. Show
how the list remains and count the number of letters deleted.
The program will feature two pre-loaded lists of names, each name represents a
player of a team
lisBALON_1 = ["JUAN","ANA","LUZ","TOM","RAÚL","SARA","LUIS","BO","RAFA"]
lisBALON_2 = ["PAM","CRUZ","ARON","GON","TATO","LOU", "JAVE", "TORO", "RAFA",
"CARRIE", "CARLA", "JUAN"]
14
Workbook
• List all players from both teams who have the following vowels
in the name: 'AEI'.
• List all players from both teams who have two or more vowels
equal in name.
• Show the players with repeated names.
Example of the result:
['JUAN', 'ANA', 'LUZ', 'TOM', 'RAÚL', 'SARA', 'LUIS', 'BO', 'RAFA', 'PAM',
'CRUZ', 'ARON', 'GON', 'TATO', 'LOU', 'JAVE', 'TORO', 'RAFA', 'CARRIE',
'CARLA', 'JUAN']
Vocales A E I
['JUAN', 'ANA', 'RAÚL', 'SARA', 'LUIS', 'RAFA', 'PAM', 'ARON', 'TATO', 'JAVE',
'RAFA', 'CARRIE', 'CARLA', 'JUAN']
Equal Vowels
['ANA', 'SARA', 'RAFA', 'TORO', 'RAFA', 'CARLA']
Repeated Names
['JUAN', 'RAFA']
The program will ask the user how many numbers they want to enter in the tuple. All of them will be requested.
the numbers are stored in the tuple. The maximum, the minimum, and the difference will be printed between
maximum and minimum and the average of all the given numbers.
Total elements 6
Número = 3
Número = 6
Número = 9
Número = 34
Número = 2
Número = 9
(3, 6, 9, 34, 2, 9) Máximo 34 mínimo 2 máximo-mínimo 32 media 10.5
The user will input all the results produced by any function and the program
it will detect all local maxima and count them. Once it has finished
enter all the data. The program will display the following calculations:
15
Workbook
Password: MBpd55*-
.
The user is asked for a sentence and the acronym of it is printed (the first letters of
each word). Do not include (of, from, and).
Check if the user enters a correct password. The password is considered correct
if it has at least 8 characters, uppercase letters, lowercase letters, numbers and no whitespace.
Otherwise, it must indicate an error.
16
Workbook
Calculate all the triangular numbers from 1 to the value indicated by the user. The formula
to calculate a triangular number is:
( + 1)
=
2
Example of the result:
Value of N ==> 10
1.0
3.0
T 3 = 6.0
10.0
15.0
T 6 = 21.0
28.0
T 8 = 36.0
45.0
55.0
The program must display on the screen a representation of the domino tiles.
standard.
The program will ask the user for a total of 10 values that must be ones or zeros. These values
they will represent a binary number. The program will mark an error if the value
the number that has been entered
It will be incorrectly interpreted in the program as 0. The conversion will be displayed on the screen.
the corresponding decimal and the complete binary number entered by the user.
17
Workbook
Complementary 4.4
It is possible to predict the future sales of a good based on historical data and estimates.
of marketing, etc., through the use of various techniques, for example, the moving average
weighted, where a weighting factor is assigned to each data point in the average (their sum must
It is common to apply a higher weighting factor (percentage) to the most recent data.
The formula is:
Where:
• Ask the user for the number of data points needed for the forecast. n.
• Request the data (Xt-1) and the weighting factor (Ci) for each data point.
• Check that the sum of the weighting factors of the data equals
100%. If this is not fulfilled, an error message will be sent as soon as it is detected.
Yes, the requested forecast is printed.
• Check for possible errors (data entry).
Example of a warehouse:
The warehouse has determined that the best forecast is determined with 4 data points and
using the following weighting factors (40%, 30%, 20%, and 10%). Determine the
forecast for month 5. The data is detailed in the following table:
18
Workbook
My 4 95000 40%
Give me n ==> 4
ventas del mes 1: 100000
a weighting of 100000.0 is 10
ventas del mes 2: 90000
A weighting of 90000.0 is 20
ventas del mes 3: 105000
a weighting of 105000.0 is 30
ventas del mes 4: 95000
A weighting of 95000.0 is 40
The forecast is 97500.0
Write a program in Python that asks for a string from the keyboard, enters the characters in
a list without repeating characters and print the final list, that is, the characters without repeating.
Repeatedly ask the user which character they want to remove from the list, remove it, and display.
the new list. The program will stop when the user inputs the character '*'.
Check if the NIF entered by a user is correct. A NIF is correct if it has 8 digits.
and letter. The last letter of the DNI is calculated from its numbers, the number is divided by 23 and
the rest is a number between 0 and 22. The letter corresponding to each number is in this
table
19
Exercise Notebook
aBcdE
1465
• aBcdEaBcdEaBcdEaBcdE14691469
The user will enter a text, and the program will show us the number of blank spaces.
what it has, the amount of uppercase letters, amount of lowercase letters, amount of
numbers and other types of characters that the entered text has.
Ask the user for their sentence and store it in a string variable. Separate the words using
as a reference the spaces between them (do not use Split). Search in the list for the word that has
more characters and remove it. Sort the list and print it in reverse.
20
Workbook
Objective
The data for the collection of 5 water pipes is recorded over the seven days of the week.
one of the machines of the factory. a two-dimensional matrix will be created in the main program
dimensions of the float data type of 5x7 that contains zeros in all its positions.
It must be:
Do the following:
• Create a matrix with fixed data that contains information about one in each row.
factory, in the order indicated in the previous list.
21
Workbook
• Add the necessary code to be able to add information about more factories in the
matrix.
• Calculate the total joint production.
• Calculate the total joint production without errors.
• Show a list of cities whose total production exceeds 500 units.
• Show which factory has the highest total production.
• Show the factory with the lowest percentage of defective units. Show
also the percentage rounded to two decimal places (use the function round(value,
num_decimals.
• Modify point 2 to avoid introducing repeated cities. In those cases, they
the error will be notified to the user and the rest of the information for that city will not be requested.
A Coruña->801
Total joint production: 2280
Total joint production without errors: 2202
Lowest % of errors: Vigo -> 3.15%
Ciudades con producción >=500: ['Vigo', 'A Coruña', 'Santiago']
Complementary work
Write two matrices of the same dimensions and calculate the resulting matrix from their sum.
Complementary 6.3.
4 1 2 4 1 2
3 3 2 → 9 1 9 63→
1 5 1 1 5 1
• Elemental operation: row addition. Given two row numbers, add to the second one.
the values of the first.
4 1 2 4 1 2
3 3 2 → 0 3 3 2→
2
1 5 1 5 6 3
22
Exercise Notebook
4 1 2 1 5 1
3 3 2 → 3 3 0 22→
1 5 1 4 1 2
23
Exercise Notebook
Objectives
• Create a function that asks the user for the time period (hours, minutes,
seconds). This function will receive as input parameter the message that is given to it.
show the user and the valid range of each value. The function will ask for the data
desired until it meets the range.
• Create a function that receives that time period and calculates the seconds.
• The main program will call the two functions mentioned above, the
the first will be called more than once to obtain all the data, and the second
it will calculate the total seconds. The result will be displayed on the screen in the
main program.
Example of the result:
Exercise 5.2. Calculate the total time of use of the electric bicycle and the cost
In the bicycle rental service "El Paseo" of the University La Grande, once the
The user registers for the service and has to indicate at the end of the month the number of times that
used the bicycle on campus and the time period hours:minutes:seconds that he/she took in
each route. The program will calculate the total number of seconds per route and the
will multiply by the cost. The cost is €0.001. Develop a program that:
• Ask the user how many times they have used the bicycle during the month.
24
Workbook
• For each time it has been used, obtain the period of time.
hours:minutes:seconds. Use the routines created in the previous exercise.
• Store the data in a list. Create a function that receives the seconds of each
time period and saved them in the list.
• Create a function that loops through the list and stores the data in a string.
seconds and cost of each route, as well as the total accumulated for both
seconds as costs.
• Show the result in the main program. This is where it will be declared.
list and the cost per second.
Example of the result:
The user will enter any two points (x1,y1) and (x2,y2) and will be able to perform different
operations: distance and midpoint.
For that:
• A function will be created that asks for a point and stores it in a variable of type
tuple.
• Create a function that receives the two points as input parameters and returns
the distance between both.
• Function that calculates the midpoint of the two input points.
• Function that prints the different options of the program (menu) on the screen.
• Function that reads the option chosen by the user and checks that it is within the range
desired, otherwise it will continue to ask for it (you can reuse the function of
exercise 1).
• In the main program, assemble the different function calls to
to obtain a functional program.
25
Exercise Notebook
Three numbers entered by the user will be sorted in ascending order. It will be implemented
a function that takes as parameters only two numbers and returns them sorted. The rest of
sentences will be in the main program.
dame un número: 5
give me a number: 3
dame un número: 1
ordered ==> 1 3 5
Create a module with the function askVal. This function receives a string, a minimum value
and one maximum. The function checks that the string can be converted to numeric and that it
finds within the stipulated range. This function returns two values true or false (if value is
suitable or not) and the corresponding numerical value. Use this module in the exercises
importing it.
Supplementary work
In exercise 2, restructure the program to store tuples that contain the three data points.
of the time period.
In addition:
• Implement a function that goes through the period list and creates another list
storing the total seconds of duration of the period.
26
Exercise Notebook
Use the program developed in exercise 4. Ask the user for a number of points.
any. Store all the given points in a list. Increase the following options to
menu
27
Exercise Notebook
• What is done to indicate that the player's roll is valid (what functions are responsible for it?
and how they do it).
"""
Three in a row
"""
import random
board=[i for i in range(0,9)]
player
#Corner, Center and others
moves=((1,7,3,9),(5,),(2,4,6,8))
Winning combinations
winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
Table
tab=range(1,10)
def print_board():
x=1
for i in board:
|
if x%3 == 0:
end
if i != 1:
end+='---------\n'
char
if i in ('X', 'O'):
char=i
x += 1
print(char,end=end)
def select_char():
chars=('X','O')
if [Link](0,1) == 0:
return chars[::-1]
return chars
def can_move(board, player, move):
if move in tab and brd[move-1] == move-1:
return True
return False
def can_win(brd, player, move):
places=[]
x=0
for i in brd:
if i == player: [Link](x);
x+=1
win=True
for tup in winners:
win=True
for ix in tup:
if brd[ix] != player:
win=False
break
if win == True:
break
return win
def make_move(board, player, move, undo=False):
if can_move(brd, player, move):
brd[move-1] = player
win=can_win(brd, player, move)
if undo:
brd[move-1] = move-1
return (True, win)
return (False, False)
28
Workbook
def computer_move():
move=-1
for i in range(1,10):
if make_move(board, computer, i, True)[1]:
i
break
if move == -1:
for i in range(1,10):
if make_move(board, player, i, True)[1]:
i
break
if move == -1:
for tup in moves:
for mv in tup:
if move == -1 and can_move(board, computer, mv):
mv
break
return make_move(board, computer, move)
def space_exist():
return [Link]('X') + [Link]('O') != 9
player
print('The player is [%s] and the computer is [%s]' % (player, computer))
%%% Tie ! %%%
while space_exist():
print_board()
print('#Tira ! [1-9] : ', end='')
move = int(input())
moved
if not moved:
>> Incorrect number! Try again!
continue
if won:
*** Congratulations! YOU WON! ***
break
elif computer_move()[1]:
=== YOU LOST! ===
break;
print_board()
print(result)
29
Exercise Book
Objective
Statements: Classwork
Let's suppose we have a file called [Link] in which the data is stored
data from a laboratory from 8:00 in the morning until 8:00 at night of a day, the data
They are taken on the hour and at the half hour continuously. The data that is collected
son
Starting from the data in the previous file, a software application is desired that displays:
30
Workbook
hour:max_persons
if counter == 0:
minimum_temperature=float(temperature)
if float(temperature) < minimumtemperature:
min_temperature=float(temperature)
totaltemperature += float(temperature)
counter += 1
Average number of people in the laboratory:
Maximum number of people in the laboratory:
at
Lowest temperature in the lab:
Average temperature in the laboratory:
str(totaltemperature/counter))
[Link]()
• Request the file name. Then request the data to save the
information of the type of the example in the cited file.
• Run the example program on the file we have saved and observe
if it gives the correct results.
• Modify the program from point 1 to ask the user if they want to create a
new data file or add data to an existing one. Make sure not to delete
by mistake an existing one and that there is one that you want to add. Next,
run the example program again and check if the obtained results are
correct
• Resolve using functions.
if [Link](file):
the file exists
Complementary work
Complementary 7.1. Carry out the proposed exercises in the solved exercise notebook.
corresponding to the file section.
31
Workout Notebook
Objectives:
Introduction
Python implements graphical user interfaces (GUI Graphics User Interfaces) using
libraries, one of the most used is the tkinter library which is included in Python as a
standard package, so there is no need to install anything to use it. tkinter is the acronym
for Tk interface and allows generating interfaces in a fast and simple way.
The tkinter module is imported just like the other modules using the import statement.
1. Tk(): creates the main window, it is the surface (or container) on which the
place the components (widgets).
• title(): window title
• geometry("WxH±X±Y"): dimensions and offset
• iconbitmap("[Link]"): change the icon
• quit ends the main loop
• destroy() : closes the window
2. mainloop(): is used to run the application. It is an infinite loop that receives and
respond to events while the main window is open.
32
Workbook
In the third step, we have to decide which widgets we want to be part of our
window, and give them the appearance and location we want in it. Each widget has
own attributes.
Widgets
They are small programs used to add functions, simplify, or automate.
those actions that are carried out frequently. To give content and form to our
In the window, we include widgets. We will list the widgets that we will use in the exercise and some of
its attributes.
Label is translated as tag and refers to a box where text can be displayed or
images. The image or the code shown may be updated during execution.
Label(window, option=value)
image
Entry(window, option=value)
Buttons: they can contain text or images and can be associated with functions or methods. When clicked
Clicking on them, tkinter automatically calls the associated function.
Button(window, option=value)
image
RadioButton: Allows the user to choose a single option from the proposed set of options.
A method can be associated that will execute when the user selects the option. Each group
The radio buttons must be associated with the same variable; when one of them is selected,
the value of the associated variable changes.
CheckButton: Select one or multiple options from the proposed set. It has two values.
possible: selected and not selected.
33
Workbook
fr=Frame(window, option=value)
title
PhotoImage class: this class is used to display images in widgets, such as labels,
buttons, canvas, and text type. Works with GIF and PGM/PPM.
image = PhotoImage(file=file)
Configure
The appearance of the widgets can be defined from their instantiation or using configure to
change the value of one or more attributes of the widget.
[Link](option=value)
34
Exercise Notebook
Example 1. Start
Execution result
35
Workbook
Execution result
Change the interface of example 2 to achieve the following result, using grid.
36
Exercise Workbook
Design your own interface to store your contacts. The interface should contain the following
información: foto de la persona, nombre, apellidos, edad, sexo, teléfono, correo electrónico.
You can use the grid or pack to place the widgets.
37
Workbook
Objectives
Control variables
They are special objects associated with some widgets (text, radiobutton, checkbutton, etc.).
to store their values and facilitate their availability in other parts of the program. If the
When a variable changes, the linked widget also changes and vice versa. Tkinter has four types of
variables and have three methods: set(), get() and trace. The first sets the value, the
the second consults and the third monitors the changes of the variables. The types of variables
son
The method trace() is used to "detect" when a variable is read, changes value or is
erased
[Link](type, function)
The type indicates what you want to check: 'r' for reading a variable, 'w' for writing a variable, and 'u'
deleted. The second argument indicates the function that will be called when the event occurs
that he is controlling.
We will use the previous application (Part I) and add two types of controls: radio button
check button, with its respective control variables. A function will be created that prints that
options are selected to show how the change in selections affects the
control variables.
The program will check that the units have an integer value and that the price has
a floating point value. A label will be added to display the result of the multiplication
of the units by the price and another label where error messages will be displayed in case
if any. Every time the value of units or the price is modified by the user, it
38
Exercise Notebook
it will first check that the value is of the correct type, if it is, the total is calculated and displayed
in the corresponding label, otherwise, the error message is displayed. To do this, it
they will also create control variables for the widgets: price and units, the
trace method to know when the value changes.
When the user presses the Accept button, it will be checked that the fields are different from
white (Name, Characteristics, and Units), if any are blank, the message will be sent
error in the label created for it, if they have a value, it will be displayed: READY!!!. The code would be:
Execution result
#functions
def check(*args): #function declaration with parameters
defect
try:
[Link](" ") #clear the message label
uni=int([Link]()) #Get the values of the variables and
convert them
prec=float([Link]()) #to the data type
[Link](round(float(prec*uni),2)) #Calculate the final price and
round it
except:
[Link]("ERROR") #Show the error
[Link](0) # Leave 0 in the total
Show why options are checked, each time the user selects
a
def Print():
print("Used " + str([Link]())) #Indicates which option is checked
print("Batteries " + str([Link]())) #Shows true or false if they are present
marked batteries
39
Workbook
def ChangeColors(event):
colores=["azure","cadet blue","medium sea
green","goldenrod","salmon","maroon","PeachPuff3","SteelBlue3"]
colorM=len(colors)
global colorN
if colorN==colorM-1:
colorN=0
else:
colorN+=1
[Link](bg=colors[colorN])
40
Workbook
[Link]('<Button-1>', ChangeColors)
[Link]()
[Link]()
Statements: Classwork
You will codify the desired behavior in the agenda you have designed in the exercise.
introduction.
• Every time the age field is modified, check that the new data is of a type.
of whole date otherwise, send an error message.
• Check the phone number must have 9 characters and all must
numeric series.
• Do the same with the email field, to indicate that the field is
Correct, it just needs to have the '@
• Add three buttons: Clear, Accept, Exit.
• The clear button clears all fields.
• In the Accept button, check that all fields have information.
41
Workbook
x = vo*cos(a)*t
y = vo*sin(a)*t - 0.5*g*t**2
Tkinter applications are within a loop, the mainloop, and events are occurrences.
that are communicated to him and have different origins: pressing the mouse, changing the size of
a widget, pressing keys, etc. (many of the events are produced by the user). Python
register the event and allows us to link it to a widget and execute a function to respond to
said event. To link the event:
[Link](event, handler)
If the indicated event is recorded in the widget, a call is made to the handler and therefore to
the indicated function.
Some Events
42
Exercise Notebook
It is a standard Python object that has attributes describing the event that has occurred.
produced. Some attributes of the event are:
Every time the user clicks on the image, the background color of the window will change.
It will create a list of random colors, each time the user clicks, the next one will be selected.
color. The code we need to include is:
def ChangeColors(event):
colores=["azure","cadet blue","medium sea
green","goldenrod","salmon","maroon","PeachPuff3","SteelBlue3"]
colorM=len(colors)
global colorN
if colorN == colorM - 1:
colorN=0
else:
colorN+=1
[Link](bg=colors[colorN])
43