[go: up one dir, main page]

0% found this document useful (0 votes)
7 views32 pages

Final Programming

The document describes basic programming concepts such as variables, data types, operators, conditionals, and input data. It explains that a variable is a memory space for storing data, and describes types such as integers, floats, strings, and booleans. It also covers arithmetic operators, reserved keywords, and how to create if/else conditionals.
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)
7 views32 pages

Final Programming

The document describes basic programming concepts such as variables, data types, operators, conditionals, and input data. It explains that a variable is a memory space for storing data, and describes types such as integers, floats, strings, and booleans. It also covers arithmetic operators, reserved keywords, and how to create if/else conditionals.
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
You are on page 1/ 32

FINAL PROGRAMMING 1

VARIABLES
In programming, a variable is a memory space where data is stored and
they retrieve the data that a program uses.
Each variable must have a name by which it can be identified and referred to.
to her, during the development of a program.
The variable name cannot match the names of the commands.
assigned to this programming language, in addition to not containing
blank spaces.
Variables that store numbers
○Integers → int
Real numbers/decimals → float
●Variables that store text (in "") →str

RESERVED WORDS
● They are identifiers for exclusive use of the programming language, which do not
they can be used to identify and name variables, methods, objects or
any element within our code.
When trying to use reserved words outside of their assigned usage,
what we will get is a compilation error.

and del for is raise assert

if else elif from lambda return

break global not try class except

or while continue exec import yield

def finally in print

STRING CHAINS OR STRINGS


It is a series of characters composed of letters, numbers, signs, and symbols.
that among its functions, highlights the interaction of a program with the
user
There are different operations to manipulate a string of characters.
The assignment → consists of assigning one string of characters to another.
using the += operator

Hello
message += " "
message += 'Cami'
message

RESULT
Hello Cami

Concatenation → consists of joining two or more strings to form one.


largest string, using the + operator. Another option

1
using commas is efficient, this way spaces are added and we
You can combine variables of both text and numbers.

Hello
espacio
Cami
print(message + space + name)

Hello
Cami
message

RESULT
Hello Cami
Hello Cami

ARITHMETIC OPERATORS
They are those who manipulate numerical data, both whole numbers and
decimal numbers also known as real numbers.
These operators are the simplest of all, they are used to perform
basic arithmetic operations, such as addition, subtraction, multiplication,
divisions, modulus or remainder, and exponentials.
Sum (+)
Subtract (-)
Multiplication (*)
Exponent (**)
Module (%)
Division (/)
Integer division (//)

COMMENTS
Significant annotations for programmers, but ignored by the
program.
○ ' ' → single quotes, as long as they are not assigned to a variable,
as they are interpreted as a null value and for that reason Python does not
take into account.
triple quotes.
○#

Hello, I am Cami

Hello, I am
Cami

Hello, I am Cami

DATA TYPES
Integers and Longs

2
Integers are those that do not have decimals, both positive
as negatives
They can be represented by the tipoint (integer) or the long type (long).
●Floating or real
Floating point numbers are those that have decimals, both positive and
negatives
They are expressed through the type float.
●Chains or Strings
They are nothing more than a text enclosed in single, double, or triple quotes.
(allowing line breaks).
Boolean
It can only have two values → True or False. These values are
especially important for conditional expressions and loops.
They are expressed using the type bool.

➔ Use typeof(variable) to find out what type of data a variable has.

INTEGER DATA TYPE


numero=15
print(number, type(number))
FLOAT DATA TYPE
numero_float=15.5
print(float_number, type(float_number))
STRING DATA TYPE
Ernesto
print(name, type(name))
BOOLEAN DATA TYPE
true_false=3==3
print(true_false, type(true_false))

RESULT:
15
15.5 <class 'float'>
Ernesto
True

DATA ENTRY ON THE KEYBOARD

allows requesting data from the keyboard

EXAMPLE → if I specify the data type, for example int or float, and I introduce another type
with different data, it will give me an error.

word = input("Enter a word: ")


When we want to store integer numbers:
num_int = int(input('Enter an integer: '))
When we want to store a float number:
Enter a float number:

3
print("String: ", word)
print("Integer: ", num_int)
print("Float: ", num_float)

RESULT
introduce a word: hello
Enter an integer: 3
Enter a float number: 2.5
hello
Enter: 3
Float: 2.5

What is your name?:


print("Hello: " + name + ", we are going to perform a sum.")

num_uno = int(input("Please enter the first value: "))


num_dos = int(input("Please enter the second value: "))

result = num_one + num_two

print(name + ' The result of the sum is: ', result)

RESULT:
What is your name?: cami
Hello Cami, we are going to do an addition.
Please enter the first value: 3
Please enter the second value: 5
The result of the sum is: 8

CONDITIONALS
It is a instruction o group of instructions what him execute when a one
a logical condition is set for the program. When that condition is met, the
program executes the instruction that has been assigned to this condition
They help us control decision-making within a program, making use of
of logic
They check if a condition is true or false and based on that, they carry out.
an action

SIMPLE CONDITIONAL SENTENCES:


if [logical condition] :
Instruction
Instruction
[Instruction]

Our program evaluates the condition and there are two possible outcomes: it is met.
(true) or it does not fulfill (false)

4
Everything below delif (with the space) is part of the condition.

num_uno =5
if num_uno == 5:
The number is five
End.

RESULT
The number is five
End.

number_one = 10
if num_uno == 5:
The number is five
End.

RESULT:
End.

In this case, 10 is not equal to 5, so the condition is not met and it goes for the
false path. Therefore, it goes from the conditional statement and moves on to the instruction
that no longer belongs to said sentence

System to calculate a student's average.

name = input("To begin, what is your name?: ")

math = int(input(name + 'What is your math grade?: '))


chemistry = int(input(name + ' What is your chemistry grade?: '))
biology = int(input(name + " What is your biology grade?: "))

average = (mathematics + chemistry + biology) / 3


average = int(average)

if average >= 6:
Congratulations

End

5
RESULT
System for calculating a student's average.
To begin, what is your name?: cami
Cami, what is your math grade?: 9
Cami, what is your chemistry grade?: 8
Cami, what is your biology grade?: 7
Congratulations Cami, you passed with an average of: 8
End

COMPOUND CONDITIONAL SENTENCES


They are those that allow us to have an instruction to execute according to the
established condition
● If the condition is met, there will be a corresponding instruction to execute.
true rama
If the condition in NO if complete there will be another instruction a execute
corresponding to the false branch
Never himself they will execute of way simultaneous the instructions from both branches,
only the instruction corresponding to the true branch will be executed or
false, whose decision is determined by the established condition
If [logical condition] :
Instruction
Else:
[Instruction]

num_uno=5

if num_uno == 5:
The number is five.
else:
The number is NOT five.

End.

RESULT:
The number is five.
The end.

num_uno=10

6
if num_uno == 5:
The number is five.
else:
The number is NOT five.

Fin.

RESULT
The number is NOT five.
Fin.

System to calculate a student's average.

To begin, what is your name?:

math = float(input(name + ' What is your math grade?: '))


float(input(name + ' What is your chemistry grade?: '))
biology = float(input(name + ' What is your biology grade?: '))

average = (mathematics + chemistry + biology) / 3

if average >= 6:
Congratulations
print("Congratulations " + name + " you passed with an average of: ",
round(average,2)

else:
print("We are sorry " + name + " you failed with: ", average)
print("We are sorry " + name + " you failed with: ", round(average, 2))

#round is used to round the number to the decimals you want

End

RESULT:
System to calculate a student's average.
To start, what is your name?: cami
Cami, what is your math grade?:2
Cami, what is your chemistry grade?: 5
Cami, what is your biology grade?:1
We regret to inform you, Cami, that you have failed with an average of: 2.6666666666666665
We regret to inform you that Cami has failed with an average of: 2.67
End

MULTIPLE CONDITIONAL SENTENCES


They aim to make specialized decisions that allow for assessment.
one variable with different results, executing for each case a series of
specific instructions
It allows us to choose a route from among several possible routes, based on the value of
a variable that acts as a selector

7
In the moment in what some of the conditions if may it be fulfilled, self execute the
instruction or instructions corresponding to said condition and the execution of
the conditional sentence will end
If [logical condition] :
Instruction
Elif [logical condition] :
[Instruction]
Else:
[Instruction]

CON
CON

num_uno=1

if num_uno == 1:
The number is ONE

elif num_uno == 2:
The number is TWO

else:
The number is unknown

End

RESULT
The number is ONE
End

num_uno=2

if num_uno == 1:
The number is ONE

elif num_one == 2:
The number is TWO

else:
The number is unknown

Fin

RESULT
The number is TWO

8
End

num_uno=3

if num_uno == 1:
The number is ONE

elif num_one == 2:
The number is TWO

else:
The number is unknown

End

RESULT
The number is unknown
End

Number to words converter!

What number would you like to convert?

if num_uno == 1:
The number is ONE
elif num_uno == 2:
The number is TWO
elif num_uno == 3:
The number is THREE
elif num_one == 4:
The number is FOUR
elif num_one == 5:
The number is FIVE
else:
This program can only convert up to the number 5

End.

RESULT:
Number to words converter!
What number do you want to convert? 3
The number is THREE
The End.

Nesting conditional sentences


They are presented when along the path of true or false of a statement.
conditional there is another conditional statement
That is, when we work with simple or compound conditional statements
multiple, we can place within the instruction or instructions to be executed
from each of these statements, another conditional statement.

9
They consist of having a conditional instruction within another, and depending on
if the condition of the first conditional sentence is met or not met, it
will execute another conditional statement.
In this way, we will have a condition within another condition, expanding the
number of options for our programs to solve a problem,
regardless of the number of situations that arise.

Converter
Options menu:
Press 1 to convert from number to word.
Press 2 to convert from word to number.

Which is your desired option?

if option == 1:
Number to word converter

option_one = int(input("What is the number you want to convert to word?: "))


if option_one == 1:
The number is ONE
elif option_one == 2:
The number is TWO
elif option_one == 3:
The number is THREE
elif option_one == 4:
The number is FOUR
elif option_one == 5:
The number is FIVE
else:
The selected number is not registered

elif option == 2:
print("Word to number converter")

Which word do you want to convert to a number?:


option_two = option_two.lower() #to convert the words to lowercase
entered.
if option_two == "one":
The number is 1
elif option_two == "two":
The number is 2
elif option_two == 'three':
The number is 3
elif option_two == 'four':
The number is 4
elif option_two == 'five':
The number is 5
else:
The selected number is not registered

else:
Option not available

FIN.
RESULT

10
Converter
Menu of options:
Press 1 to convert from number to word.
Press 2 to convert from word to number.
What is your desired option?
Word to number converter
What is the word you want to convert to a number: ?two
The number is 2
END.

------------------------------------------------

Converter
Menu of options:
Press 1 to convert from number to word.
Press 2 to convert from word to number.
What is your desired option?
Number to word converter
What is the number you wish to convert to word: 5
The number is FIVE
END.
RELATIONAL OPERATORS
Relational operators are symbols used to compare two values.
and they are generally used in conditional sentences for making
decisions.
When using relational operators within a conditional statement, if the
the result of the comparison is correct, the expression or condition is considered
true, and if not, it will be false

OPERATOR NAME EXAMPLE MEANING

< Less than 5 is less than 4 5 is less than 4

> Greater than 7 is greater than 5 7 is greater than 5

== Equal to 5 equals 5 5 is equal to 5

!= Not equal to (different) 4 is not equal to 5 4 is different from 5


4 is not equal to 5

<= Less than or equal to 6 <= 6 6 is less than or equal


a6

>= Greater than or equal to 9 is greater than or equal


9 is greater
to 5 than or equal to
a5

print("Introduce two numbers to compare: ")

num_uno = int(input("Enter the first number: "))


num_dos = int(input("Enter the second number: "))

print("The numbers to compare are: ", num_uno, "and", num_dos)

11
if num_one == num_two:
It's the same...
if num_uno != num_dos:
It is different...
if num_one < num_two:
It's smaller...
if num_one > num_two:
It is greater...
if num_one <= num_two:
It is less than or equal...
if num_one >= num_two:
print("Is greater than or equal...")

RESULT:
Enter two numbers to compare:
Enter the first number: 15
Enter the second number: 2
The numbers to compare are: 15 and 2
It's different...
It is greater...
is greater than or equal to...

LOGICAL OPERATORS
Sometimes, it is necessary to use more than two logical conditions within one.
same condition, which means we find ourselves in the need to implement multiple
relational operators to create a much more complex logical expression
However, it is not possible to place two logical conditions within the same one.
condition, without the support of any element that indicates to our programs,
that the union of two or more logical conditions will be carried out within the same
expression.
For this type of situation, there are logical operators, which,
they allow grouping logical conditions within the same condition. That is,
with logical operators we have the possibility to use multiple
relational operators within the same logical condition.

LOGICAL OPERATOR SYMBOL

CONJUNCTION AND

DISJUNCTION OR

DENIAL NOT

AND
(num_uno = 5)
ifnum_one == 5 How do I do to ifnum_uno== 5and ifnum_dos >= 5:
join these two Both conditions have been
(num_uno = 5) → conditions
united
ifnum_dos >= 5 logics in one
sole expression?

12
(num_uno = 5)
ifnum_uno== 5 ifnum_uno == 5 and ifnum_dos >= 5:
How do I do to Both conditions have been
(num_uno = 2) → join these two
united
ifnum_dos >= 5 conditions
logics in one else:
sole expression? One or both conditions not
they have been fulfilled

OR
(num_uno = 5)
ifnum_uno == 5 It meets one or ifnum_uno== 5or ifnum_dos >= 5:
both conditions Both conditions have been
(num_uno = 2) →
united
ifnum_dos >= 5

(num_uno = 8)
ifnum_uno== 5 Does not meet any. ifnum_uno== 5or ifnum_dos >= 5:
from two Both conditions have been
(num_uno = 2) → conditions
united
ifnum_dos >= 5 else:
Does not meet any of the
two conditions)

#and

Conjunction (and)

num_uno = int(input("Enter a number greater than 2 and less than 5: "))

if num_uno > 2 and num_uno < 5:


print("The number ", num_uno, " meets the condition")
else:
print("The number ", num_uno, "DOES NOT meet the condition")

#or
Disjunction (or)

word = input("To meet the condition write 'yes' or 'yes':")

if word == 'yes' or word == "yes"


The condition has been met
else:
The condition has NOT been met

13
RESULT:
Conjunction (and)
Write a number greater than 2 and less than 5:3
The number 3 meets the condition

Disjunction (or)
To comply with the condition write 'yes' or 'yes':yes
The condition has been fulfilled

PRACTICAL EXERCISES:

The multinational company Rappi requests a system that determines the days of
holidays to which a worker is entitled, taking into account the following
characteristics:
There are three departments within the company with their respective keys:
1. Customer service department (key 1)
2. Logistics Department (key 2)
3. Management (key 3)

Workers with key 1 (Customer service):


With 1 year of service, they receive 6 days of vacation.
With 2 to 6 years of service, they receive 14 days of vacation.
After 7 years of service, they receive 20 days of vacation.

Workers with key 2 (Logistics):


With 1 year of service, they receive 7 days of vacation.
With 2 to 6 years of service, they receive 15 days of vacation.
After 7 years of service, they receive 22 days of vacation.

Workers with key 2 (Logistics):


With 1 year of service, they receive 10 days of vacation
With 2 to 6 years of service, they receive 20 days of vacation.
After 7 years of service, they receive 30 days of vacation.

The system must request the 'Name', 'Department key', and 'Tenure' of the
worker from the keyboard
Subsequently, the program must display a message on the screen containing the
worker's name

Rappi's vacation control system

Please enter the employee's name:


department_key = int(input("Please enter the department key: "))
please enter the number of years
labor)

if department_key == 1:
if employee_seniority == 1 and employee_seniority <2:
The employee
vacation
elif employee_seniority >= 2 and employee_ancient <=6:

14
The employee
vacation
elif employee_seniority >= 7:
The employee
vacation
else:
The employee

elif department_key == 2:
if employee_seniority == 1 and employee_ancientness <2:
The employee
vacation
if employee_seniority >= 2 and employee_seniority <=6:
The employee
vacation
elif employee_seniority >= 7:
The employee
vacation
else:
The employee

elif department_key == 3:
if employee_seniority == 1 and employee_seniority <2:
The employee
vacation
if employee_seniority >= 2 and employee_seniority <= 6:
The employee
vacation
if employee_seniority >= 7:
The employee
vacation
else:
The employee

else:
The department key does not exist, please try again.

ANSWER:
Rappi's vacation control system
Please enter the employee's name: Cami
Please enter the department key:3
Please enter the number of working years 2.5
Employee Cami is entitled to 20 days of vacation.

EVEN NUMBER → is an integer that is divisible by two. That is, at the moment
that an integer divided by two has a remainder of zero.

ODD NUMBER → is an integer that is not divisible by two. That is to say, that when
the moment an integer is divided by two, the modulus or remainder is equal to
one

Develop a program that requests an integer number from the user via keyboard,
subsequently, the program must determine and indicate through a message whether the
The entered number is even or odd.

15
The on-screen message should display the phrase the number is even or odd, along with the
number that the user entered from the keyboard, for example:
The number 8 is even
The number 5 is odd

Program that determines if a number is even or odd

number = int(input("Please enter an integer: "))

if number % 2 == 0:
print("The number ", number, " is even")

elif number % 2 == 1:
print("The number ", number, " is odd")

RESULT
Program that determines if a number is even or odd
Please enter an integer: 250
The number 250 is even.

Program that determines if a number is even or odd


Please enter an integer: 365
The number 250 is odd.

Develop a program that requests three integers from the user via keyboard.
subsequently, the program must determine and indicate through a message in
screen, which of the three numbers is the largest.
The message on screen should show the number that turned out to be the largest of the
three, for example:
The number 10 is the largest of the three.

Program to determine which is the largest number of the three

num_uno = int(input("Enter the first number: "))


num_dos = int(input("Enter the second number: "))
Enter the third number:

if num_one > num_two and num_one > num_three:


print("The number ", num_uno," is the largest of the three")
else:
if num_dos > num_tres:
print("The number ", num_dos, " is the largest of the three")
else:
print("The number ", num_tres, " is the largest of the three")

RESULT
Program to determine which is the largest number of the three
Enter the first number: 1
Enter the second number: 2
Enter the third number: 3
The number 3 is the largest number of the three.

16
ASSIGNMENT OPERATORS
NAME OPERATOR IMPLEMENTATION EXPRESSION
EQUIVALENT

Assignment = X=Y X=Y

Sum assignment += X plus equal Y X=X+Y

Subtraction assignment -= X minus equals Y X=X-Y

Assignment of *= X multiplied by Y X=X*Y


multiplication

Assignment of /= X is not equal to Y X=X/Y


division

Assignment of //= X is divided by Y and the result


X=X is stored
// Y in X.
integer division

Assignment of **= X **= Y X = X raised to the power of Y


exponent

Module assignment %= X %= Y X=X%Y


or the rest

WHILE LOOP
● Sometimes when we are developing a program, we encounter the
need to execute one or more lines of code repeatedly, with which
the most logical option is to duplicate the code of these instructions so that
the program completed the assigned task.
However, this alternative is not the most optimal as it duplicates code.
It can generate various problems such as, for example, unnecessary files.
more extensive and difficult to understand when wanting to carry out some
modification or update of the same.
In this situation, in programming we have repetition statements.
code, which allows us to execute a series of instructions or lines of
controlled manner code within our programs, to which they are
known as cycles or loops.
A cycle or loop allows the instructions to be executed repeatedly.
code lines indicated by the programmer, thus, there is no
need to duplicate lines of code to execute them more than once.
The while loop allows for the repeated execution of a group of instructions.
while a condition is met, that is, while the loop condition or
the loop meets the instructions will continue to execute

17
while[condition]:
[instruction]

X=1
while X < 4:
print(X)
X+=1
End

RESULT
1
2
3
End

What this instruction does is keep adding 1, and since the condition is that it is < 4,
when it is not fulfilled, that is, it is > 4, the program ends.

X=1
while X < 11:
Cami
X+=1
End

RESULT:
Rug
Cami
Cami
Cami
Cami
Cami
Cami
Camie
Cami
Cami
End

BREAK SENTENCES
The break statement is used to stop the execution of an iteration and exit.
from her, which will allow the program to continue executing the code
that is outside our loop.

CON
CON

18
#example for break
print("while with the break statement")
counter = 0
while counter < 10:
counter += 1

if counter == 5:
break
Current value of the variable:
End of the program, the break statement has been executed.

RESULT
while with the break statement
Current value of the variable: 1
Current value of the variable: 2
Current value of the variable: 3
Current value of the variable: 4
End of the program, the break statement has been executed.

SENTENCES CONTINUE
It allows to stop the current iteration and return to the beginning of the loop to
perform a new iteration, if the condition that governs our loop is
continues to fulfill (an iteration is the repetition of a segment of code within
of a program)

CON
CON

#example to continue
print("while with the continue statement")
contador =0
while counter < 10:
counter += 1

if counter == 5:
continue
Current value of the variable: , counter

RESULT
while with the continue statement
Current value of the variable: 1
Current value of the variable: 2
Current value of the variable: 3
Current value of the variable: 4
Current value of the variable: 6
Current value of the variable: 7
Current value of the variable: 8

19
Current value of the variable: 9
Current value of the variable: 10

What the program does is that when it reaches 5, it skips it.

THE LEN() FUNCTION


The len() function allows us to obtain the length of a string of characters, or
well, the number of elements that make up an object
You always start counting from the number 0.

len(" H o l a ")
0 1 2 3 4

length of 'Hello Cami'


0 1 2 3 4 5 6 7 8 8

The space counts as one more character.

#option 1
print("Hello has", len("Hello"), ("characters."))

#option 2
length = len("Argentina")
Argentina has

RESULT:
Hello has 4 characters.
Argentina has 12 characters.

FOR LOOP
It is a control structure that allows us to repeat a block of instructions.
(sentences), a certain number of times

for [variable] in [iterable_object] :


Instruction
Instruction
Instruction

An iterable object is one that allows you to traverse its elements one by one. Such as
for example, a string of characters. For example, the sentence 'Hello Cami
traverse character by character

Hello
for character in string:
print(character)
End of the program.

RESULT:
H

20
o
l
a
End of the program.

THE CLASERANGE
Generate immutable number sequences, that is, ones that cannot be modified.
these sequences are generated from a previously established range
It is generally used as an iterable object within the syntax of the for loop.
for loop, with which the respective iterations are achieved
It allows us to work with a minimum of one argument and a maximum of three.
arguments simultaneously. Thus, we can decide the number with which
It will start and end the sequence of numbers, and at the same time, indicate the increment.
the decrement between a number and the next
● range(inicio, parada, paso)
start: is an integer value that indicates the number from which it
it will start generating the sequence of numbers, and this number will always form
part of the sequence.
○ stop: it is an integer value that indicates the number up to which it will go
generate the sequence of numbers, and this number will never be part of the
sequence. For example, if it's 10, it will go from 0 to 9.
○ step: it is an integer value, which indicates the increase or decrease of the
numerical succession between one number and the next

5, 6, 7, 8, 9, 10
range(0, 6) → 0, 1, 2, 3, 4, 5
0, 2, 4, 6, 8, 10
0, 3, 6, 9
range(10, 0) → impossible. it returns nothing. since the increment is 1, it never goes to
reach zero.
range(10, 0, -1) → 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

for [variable]in range (start, stop, step):


[Instruction]
Instruction
Instruction

for index in range (1,5):


print(index)
End of the program

RESULT
1
2
3
4
End of the program

21
Develop a program that displays the multiplication table of a number on the screen.
anyone, this number should be requested and entered from the keyboard by the
user
Use the for loop
The table must contain the multiplications from 0 to 10.

num = int(input("Which multiplication table do you want to see?"))


The table of {num} is:
for iin range(11):
print(f"{num} x {i} = {num * i}")

RESULT
Which multiplication table do you want to see? 8
The table of 8 is:
8x0=0
8x1=8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80

LISTS
Data structures are those that allow us to organize information.
efficiently, and thus, design alternative solutions for a specific
problem
One of the simplest data structures that exists are lists.
Lists are used to store sets of information, in this way,
create a collection of ordered elements, and in turn, these elements can either
no to be related between yes, it to say a list can to be homogeneous o
heterogeneous.
Homogeneous lists:
All the elements that make up the list are of the same data type.
○ lista_homogenea = ["Ari","Cami","Manu"]
Heterogeneous lists:
All the elements that make up the list are of different types.
date
○ lista_heterogenea = ["nombre",20, 1.70, True]
Additionally, the lists they have the characteristic of to be mutable, it is to say, what you
content can be modified after it has been created
● list =[]

Homogeneous list

vocales = ["a", "e","i", "o","u"]


print(vowels)

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

22
print(integers)

numeros_decimales = [1.5,2.5,3.3,4.9]
print(decimal_numbers)

valores_boleanos = [True,False,False,True]
print(boolean_values)

RESULT:
Homogeneous list
['a', 'e', 'i', 'o', 'u']
[1, 2, 3, 4, 5]
[1.5, 2.5, 3.3, 4.9]
[True, False, False, True]

Heterogeneous lists

datos = ["Ari",20,1.76, True


print(data)
RESULT
Heterogeneous lists
Ari

When we work with lists, surge the necessity of access to the elements
content within it, as this way we can consult and even
modify its content
For access a the elements of a list, is necessary to support us of the
indices, the which the they will indicate to us program the position exact del
element we want to work with from the list.

marcas = ["Apple", "Samsung", "Lenovo", "HP"]


len(brands)

To access the position of a list:


Samsung
Lenovo
marks[-1] → HP (goes from back to front)

marcas[1:3] → Samsung, Lenovo

Accessing the positions of a list


marcas = ["Apple","Samsung","Lenovo","HP"]

Complete list:

print("How many elements does the list have?:", len(marcas))

print("Brand 1:", brands[1])

print("Brand 3:", brands[3])

23
print("Brand -1:", brands[-1])

print("Brand -3:", brands[-3])

Print 'Brand 1 to 3:', brands[1:3]

Print('Brand 2:', brands[:2])

print("Brand 1:", brands[1:])

print("Brand:", brands[:])

RESULT:
Accessing the positions of a list
Lista completa: ['Apple', 'Samsung', 'Lenovo', 'HP']
How many elements are in the list?: 4
Samsung
Brand 3: HP
HP
Samsung
Marca 1 a 3: ['Samsung', 'Lenovo']
Marca 2: ['Apple', 'Samsung']
Marca 1: ['Samsung', 'Lenovo', 'HP']
Marca: ['Apple', 'Samsung', 'Lenovo', 'HP']

MODIFY ELEMENTS OF A LIST


A of the big advantages to to work with lists, es what we can modify
each of its elements, according to our needs
The syntax to modify the elements of a list is as follows:
○ vocales = [“a”, “e”, “i”, “o”, “u”]
x
it would be as follows: vowels = ["a", "x", "i", "o", "u"]
○ vocales = [“a”, “e”, “i”, “o”, “u”]
vocales[2:4] = [“x”, “y”]
it would be as follows: vowels = ["a", "e", "x", "y", "u"]

ADD ELEMENTS TO THE LIST


When working with lists, there comes a need to add new elements to
the same, for so, expand the amount of information with the what we are
working.
For this situation we count with he method append() the which us allows
add new elements to the end of a list
list_name.append(new_element)

INSERT ELEMENTS INTO A LIST


It is possible to insert elements into a list at a specific position.
Thus, we will be able to establish the order and organization of all the elements.
that make up our lists
For this situation, we count with the method insert() what a difference delete
method append() we allows indicate the position exact inside of the list,
where we want to add the new element

24
● The syntax to use the insert() method is as follows:
list_name.insert(position, new_element)
○ letras = [“b”, “d”, “f”, “g”]
letters.insert(0, "a")
it would be as follows: letters = ["a", "b", "d", "f", "g"]
○ letras = [“a”, “b”, “d”, “f”, “g”]
letters.insert(2, "c")
it would be as follows: letters = ["a", "b", "c", "d", "f", "g"]
○ letras = [“a”, “b”, “c”, “d”, “f”, “g”]
letters.insert(4, "e")
it would be as follows: letters = ["a", "b", "c", "d", "e", "f", "g"]

DELETE A LIST - THE INSTRUCTION OF


When working with lists, in addition to being able to remove one or several elements from a list
list, is it possible to delete an entire list
To achieve it, we count with the instruction of, the which, us allows remove
a whole list, and at the same time, allows us to delete a single item by indicating the
exact position of the element.
● Alternatively, remove two or more elements simultaneously, indicating the range of
the positions occupied by the elements to be removed
The syntax for using the 'del' statement is as follows:
○ of the name_list → to delete the entire list
○ del name_list[position] → to remove a single element
○ del name_list[position:position] → to remove 2 or more elements
● Examples:
○ vocales = [“a”, “e”, “i”, “o”, “u”]
of vowels [3]
it would be as follows: vowels = ["a", "e", "i", "u"]
○ vocales = [“a”, “e”, “i”, “o”, “u”]
of vowels [0:2]
It would be as follows: vowels = ["i", "o", "u"]
○ vocales = [“a”, “e”, “i”, “o”, “u”]
of vowels [:]
it would be as follows: vowels = [] → removes the content
○ vocales = [“a”, “e”, “i”, “o”, “u”]
of vowels
it would be as follows: remove the entire list

Nested Lists
Nested lists are lists within other lists.
→ lista = [1, “a”,True,[1,2,3]]
list[3][1] → first access position 3 and then position 1
It shows you the → 2
→ lista = [1,“a”,True, [1,2,[“f”, “g”, “h”]]]
list[3][2][0] → first access position 3, then 2, and then 0
It shows you the → f

FINAL TYPE EXERCISES:

25
Read the student ID numbers of a course and their final exam grades.
The end of the load is determined by entering -1 as the file number.
It must be validated that the entered grade is between 1 and 10. Reading completed.
data, inform
Number of students who passed with a grade of 4 or higher
Number of students who failed the exam. Score lower than 4
Average grade and the files that exceed the average
Then it is requested to display a list of files and grades ordered in a way
ascending according to the file number.
Resolve in two ways: Using two parallel lists and using a matrix of
two rows.

legajo =0
note = 0
alumnos = []

while file_number != -1:


file = int(input("Enter your file number (-1 to finish): "))
if file == -1:
break

grade = int(input("Enter your final exam grade: "))


while nota < 1 or grade >10:
Grade out of range, please re-enter it:
students.append((id, grade))

cant_aprobados =0
cant_desaprobados=0
total_notas =0

for file, notes of students:


if nota >=4:
approved_count += 1
else:
cant_desaprobados += 1
total_notes += grade

if len(students) > 0:
average = total_grades / len(students)
else:
average = 0

legajos_arriba_promedio = []
for file, student notes:
if grade > average:
average_files_above.append(file)

print("Number of students who passed:", cant_aprobados)


print("Number of students who failed:", cant_desaprobados)
Print("Average grade:", average)
Print("Files with a grade above average:", legajos_arriba_promedio)

RESULTS:
Enter your file number (-1 to finish):1161066
Enter your final exam grade: 6
Enter your file number (-1 to finish):1161098

26
Enter your final exam score: 4
Enter your file number (-1 to finish):1161027
Enter your final exam grade: 5
Enter your file number (-1 to finish):1161926
Enter your final exam score: 10
Enter your file number (-1 to finish):1161034
Enter your final exam grade: 9
Enter your file number (-1 to finish):-1
Cantidad de alumnos que aprobaron: 5
Number of students who failed: 0
Average grade: 6.8
Legajos con nota mayor al promedio: [1161926, 1161034]

Time to play: Develop a program that generates a random four-digit integer.


numbers and suggests to the user to find out by entering values repeatedly
until found. In each attempt, the program will display messages indicating whether the number
the entered value is greater than or less than the secret value.
Allow the user to exit the game by entering -1. Upon finishing the game.
inform the number of attempts made, asking the user to enter their number
The document improved the best record of attempts obtained so far.
Then show the ordered list of the top 5 scores (also indicating to whom)
they belong) and ask if they want to play again, restarting the game if necessary
affirmative.

27
import random

best score = float('inf') # Best score of attempts initialized to infinity


best_scores = [] # Lista para almacenar los mejores puntajes

while True:
Generate secret four-digit number
figures
Guess the four-digit secret number!

attempts = 0
while True:
guess = int(input("Enter your attempt (-1 to quit):
if guess == -1:
break

attempts += 1

if guess == secret_number:
print("Congratulations! You guessed the number in" , attempts, "attempts!")
if attempts < best_score:
Enter your document number:
best_score = attempts
best_scores.append((attempts, document_number))
break
elif guess < secret_number:
The entered number is greater.
else:
The entered number is smaller.

best_scores.sort() # Sort the list of best scores

High scores:
for score, document in best_scores[:5]:
Attempts:

Do you want to play again? (y/n):


if play_again.lower() != 'y':
Thank you for playing!
break

Read numbers that represent the ages of a group of people, ending the reading
When the number -1 is entered. Print how many are under 18 years old, how many
they are 18 years old or older and the average age of both groups. Discard values that do not
represent a valid age. (A valid age is considered to be between 0 and 100).

menores_de_18 =0
mayores_de_18 =0
suma_menores_de_18 =0
suma_mayores_de_18 =0

age = int(input("Enter the age"))

28
while age != -1:
if age >= 0 and age <=100:

if ( age >= 18):


over_18 += 1
sum_older_than_18 += age

else:
under_18 += 1
sum_under_18 += age
else:
The age is invalid, please enter another one between 0 and 100:

age = int(input('Enter another age'))

The minors under 18 are: , minors_under_18


The over 18s are:

if adults_over_18 > 0:
average_of_over_18 = sum_of_over_18 / over_18
The average age of the elderly is:

if minors_under_18 >0:
average_minors = sum_of_minors_under_18 / minors_under_18
The average age of the minors is:

RESULT:
Enter the age12
Enter another age 32
Enter another age 45
Enter another age 76
Enter another age 202
the age is invalid, please enter another between 0 and 100:
Enter another age 102
the age is invalid, please enter another one between 0 and 100:
Enter another age32
Enter another age-1
Those under 18 are: 1
Those over 18 are: 4
The average age of the elders is: 46.25
The average age of the minors is: 12.0

Read three numbers D, M, and A corresponding to the day, month, and year of a date, and a
an integer number N that represents a quantity of days. Create a program that prints
the new date that results from adding N days to the given date. Keep in mind the years
leap years as detailed in exercise 7 of practice 3.

A leap year is divisible by 4, with the exception of years that are divisible
for 100 but not for 400

def is_leap(year):
return ( ( year %4 == 0 and year %100 != 0) or year %400 == 0 )

#30 days= 4, 6, 9, 11

29
31 days = 1, 3, 5, 7, 8, 10, 12

def get_days_of_month (month, year):


if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month ==
10 or month == 12:
return 31
elif month == 2:
if is_leap_year(year):
return 29
else:
return 28
else:
return 30

day = int(input("Enter a day: "))

month = int(input("Enter a month: "))

year = int(input("Enter a year: "))

Enter the number of days to add:

August 25, 2023 + 58

while cant_dias_sumar > 0:


get_days_of_month(month, year)
print("The number of days in the month ", month, "is: ", num_days)

if cant_dias_sumar >= cant_dias_mes - dia + 1:


cant_dias_sumar -= cant_dias_mes - day + 1
dia = 1
month += 1

if month > 12:


mes = 1
year += 1
else:
day += days_to_add
cant_dias_sumar = 0

print("The new day is: ", day, " / ", month, " / ", year)

RESULT
Enter a day: 7
3
Enter a year: 2000
Enter the number of days to add: 32
The new day is: 8 / 4 / 2000

Read an integer and display a message informing how many digits it contains.
Keep in mind that the number can be negative. Example: If it is entered
12345 should print 5.

number = int(input("Enter an integer number"))

30
length = len(str(abs(number)))

The number contains

RESULT:
Enter an integer 9056
The number contains 4 digits.

Read an integer and reverse its digits. Print it on the screen.


inverted number. Keep in mind that the number can be negative. For example, if
If -1234 is entered, it should show -4321.

#432

number = int(input("Enter an integer: "))


absolute_number = abs(number)

numero_invertido =0

while absolute_number > 0:


last_digit = absolute_number % 10
inverted_number = inverted_number * 10 + last_digit
absolute_number //= 10

if number < 0:
inverted_number *= -1

print(inverted_number)#234

notes[0][1]

RESULT
Enter an integer: 432
234

A Consortium Administrator needs a system to manage the collection of


the expenses of an apartment building with 20 units. Store in two lists
the following information: Unit number and area in square meters. Validate
that duplicate unit numbers are not entered. Each unit pays a fee of
fixed value per square meter, which is entered via keyboard. The request is:
Inform the average expenses of the month.
• Sort the listings from highest to lowest according to the area. Display on the screen the
ordered list informing the unit number and the area in square meters.

unidad = []
metros = []
Enter the value of the expenses per square meter:

for iin range(20):


unit_number = int(input("Enter your unit number: "))
while number_unit in unit:
The unit number already exists. Please enter a valid unit.
Enter your unit number:

31
area=float(input("Enter the number of square meters: "))

unit.append(unit_number)
metros.append(surface)

total_superficie = 0
for area in square meters:
total_area += area

average_expenses = total_area * expenses / len(unit)


Average monthly expenses:

for unit, meters in sorted_list


Unit:
Unit:
Print('Unit: ', unit[3], 'Surface: ', meters[3])
Unit: , area:
print("Unit: ", unidad[5], "Surface: ", metros[5])
Print: "Unit: ", unit[6], "Surface: ", meters[6]
Unit: , area:
Unit: , Area:
print("Unit: ",unit[9],"Surface: ",meters[9])
Unit: , Surface:
Unit: , Area:
Unit: , unit[12], Surface: , meters[12]
Unit: , area:
Unit:
Unit: , surface:
Unit: , Surface:
Unit: , Surface:
Unit:
Unit: , area:
Unit: , Surface:

32

You might also like