0% found this document useful (0 votes)
10 views44 pages

Python Programming Workbook 2022-2023

This document presents a workbook for learning Python. It contains 8 exercises that cover topics such as: introduction to the Python and Thonny environment, basic data types, operators, functions, modules, graphical interfaces, and more. The aim is to familiarize students with the Python programming language through solving a series of problems and practical exercises of increasing complexity.

Translated by

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

Python Programming Workbook 2022-2023

This document presents a workbook for learning Python. It contains 8 exercises that cover topics such as: introduction to the Python and Thonny environment, basic data types, operators, functions, modules, graphical interfaces, and more. The aim is to familiarize students with the Python programming language through solving a series of problems and practical exercises of increasing complexity.

Translated by

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

2022

2023

Workbook
COMPUTING FOR ENGINEERING
Workbook

Table of contents

EXERCISE 1. ENVIRONMENT AND INTRODUCTION TO PYTHON: FIRST STEPS...............................2

IINTRODUCTION.......................................................................................................................2

EXERCISE 2. INPUT-OUTPUT AND PREDEFINED FUNCTIONSS ................................................7

EXERCISE 3. CONTROL STATEMENTS I AND EXCEPTION HANDLING.................................10

EXERCISE 4. SEQUENCES: LISTS-TUPLES-STRINGS. CONTROL STRUCTURES II ...........13

EXERCISE 5. MATRICES. LIST OF LISTS............................................................................21

EXERCISE 6. FUNCTIONS AND MODULES................................................................................24

EXERCISE 7. PERSISTENCE: FILES ...............................................................................30

EXERCISE 8. TKINTER. GRAPHICAL USER INTERFACES. PART I. INTRODUCTION .................32

IINTRODUCTION.....................................................................................................................32
WIDGETS 33
CPLACE THE WIDGETS IN THE WINDOW35

EXERCISE 8. GRAPHICAL USER INTERFACES. PART II.................................................38

1
Workbook

Exercise 1. Environment and Introduction to Python: first steps

Objectives

• Manage the Python interpreter.


• Know Thonny (IDE). Create, open programs and run them.
• Working with Python's basic data types and performing simple operations
with the same ones.
• First programs in Python and comment on them.
• Familiarize yourself with Debug.

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

Familiarize yourself with Thonny

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

Main elements of the 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.

Write statements directly

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.

Create a program and run a program

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.

Run, press the F5 key or click the button .


The result of the execution can be seen in the shell, in the variables window we can see the
variables and their values as a result of the program execution. The errors that
could also exist would be displayed in the Shell window.

Exercise 1.1. Variables

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.

Exercise 1.2. Strings I

Buenos
"days". Write the following statements:

• By applying the appropriate operators, the result is Good morning


• GoodGoodGoodmorning.
• Print a letter from variable 1 on each line.
• Print each letter of variable 2 on a new line but starting from the last.
until the first.

Exercise 1.3. Strings II

abc
sentences that allow us to know if:

• The two variables are equal.


• The first variable is smaller than the second variable.
• The second variable is less than the first.

Exercise 1.4. Comments

Comment on the previous programs using the different types of comments.

Exercise 1.5. Precedence

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.

Example of the result:

• The value of (a + b) * c / d is 90.0


• The value of ((a + b) * c) / d is 90.0

5
Workbook

• The value of (a + b) * (c / d) is 90.0


• The value of a + (b * c) / d is 50.0

Exercise 1.6. Calculate the distance between two points

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.

= 1(− 2+ )12− 2(+ 1− )22 ( )2


Example of the result:

The distance between the points (2.0, 3.0, 4.0) and (5.0, 6.0, 7.0) is:
5.196152422706632

Exercise 1.7. List

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.

Exercise 1.8. Debug

Familiarize yourself with the Debug to check how the variables change as you go
running a program.

Statements: Complementary work

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

Exercise 2. Input-Output and predefined Functions

Objectives

• Data input and output.


• Invoke predefined functions.
• Use methods of the str class.
• Import modules.

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:

Give me the coordinate X1 5.2


Give me the coordinate Y1 3.8
Give me the coordinate Z1 2
Give me the coordinate X2 6.1
Give me the coordinate Y2 7.8
Give me the coordinate Z2 1
The distance between the points (5.2,3.8,2.0) and (6.1,7.8,1.0) is 4.22

Exercise 2.2. Names


Ask the user for their first name and their two last names, store them in three variables. Make the
following sentences:

• show first and last name. all in lowercase.


• SHOW FIRST LAST NAME, SECOND LAST NAME, AND NAME. ALL IN UPPERCASE.
• Show first surname, second surname, and name. In uppercase the first one.
letter of each word.
Example of the result:

Give me the name Juan


Give me a good last name 1
Give me the surname 2 montes
Juan Bueno Montes
GOOD MOUNTAINS JUAN
Good Mountains Juan

7
Exercise Notebook

Exercise 2.3. Changing strings

it was the best of times, it was the worst of times


it was the age of wisdom, it was the age of foolishness, it was the epoch of belief,
it was the epoch of disbelief, it was the season of light, it was the season of darkness, it was the
spring of hope, it was the winter of despair. Carry out the following
modifications to the phrase:

• Change the word times to moments throughout the entire phrase.


• Change the word age in the entire sentence obtained in the previous section to
time.
• Show the number of characters that the new phrase has.
• Show the position of the word hope in the sentence.
original.
• Indicate if the original phrase is longer than the new phrase.
• Show the first 20 characters of the new phrase.
• Change the phrase to present by changing the verb tense from was to is.
• Capitalize The First Letter Of Each Word In The New Sentence.
• Remove all whitespace characters from the original sentence.

Exercise 2.4. Checks

Make the following checks:

• 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.

Exercise 2.5. Random

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

Exercise 3. Control Statements I and Exception Handling

Objectives

• Use If/Else conditional control statements.


• Apply iterative statements. While
• Avoid exceptions: try/except

Statements: Class work

Exercise 3.1. Multiples

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.

Example of the result:

Give me an integer: 9
Give me another integer: 36
36 is a multiple of 9

Exercise 3.2. Calculations for a circle

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.

Example of the result:

Give me the radius: 42.5


Possible calculations
a) Calculate the diameter
b) Calculate the perimeter
c) Calculate the area
d) Exit
Option ====> b
The perimeter is 267.035
must be greater than 1.

Exercise 3.3. Sum of digits

Sum the digits of a positive integer previously entered by the user. Think
two different ways to do it.

Example of the result:

Give me a number: 91.


Resultado: 10.
Give me a number: 23.
Resultado: 5.

10
Workbook

Exercise 3.4. What does the print statement output

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

Exercise 3.5. Guess a number

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.

Example of the result:

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

Statements: Complementary work

Complementary 3.1. Friendly numbers

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.

Example of the result:

Enter the first number: 220.


Enter the second number: 284.
The numbers 220 and 284 are friends.
Enter the first number: 5.
Enter the second number: 6.
The numbers 5 and 6 are not friends.

11
Exercise Notebook

Complementary 3.2. Generate a pair of prime numbers.

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).

Example of the result:

Enter a number: 4.
Result:
Pairs of numbers are: 3 and 5, 5 and 7, 11 and 13, 17 and 19.

Complementary 3.3. Arithmetic progression.

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

Complementary 3.4. Calculation of the perfect number

Check if an entered number is a perfect number. A number is perfect if the sum of


its divisors equal the number.

Example of the result:

Enter the number: 28


28 is a perfect number. Its divisors are: 1 + 2 + 4 + 7 + 14.
Enter the number: 5.
5 is not a perfect number.

12
Exercise Notebook

Exercise 4. Sequences: Lists-Tuples-Strings. Structures of


Control II

Objectives

• Deepen the work with sequences: strings, lists, and tuples.


• Add, insert, and delete elements.
• Use the different methods that exist for sequence manipulation.
• Handle one of the most commonly used control structures: for.

Statements: Class work

Exercise 4.1. Approximate the value of e


The value of e can be approximated with the following series:

1
=
!
g=0

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.

Example of the result:

Indicate the number of repetitions: 12


N= 0 es 1.0 sumatorio 1.0 diferencia 1.718281828459045
N= 1 es 1.0 sumatorio 2.0 diferencia 0.7182818284590451
N= 2 es 0.5 sumatorio 2.5 diferencia 0.2182818284590451
N= 3 es 0.16666666666666666 sumatorio 2.6666666666666665 diferencia
0.05161516179237857
N= 4 es 0.041666666666666664 sumatorio 2.708333333333333 diferencia
0.009948495125712054
N= 5 es 0.008333333333333333 sumatorio 2.7166666666666663 diferencia
0.0016151617923787498
N= 6 es 0.001388888888888889 sumatorio 2.7180555555555554 diferencia
0.0002262729034896438
N= 7 es 0.0001984126984126984 sumatorio 2.7182539682539684 diferencia
0.000027860205076724043
N= 8 es 2.48015873015873e-05 sumatorio 2.71827876984127 diferencia
3.0586177750535626e-06
N= 9 es 2.7557319223985893e-06 sumatorio 2.7182815255731922 diferencia
3.0288585284310443e-07
N= 10 es 2.755731922398589e-07 sumatorio 2.7182818011463845 diferencia
2.7312660577649694e-08
N= 11 es 2.505210838544172e-08 sumatorio 2.718281826198493 diferencia
2.260552189881082e-09
Note: Use the format function and import the constant e and factorial.

13
Workbook

Exercise 4.2. Print without vowels

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.

Example of the result:

this is a test to see how it works


program
This is a problem for the program.
Número de letras = 54 Número de vocales = 21 y Espacios = 9

Exercise 4.3: Remove letter from a word

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.

Example of the result:

Thursday has very interesting advantages that other days do not.


they do not have

Thursday has very interesting advantages that others


'días', 'no', 'tienen']
Give me the letter to remove => e
From the word 1-the, it is removed at position 1
From the word 2-Thursday, the letter in position 3 is removed.
From the word 2-Thursday, the character at position 5 is removed.
From the word 3-has, the position 3 is removed
From the word 3-has, it is removed at position 5.
From the word 4-advantages, it is removed at position 2.
From the word 6-interesting, the character at position 4 is removed.
From the word 6-interesting, the letter in position 6 is removed.
From the word 6-interesting, it is removed at position 11.
From the word 7-what, the position 3 is eliminated.
From the word 11-they have, the letter in position 3 is removed.
From the word 11-they have, the position 5 is removed.
Final List
['l', 'juvs', 'tin', 'vntajas', 'muy', 'intrsants', 'qu', 'otros', 'días',
'no', 'tinn']
Characters removed 12
Note: Use enumerate.

Exercise 4.4. Teams

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

The program should:

• 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']

Exercise 4.5. Calculations with tuples

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.

Example of the result:

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

Exercise 4.6. Local maxima of a function

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:

• The sum of all the entered data.


• The average of all the data entered.
• The sum of all the data divided by the number of maxima found.
• Avoid possible data entry errors and division by zero.

15
Workbook

Example of the result:

Number of points of the function == > 10


value of the function at point 1 => 2.0
value of the function at point 2 => 1.5
valor de la función en el punto 3 => 3.5
valor de la función en el punto 4 => 2.1
The value 3.5 is a local maximum.
value of the function at point 5 => 6.7
valor de la función en el punto 6 => 5.8
The value 6.7 is a local maximum
valor de la función en el punto 7 => 0.1
valor de la función en el punto 8 => 4.7
value of the function at the point 9 => 2.0
The value 4.7 is a local maximum
valor de la función en el punto 10 => 3.5

Total sum 31.900000000000002, Local maxima 3,


Promedio 3.1900000000000004, Suma/máximos 10.633333333333335

Exercise 4.7. Password Generator

Write a program in Python that generates random passwords of 8 characters.


characters must be uppercase letters A-Z, 2 characters must be lowercase letters a-z, 2 characters
They must be digits 0-9 and the last two special characters (!, ?, *, #, =, -, ), ç). Check the code
ASCII.

Password: MBpd55*-
.

Exercise 4.8. Create acronyms

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).

Consumers and Users Association of Spain


ACUE

Exercise 4.9. Verify a password

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.

Example of the result:

Enter the password: JJPR5


Invalid password.
Enter the password: Jjrt5iklu
Valid password.
Statements: Complementary work

16
Workbook

Statements: Complementary work

Complementary 4.1. Generate triangular numbers

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

Complementary 4.2. Print the domino game pieces

The program must display on the screen a representation of the domino tiles.
standard.

Example of the result:

0|0 ; 0|* ; 0|** ; 0|*** ; 0|**** ; 0|***** ; 0|****** ;


*|* ; *|** ; *|*** ; *|**** ; *|***** ; *|****** ;
**|** ; **|*** ; **|**** ; **|***** ; **|****** ;
***|*** ; ***|**** ; ***|***** ; ***|****** ;
****|**** ; ****|***** ; ****|****** ;
*****|***** ; *****|****** ;
******|****** ;

Complementary 4.3. Convert a binary number to decimal

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

Example of the result:

Give me a binary number 9 = 0


Give me an 8-bit binary number = 0
Give me a binary number 7 = 1
Give me a binary number 6 = a
The number is not correct
Give me a binary number 5 = 0
0001
Give me a binary number 3 = 1
Give me a binary number 2 = 0
Give me a binary number 1 = 1
Give me a binary number 0 = 1
The result of converting the number 0010011011 is 155
Note: Do not use the bin function.

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:

• ^: Average sales in units in the period t


• Ci: Weighting factor
• Xt-1: Actual sales or demands in units from the periods prior to t
• n: Number of data
Make a program that:

• 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

Period Sales(units) Weighting = (100000 * 0.1) + (90000 * 0.2) + (105000 * 0.3)


+
Month 1 100000 10%
(95000 *0,4)
My 2 90000 20%

Month 3 105000 30% Month 5 = 97,500 units

My 4 95000 40%

Example of the result:

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

Supplementary 4.5. Create a list

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 '*'.

Example of the result:

Give me a string: this is a test of any string to see how


the program works
this is a test
'i', 'v', 'm', 'j', 'g']
Character to remove or (*)
est le bonheur qui en parle
'v', 'm', 'j', 'g']
Character to remove or (*): g
est la prudence
'v', 'm', 'j']
Character to remove or (*): *
es: [‘MMM’, 12, 23, 45, 98]

Complementary 4.6. Verify NIF

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

Complementary 4.7. Achieve a chain

The program has these variables:

aBcdE

1465

Get the result you see on the screen in a few statements:

• aBcdEaBcdEaBcdEaBcdE14691469

Complementary 4.8. Types of characters

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.

Example of the result:

Calculate the prime number of 5


Number of spaces: 5
Number of digits: 1
Number of uppercase letters: 1
Number of lowercase letters, 21
Other characters: 0

Complementary 4.9. Word list

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.

Example of the result:

Give me a sentence: this sentence is random and contains several words.


['esta', 'frase', 'es', 'aleatoria', 'y', 'contiene', 'varias', 'palabras']
random element: list ['this', 'sentence', 'is', 'and', 'contains', 'several',
words
['contiene', 'es', 'esta', 'frase', 'palabras', 'varias', 'y']
this sentence contains various words y

20
Workbook

Exercise 5. Matrices. List of lists

Objective

• Create, modify, and iterate through matrices.


• Know the main functions of arrays: len, append, insert, and pop.
• Implement typical matrix algorithms.

Statements: Class work

Exercise 6.1. Pipes

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:

• Fill the matrix with random floating-point numbers ranging from


[150.52 to 321.19]. All elements of the matrix are rounded to have
only two decimals.
• Create a list with the sum of the total liters collected from each of the
five pipes.
• Create a list with the sum of the totals of the liters collected each day.
• Find the maximum collection value of all the data.
• Calculate how many liters of water the machine receives.

Exercise 6.2. Calculations and searches on matrices

A refrigerator manufacturing company has several factories, of which we have the


next information:

• City where the factory is located.


• Number of units manufactured last year.
• Number of defective units manufactured last year.
• Cost per unit of each refrigerator manufactured (in euros).

City Total production Defective Unit cost (€)


Vigo 731 23 3498.54
Lugo 238 12 3823.35
A Coruña 801 26 3324.12
Santiago 510 17 3325.89

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.

Result with the data from the previous table:

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

Complementary 6.1. Sum of matrices

Write two matrices of the same dimensions and calculate the resulting matrix from their sum.

Complementary 6.2. Product of matrices


Write two matrices and calculate the resulting matrix of their product. It must be taken into account that
The number of columns of the first matrix must match the number of rows of the second.

Complementary 6.3.

• Elementary operation: multiply a row by a scalar. Given a scalar and a


row number, multiply the values of this by the scalar.

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

• Elementary operation: Swapping two rows. Given two row numbers,


swap the values of both.

22
Exercise Notebook

4 1 2 1 5 1
3 3 2 → 3 3 0 22→
1 5 1 4 1 2

• Using the previous elementary operations, calculate the determinant by the


Gauss method.
In[Link]
a reminder of how to do it.

23
Exercise Notebook

Exercise 6. Functions and Modules

Objectives

• Identify the most appropriate functions to divide a program.


• Implement the identified functions optimally.
• Determine the parameters that the function should receive to achieve its objective
and the return values if necessary.
• Understand and know how to use variables in programs: global and local.
• Import a custom module.
• Create an executable using PyInstaller.

Statements: Class work

Exercise 5.1. Calculate total seconds

Calculate the seconds of a period of time expressed as hours:minutes:seconds. In the


hours will be accepted in a range of [0-23], and minutes and seconds [0-59]. For this:

• 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:

Seconds converter program


Hours 25
Hours 25
24 hours
Hours 23
Minutes 60
Minutes 59
Seconds 0
The total seconds are 86340

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:

Seconds converter program


Number of times 3 was used
0 Hours 1
0 Minutes 1
0 Seconds 1
1 Hour 2
1 Minute 2
1 Seconds 2
2 Hours 3
2 Minutes 3
2 Seconds 3
0 seconds = 3661 = 3.661
1 second = 7322 = 7.322
2 seconds = 10983 = 10.983

Seconds Total 21966 = 21.966

Exercise 5.3. Operations with points (x,y)

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

Example of the result:

Working with two points


Request points
2. Midpoint
3. Distance
4. Exit
Option: 1
Give me X 4
Give me Y 1
Give me X 5
Give me Y 7
(4,1)(5,7)
Work with two points
Ask for points
2. Midpoint
3. Distance
4. Exit
Option: 2
The midpoint is => (4.5, 4.0)
Note: You can implement other routines to achieve the same result.

Exercise 5.4. Sort three numbers

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.

Example of the result:

dame un número: 5
give me a number: 3
dame un número: 1
ordered ==> 1 3 5

Exercise 5.5. Create the executable of the program from exercise 4

Exercise 5.6. Create a module

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

Complementary 5.1. Calculate the total time of electric bicycle use

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

• Create a function that sorts the two lists in ascending order.


• Create a function that sums all the elements of the total seconds list.
• Display on screen the list where the time period is stored,
seconds of each period and the total seconds.
Example of the result:

Seconds converter program


Number of times 3 was used
0 Hours 2
0 Minutes 20
0 Seconds 15
1 Hour 1
1 Minute 12
1 Seconds 33
2 Hours 1
2 Minutes 9
2 Seconds 45
((1, 9, 45), 4185)
((1, 12, 33), 4353)
((2, 20, 15), 8415)
Total seconds 16953
Note. You can use the functions sort, zip, etc.

Complementary 5.2. Working with points

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

• Calculate the distances between each pair of points given consecutively.


• Calculate the midpoint between each pair of consecutive points.
• Show the greatest distance.
Example of the result:

Work with two points


Request points
2. Show
3. Exit
Option: 2
((2, 2), 0, 0)
((4, 5), 3.605551275463989, (3.0, 3.5))
((7, 5), 3.0, (5.5, 5.0))
((9, 12), 7.280109889280518, (8.0, 8.5))
The greatest distance is 7.280109889280518

Complementary 5.3. Three in a row


Do you have the complete code for the game Three in a row? Copy it and check that it works.
Document the input parameters that each of the game's functions receives, and the
values that it returns, briefly summarize what each of them does. In addition,
answer the following:

• Detail what the function called: computer_move() does.


• How is it decided which character represents the user and which represents the computer (what function)?

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

Exercise 7: Persistence: Files

Objective

• Creation and manipulation of data in a file.


• Creation and manipulation of data with sqlite 3.

Statements: Classwork

Exercise 7.1. File

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

• Time in hours and minutes format as integers.


• Atmospheric pressure in millibars in the form of an integer without decimals.
• Temperature in degrees Celsius in the form of a number with 1 decimal.
• Relative humidity in percentage in the form of a number with 2 decimals.
• Number of people in the laboratory.
• As an example of a data from the file it could be:
8;30;976;17.1;68.35;9

Starting from the data in the previous file, a software application is desired that displays:

• What has been the average number of people in the laboratory?


• What has been the maximum number of people in the laboratory?
• At what time was the highest number of people recorded in the laboratory?
• What has been the lowest temperature recorded in the laboratory?
• What has been the average temperature in the laboratory?

Below is the application code that fulfills the functionalities


previously described:
file=open("c:/tmp/[Link]", "r")
totalpersonas=0
contador=0
máximodepersonas=0
totaltemperatura=0
for line in file:
list=[Link](";")
list[0]
list[1]
pressure
temperature=float(list[3])
humidity = float(lista[4])
people=float(list[5])
totalpeople += float(people)
if float(people) > maximum_of_people:
maximum_of_people=float(people)

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]()

A program is requested to be created that:

• 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.

To know the current working directory we can include:


import [Link]
[Link]()
To check if the file exists:

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

Exercise 8. tkinter. GUI Graphic Interfaces. Part I. Introduction

Objectives:

• Management and positioning of some widgets.


• Use of the most common attributes.

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.

Steps to create an application with tkinter:

1. Import the tkinter module


2. Create the main window
3. Add the necessary widgets to the window
4. Include triggers in the widgets (respond to events)
In this exercise, we will focus on the first three steps, the events, and how to respond to them.
we will see it in the second part.

The tkinter module is imported just like the other modules using the import statement.

from tkinter import *


import tkinter as tk
The two previous methods do the same, but it is very common to see the second one where it
rename tkinter as tk.
To initialize tkinter, we need to create the main window (the one that contains all the widgets)
and keep the program running. The two methods we need to include are:

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

Allows both showing information to the user and obtaining it.

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.

opt= Radiobutton(window, variable=v, value=1,… option=value)


control variable it is associated with

CheckButton: Select one or multiple options from the proposed set. It has two values.
possible: selected and not selected.

CheckButton(window, variable=v, option=value)


control variable to which it is associated

Frame: acts as a container for widgets to create a logical grouping.

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)

Common attributes that apply to almost all widgets

• bd: width of the warehouse.

• bg: background color.


• call a function.
• font: text source. What we can indicate about the source is:
ofamily: nombre: Arial, Courier, Comic Sans MS, Fixedsys, MS Sans Serif,
MS Serif, Symbol, System, Times and Verdana.
size
NORMAL or BOLD
slant: NORMAL or ITALIC
1(underline) or 0(not underline)
1 (strike through) or 0 (no strike through)
• text color
• image: image that wants to be shown.
• width: set width.
• set height.
• text that shows the label
• justify: justifies text. Accepts the following parameters: LEFT, RIGHT, and CENTER.
• compound: use text and images at the same time: BOTTOM, LEFT, RIGHT and
TOP.
• pady, padx, ipady, ipadx: specify (in pixels) the external and internal margins
of an element.

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

Place the widgets in the window


Tkinter has three classes to manage the position of widgets. We will focus on
the first two:
1. pack(fill=Y, expand=1): organizes the widgets into blocks.
• fill: so that the widget occupies all the space assigned to it. It can expand
X, Y and BOTH (both directions).
• indicates to allocate the extra space to the widget if expand has a value
different from 0.
• Indicate on which side of the father it is displayed: TOP (default), BOTTOM
LEFT or RIGHT.
2. grid(): widgets are arranged like in a table divided into rows and columns. Each
cell contains a widget that is centered. It starts at position 0 in both
for rows as for columns.
• line
• columna.
• sticky: to stick the widget to one of the edges: N, S, E, W (north, south, east and
west).
• columnspan: for the widget to occupy more than one column.
• rowspan: that the widget occupies more than one row.
3. place(): widgets are arranged in the specific positions of the programmer.

Example 1. Start

A window of specific dimensions will be created.


we import the package
from tkinter import Tk
We create a window
window
we set the window title
A different program
We set the size of the window
[Link]("400x400")
We show an icon in the window
[Link]("[Link]")
we show the window
[Link]()

Execution result

Example 2. Include widgets


More widgets are added to the previous window. The idea is to create an interface like the one that
sample. The pack method will be used to place the widgets. You can use other sources and
colors.

35
Workbook

from tkinter import *


window = Tk()
A different program
[Link]("550x550")
[Link](bg="azure")
Technical Sheet
20), bg="grey", fg="black".pack()
Important data about the character
font=("Arial Bold", 15), fg="red").pack()
PhotoImage(file="[Link]")
lblimagen = Label(window, image=image)
[Link]()
Label(window, text="Model", font=("Arial Bold", 10)).pack()
txtModel = Entry(window, width=10).pack()
Features
10)).pack()
Entry(window, width=30).pack()
Units
txtUni = Entry(window, width=10).pack()
Price
Entry(window, width=10).pack()
Button(window, text='Accept', width=10, fg='red').pack(side=RIGHT)
btnSalir = Button(ventana,text="Salir",width=10,fg="red",
command=[Link]).pack(side=RIGHT)
[Link]()
[Link]()

Execution result

Statements: Class work

Exercise 8.1. Modify

Change the interface of example 2 to achieve the following result, using grid.

36
Exercise Workbook

Statements: Complementary work

Complementary 8.1. Agenda

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

Exercise 8. Graphical User Interfaces. Part II

Objectives

• Use control variables.


• Invocation and implementation of functions
• Outline following object-oriented principles

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

• BooleanVar(). True or False.


• StringVar(). Initializes to "".
• IntVar(). Initializes to 0.
• DoubleVar(). Initializes to 0.0

#To declare them: #Give value to the variables Recover value


integer = IntVar() [Link](100) print("Value of ", [Link]())
StringVar() [Link]("GFG") print("Value of ", [Link]())
boolean = BooleanVar() [Link](False) print("Value of ", [Link]())
floating = DoubleVar() [Link](10.36) print("Value of ", [Link]())

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.

Example 1: Adding more widgets, control variables, and functions

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

from tkinter import *


window = Tk()
[Link]('A program')
[Link]("560x390")

Creation of the variables


withEntry=15
IntVar()
control=BooleanVar()
BooleanVar()
units
StringVar()
DoubleVar()
DoubleVar()
StringVar()
StringVar()
colorN=0

#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

print("Control " + str([Link]())) #Shows true or false if they are


control option marked
If the fields have values then READY, otherwise indicate to complete.
def Accept():
if [Link]()=="" or [Link]()=="" or [Link]()=="" or
[Link]()==""
[Link]("MISSING TO COMPLETE") #Show the error
else:
[Link]("READY") #Show the error

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])

Set a default value


[Link](1)
Indicate monitoring of the variables
[Link]('w',check)
[Link]('w',check)

We create the label and place it on the window


Technical Data Sheet
15),bg="plum3", fg="grey45")
Important character data
font=("Arial Bold", 15)
PhotoImage(file="[Link]")
lblimage = Label(window, image=image, bg="grey")
Name
fg="RoyalBlue2")
Entry(window, width=withEntry, fg="blue2", textvariable=modelo)
Features
fg="RoyalBlue2"
Entry(window, width=withEntry, fg="blue2", textvariable=carac)
Units
fg="RoyalBlue2"
Entry(window, width=withEntry, fg='blue2', textvariable=units)
Price
RoyalBlue2
Entry(window, width=withEntry, fg='blue2', textvariable=price)
Total
fg="RoyalBlue2"
Entry(window, width=withEntry, text='',
blue2
Price
Bold", 10), textvariable=message, fg="red", bg="pink")
New labels for the radio buttons
Radiobutton(window, text="New", font=("Arial Bold",
used
optSemi=Radiobutton(window, text="Semi", font=("Arial Bold",
used
Radiobutton(window, text="Used", font=("Arial Bold",
used
New labels for the checks
chkControl=Checkbutton(window, text="Control", font=("Arial Bold",
9),variable=control, command=Print)
Check batteries
batteries
btnAceptar = Button(ventana,text="Aceptar",width=10,fg="red",command=Aceptar)
Button(window, text="Exit", width=10, fg="red")
[Link]

40
Workbook

we show the labels


[Link](row=0,column=1,columnspan=3,padx=3,pady=5,ipadx=3,ipady=3)
[Link](row=1,columnspan=4)
[Link](column=0,row=2,columnspan=2,rowspan=10,padx=10,pady=10,ipadx=3,
ipady=3)
[Link](row=3,column=2,sticky=W)
[Link](row=3,column=3,sticky=W)
[Link](row=4,column=2,sticky=W)
[Link](row=4,column=3,sticky=W)
[Link](row=5,column=2,sticky=W)
[Link](row=5,column=3,sticky=W)
[Link](row=6,column=2,sticky=W)
[Link](row=6,column=3,sticky=W)
[Link](row=7, column=2, sticky=W)
[Link](row=7,column=3,sticky=W)
[Link](row=8,column=2,columnspan=2,pady=5)
[Link](row=9,column=2,sticky=W)
[Link](row=9,column=3,sticky=W)
[Link](row=9,column=4,sticky=W)
[Link](row=10,column=2,sticky=W)
[Link](row=10,column=3,sticky=W)
[Link](row=11,column=2)
[Link](row=11,column=3)

[Link]('<Button-1>', ChangeColors)

[Link]()
[Link]()

Statements: Classwork

Exercise 8.2. Encode the agenda

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.

Note: Use the code you have from other exercises

41
Workbook

Exercise 8.3. Projectile calculations

A projectile launched at a velocity vo and an angle a (radians) will follow a trajectory


described by the following formulas, where t is time and g is gravity:

x = vo*cos(a)*t

y = vo*sin(a)*t - 0.5*g*t**2

• Implement a window application that allows the user to enter the


parameters in input fields, perform 3 types of calculations upon pressing send
buttons and display the results in labels:
• Distance and impact time based on speed and launch angle using a
loop.
• Distance and impact time from velocity and launch angle using
formula.
• Exit angle and impact time based on velocity and impact distance.

Events and linking

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

• Button-1: A mouse button is pressed, button-1 is the left button.


button-2 is the middle one (if available) and button-3 is the right button.

42
Exercise Notebook

• The mouse moves while button 1 (left) is pressed.


B2-Motion and B3-Motion are available.
• <ButtonRelease-1> Button one of the mouse is released.
• Double-click on button-1
• The mouse pointer enters the widget.
• The mouse pointer leaves the widget.
• Enter is pressed.
• The user presses any key.

The event object

It is a standard Python object that has attributes describing the event that has occurred.
produced. Some attributes of the event are:

• widget: The widget that generates the event.


• x, y: Mouse position coordinates.
• Type: type of event.

Example 2. Click on the image

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:

Routine that changes the background color of the widget


Declaration of the variable that holds the current color.
colorN=0

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])

[Link]('<Button-1>',CambiaColores) #Links the image label with the


mouse click

43

You might also like