0% encontró este documento útil (0 votos)
5 vistas8 páginas

Introducción a Python: Listas y Operaciones

Cargado por

tianyujiang08
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
5 vistas8 páginas

Introducción a Python: Listas y Operaciones

Cargado por

tianyujiang08
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

El python pot fer servir de calculadora fent operacions varias, operacions i cadenes de text.

input és para que el usuario introduzca


print es el texto q sale

int: un número s
float: un número amb decimals
eval: introduces una operación i sale el resultado (puede tener decimales)

Llistes python

Una lista se basa en almacenar información de diferentes tipos.

Creación: Usando corchetes [] o list().

mi_lista = [1, 2, 3]

Acceso: Elementos se acceden por índice (0 basado).

mi_lista = [1, 2, 3]

print(mi_lista[0])

Modificación: Puedes cambiar elementos usando su índice.

mi_lista = [1, 2, 3]

print(mi_lista[0])
mi_lista[1] = 5

append(): Añade un elemento al final.

insert(): Inserta un elemento en una posición específica.

remove(): Elimina la primera aparición de un elemento.

pop(): Elimina y devuelve el último elemento.

sort(): Ordena la lista.

Slicing: Puedes obtener sublistas.

mi_lista = [1, 2, 3]

print(mi_lista[0])

mi_lista[1] = 5

sub_lista = mi_lista[1:3]

Ejercicios 1:

x = 4 * 3 - 5 * 2 + 3 * (-1)

print(x)

x = 2 + 4 ** 3

print(x)

x = 36 % 7

print(x)
x = 3 < 7

print(x)

x = 5 == 4

print(x)

x = 5 * (8 - 2 * 7 + 1)

print(x)

x = (2 + 4) ** 3

print(x)

x = 36 % 6

print(x)

x = 5 <= 6

print(x)
x = 7 != 8

print(x)

x = 4 - 6 * (3 + 2 * 4)

print(x)

x = 2 ** 10

print(x)

x = 16 / 5

print(x)

x = 5 >= 5

print(x)

x = 6 == 4 or 5 < 7

print(x)

x = 4 * (3 - 5) + (12 + 8) * 3

print(x)
x = 36 % 8

print(x)

x = 16 // 5

print(x)

x = 6 < 8 and 7 > 9

print(x)

x = 6 == 4 and 5 < 7

print(x)

Ho he fet amb files, fila 1, fila 2…

Ejercicios 2:

n = 5

y = 2 * n + 2

print(y)
# Primera fila de operaciones

n = 5

y = 2 * n + 2

# y es ahora 12

n += 1

# n es ahora 6

x = 3 * n

# x es ahora 18

# Segunda fila de operaciones

x = x ** 2

# x es ahora 324

x = x %= 5

# x es ahora 4

x *= 4

# x es ahora 16

# Tercera fila de operaciones

result1 = n ** (1/2)

# result1 = 2.449489742783178

result2 = n / x

# result2 = 0.375

result3 = x // y
# result3 = 1 (es 1.3 pero el // borra decimales)

result4 = n / 2

# result4 = 3

Ejercicios 3:

palabra1 = "Informática"

palabra2 = "programación"

resultado1 = palabra1 + palabra2

resultado2 = palabra1 + '---' + palabra2

resultado3 = palabra1[3]

resultado4 = palabra1[0] + palabra2[2]

resultado5 = palabra1[:4]

resultado6 = palabra2[-4]

resultado7 = palabra2[6:]

resultado8 = palabra1[:]

resultado9 = list(palabra1)

print("Resultado 1:", resultado1)

print("Resultado 2:", resultado2)

print("Resultado 3:", resultado3)

print("Resultado 4:", resultado4)

print("Resultado 5:", resultado5)

print("Resultado 6:", resultado6)

print("Resultado 7:", resultado7)

print("Resultado 8:", resultado8)


print("Resultado 9:", resultado9)

Common questions

Con tecnología de IA

Operator precedence in Python determines the order in which operations are performed in an expression, which can significantly alter results. It's defined by rules where expressions with higher precedence operators like '**' (exponentiation) are evaluated first, followed by '*', '/', '//', and '%', and then '+' and '-'. Proper usage of parentheses can override default precedence .

In Python, list elements can be directly modified by accessing them with indices and assigning new values. For instance, mi_lista = [1, 2, 3] allows modification of the second element by mi_lista[1] = 5, changing the list to [1, 5, 3]. This capability allows dynamic and flexible list management .

Python's eval() function is useful for dynamically evaluating expressions from strings, such as arithmetic operations with user input at runtime, allowing flexible calculations and adjusting code execution. However, it poses security risks if used with untrusted input, as it can execute arbitrary code leading to vulnerabilities .

Python handles list slicing by using the notation list[start:stop:step], where 'start' is the beginning index, 'stop' is the end index (not included), and 'step' determines the increment. For example, in the list mi_lista = [1, 2, 3], the slice mi_lista[1:3] returns [2, 3]. Slicing creates a new list from the original specified by the indices .

Concatenation joins strings, as in 'palabra1 + palabra2' combining "Informática" and "programación" into "Informáticaprogramación". Indexing accesses specific characters, using zero-based indices like palabra1[3], which yields the fourth character, 'o'. Together, these modes manipulate string structures to create new strings or access string elements .

Integer division with '//' in Python performs division and yields the quotient as an integer, discarding any fractional part. This operator is practical when only the whole number portion of a division is of interest, such as calculating full containers in logistics. It differs from typical division, which returns decimals if present, preserving precision .

Key list operations in Python include append(), which adds an element to the end; insert(), which adds an element at a specific position; remove(), which deletes the first occurrence of an element; pop(), which removes and returns the last element; and sort(), which organizes the list in order. Slicing allows access to sublists using indices .

The '**' operator in Python is used for exponentiation, raising a number to the power of another. For example, 2 ** 3 results in 8. The '//' operator performs integer division, which returns the floor of the division, removing any decimal values. For example, 16 // 5 results in 3, as it removes the decimal .

Python can perform various mathematical operations using operators such as +, -, *, /, %, **, and //. It also manages text strings and numeric inputs, allowing user input with input() and displaying results using print(). For example, eval() can evaluate expressions and return numeric results, accommodating operations with decimals .

The append() method adds elements to the end of the list, ideal for building up lists dynamically. insert() places an element at a specified index, useful when maintaining order is essential. remove() eliminates the first occurrence of a specified value, suitable for clearing elements known to exist. Each method serves distinct list management purposes based on need .

También podría gustarte