I've been messing around with this code for some hours, and it still give me errors. I want to do an 'automark' for tests, where you introduce the good answers and the bad ones, and it calculates the final mark.
Code:
class puntuacion:
def __init__(self, aciertos, errores):
self.aciertos = int(input("Introduce el numero de aciertos"))
if self.aciertos > 40:
print("Numero maximo de aciertos: 40")
exit()
self.errores = int(input("Introduce el numero de errores: "))
def calculo(self):
totalac = self.aciertos * 0.25
print(totalac)
while self.errores > 3:
totalerr += -0.25
self.errores - 3
print'Nota final: ', totalac-totalerr
calculo({})
Error:
C:\Users\Admin>python C:\Users\Admin\Documents\python\test2.py
Traceback (most recent call last):
File "C:\Users\Admin\Documents\python\test2.py", line 1, in <module>
class puntuacion:
File "C:\Users\Admin\Documents\python\test2.py", line 17, in puntuacion
calculo({})
File "C:\Users\Admin\Documents\python\test2.py", line 10, in calculo
totalac = self.aciertos * 0.25
AttributeError: 'dict' object has no attribute 'aciertos'
You can't call an instance method directly: you have to instantiate the class first:
p = puntuacion(something, something_else)
p.calculo()
The calculo() method does not take any arguments: the first argument, selfis implicit, and corresponds to the class instance. You don't pass it.
You should also remove the input() functions from your __init__; you're already passing aciertos and errores as arguments, and generally you don't want to do "complicated" stuff (like user interaction) in the initialization of a class:
...
def __init__(self, aciertos, errores):
self.aciertos = aciertos
self.errores = errores
...
and then:
aciertos = int(input("Introduce el numero de aciertos"))
if aciertos > 40:
sys.exit("Numero maximo de aciertos: 40")
errores = int(input("Introduce el numero de errores: "))
p = puntuacion(aciertos, errores)
p.calculo()
Related
I want to do a list with lists inside, with a for and i get index out of range
I tryed with empleados.append() but it doesnt work
def main():
empleados=[]
for i in range(1):
empleados[i][0](input("Ingrese el Nombre: "))
empleados[i][1](input("Ingrese el Apellido: "))
empleados[i][2](int(input("Ingrese el Sueldo Base: ")))
empleados[i][3](int(input("Ingrese el AFP 1 o 2: ")))
empleados[i][4](datetime(int(input("Ingrese la Fecha de Ingreso(pulsa intro cada vez 2000 12 31): ")),int(input("/")),int(input("/"))))
empleados[i][5](int(input("Ingrese la cantidad de hijos que tiene: ")))
welcome to SO!
There's no list at empleados[0] to insert new values into. I find something like this is a little easier to read:
def main():
empleados=[]
for i in range(1):
empleado_nueva = []
empleado_nueva.append(input("Ingrese el Nombre: "))
empleado_nueva.append(input("Ingrese el Apellido: "))
empleado_nueva.append(int(input("Ingrese el Sueldo Base: ")))
empleado_nueva.append(int(input("Ingrese el AFP 1 o 2: ")))
empleado_nueva.append(datetime(int(input("Ingrese la Fecha de Ingreso(pulsa intro cada vez 2000 12 31): ")),int(input("/")),int(input("/"))))
empleado_nueva.append(int(input("Ingrese la cantidad de hijos que tiene: ")))
empleados.append(empleado_nueva)
return empleados
It's worth mentioning that the index-access pattern you're attempting (empleados[i][0] = ...) only works if there's something already at that index, for instance:
>>> x = []
>>> x[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> x = ['a', 'b', 'c']
>>> x[0] = 'd'
>>> x
['d', 'b', 'c']
So the append's are probably the best way to go.
The problem is you're trying use empleados[i] as a list with an existing index you can insert into, when at the moment, it's not.
You need to set up your variables a separate list and then append them. E.g.
def main():
empleados=[]
vars = [
input("Ingrese el Nombre: "),
input("Ingrese el Apellido: "),
int(input("Ingrese el Sueldo Base: ")),
int(input("Ingrese el AFP 1 o 2: ")),
datetime(int(input("Ingrese la Fecha de Ingreso(pulsa intro cada vez 2000 12 31): ")),int(input("/")),int(input("/"))),
int(input("Ingrese la cantidad de hijos que tiene: ")
empleados.append(vars)
We're making an exercise with pickle, and this code doesn't work as it is supposed to. Please help me, this is the code (some words are in Spanish because I'm from America):
import pickle
class persona:
def __init__(self, nombre, genero, edad):
self.nombre = nombre
self.genero = genero
self.edad = edad
print("se ha creado una persona nueva con el nombre de: ", self.nombre)
def __str__(self):
return "{} {} {}".format(self.nombre, self.genero, self.edad)
class listaPersonas:
personas = []
def __init__(self):
listaDePersonas = open("ficheroExterno", "ab+")
listaDePersonas.seek(0)
try:
self.personas = pickle.load(listaDePersonas)
print("Se cargaron {} personas del fichero externo".format(len(self.personas)))
except:
print("El fichero está vacío")
finally:
listaDePersonas.close()
del(listaDePersonas)
def agregarPersonas(self, p):
self.personas.append(p)
self.guardarPersonasEnFicheroExterno()
def mostrarPersonas(self):
for p in self.personas:
print(p)
def guardarPersonasEnFicheroExterno(self):
listaDePersonas = open("ficheroExterno", "wb")
pickle.dump(self.personas, listaDePersonas)
listaDePersonas.close()
del(listaDePersonas)
def mostrarInfoFicheroExterno(self):
print("La información sle fichero externo es la siguiente: ")
for p in self.personas:
print(p)
miLista = listaPersonas()
persona = persona("Sandra", "Femenino", 29)
miLista.agregarPersonas(persona)
miLista.mostrarInfoFicheroExterno()
and it throws that:
El fichero está vacío
se ha creado una persona nueva con el nombre de: Sandra
Traceback (most recent call last):
File "Guardado_permanente.py", line 54, in <module>
miLista.agregarPersonas(persona)
File "Guardado_permanente.py", line 34, in agregarPersonas
self.guardarPersonasEnFicheroExterno()
File "Guardado_permanente.py", line 42, in guardarPersonasEnFicheroExterno
pickle.dump(self.personas, listaDePersonas)
_pickle.PicklingError: Can't pickle <class '__main__.persona'>: it's not the same object as __main__.persona
***Repl Closed***
I have like 1 1/2 hour that I'm seeing this code and I'm trying to guess which is the problem, but the code is the same as my teacher's code. please, help me. I'm using Sublime text to code.
In this line, you have replaced your class persona with an instance of the class:
persona = persona("Sandra", "Femenino", 29)
pickle is trying to find the class definition for persona but can't, because it doesn't have a name anymore.
Don't try to use the same name for two things; only the last assignment counts. Standard style is to use CamelCase names for clasess, so you could name your class Persona instead.
everyone! I have this problem when I try to call a function that involves interaction with the user and I don't know what the problem is. The function that requires an input works perfect when separate from the other function.
I am using Jupyter Notebook [py2].
The function I am talking about is the following:
import numpy as np
import matplotlib.pyplot as plt
#Distribución Exponencial
def dist_exp():
a = int(raw_input("Ingrese Lambda: "))
b = int(raw_input("Ingrese la cantidad de numeros a generar: "))
beta = 1./a
exp = np.random.exponential((beta), b) #el primer valor es Beta (1/Lambda)
mediana_t = np.log(2)/(a*a)
print exp #imprime los números aleatorios generados
print "Estadísticos teóricos: ", "Minimo=0", " Maximo= infinito", " Media={}".format(beta), " Mediana={}".format(mediana_t), " Varianza={}".format(1/(a*a))
#imprime los estadísticos teóricos
print "Estadísticos muestrales: ", "Minimo={}".format(np.min(exp)), " Maximo={}".format(np.max(exp)), " Media={}".format(np.mean(exp)), " Mediana={}".format(np.median(exp)), " Varianza={}".format(np.var(exp))
#imprime los estadísticos muestrales
#bins son las clases para el histograma
if b<1000: #para los bins
bn = 20
else:
bn = 200
h = plt.hist(exp, bins=bn, normed=True) #bins son las clases para el histograma
plt.show() #despliega el histograma
I am calling this function (and 4 other similar functions) from the following:
from ipywidgets import widgets, interactive
from IPython.display import display
print "Ingrese la distribucion deseada. Las opciones son: Binomial, Exponencial, Geometrica, Lognormal y Triangular"
text = widgets.Text()
display(text)
def handle_submit(sender):
print(text.value)
if text.value == "Binomial":
return dist_bin()
elif text.value == "Exponencial":
return dist_exp()
elif text.value == "Geometrica":
return dist_geom()
elif text.value == "Lognormal":
return dist_log()
elif text.value == "Triangular":
return dist_tri()
else:
print "Por favor ingrese una distribucion valida. Ponga atencion a las opciones."
text.on_submit(handle_submit)
So, everytime the user types a valid String in the textbox, I need to perform a function, but I get this error instantly:
---------------------------------------------------------------------------
EOFError Traceback (most recent call last)
<ipython-input-8-1e49bbab45fa> in handle_submit(sender)
10 print(text.value)
11 if text.value == "Binomial":
---> 12 return dist_bin()
13 elif text.value == "Exponencial":
14 return dist_exp()
<ipython-input-5-081f517da431> in dist_bin()
1 #Distribución Binomial
2 def dist_bin():
----> 3 n = int(raw_input("Ingrese n: ")) #número de intentos
4 p = float(raw_input("Ingrese p: ")) #probabilidad de cada intento
5 num = int(raw_input("Ingrese la cantidad de numeros a generar: "))
EOFError: EOF when reading a line
I will appreciate any help.
Thank you all!
I'm testing a query with python and sqlite3. First method works fine, but
second is not working. It is about the defined type of variable containing the resgisters in DB:
import sqlite3
def insertar():
db1=sqlite3.connect('tabla.db')
print("Estas en la funcion insertar")
nombre1=raw_input("Escribe el titulo de la novela: ")
autor1=raw_input("Escribe el autor de la novela: ")
year1=str(input("Digita el any de la novela: "))
consulta=db1.cursor()
strConsulta = "insert into tabla(nombre, autor, year) values\
('"+nombre1+"','"+autor1+"','"+year1+"')"
print(strConsulta)
consulta.execute(strConsulta)
consulta.close()
db1.commit()
db1.close()
def consultar():
db2 = sqlite3.connect("tabla.db")
print("Estas en la funcion insertar")
db2row_factory = sqlite3.Row
consulta = db2.cursor()
consulta.execute("select * from tabla")
filas = consulta.fetchall()
lista = []
for fila in filas:
s = {}
s['nombre'] = fila['nombre']
s['autor'] = fila['autor']
s['year'] = str(fila['year'])
lista.append(s)
consulta.close()
db2.close()
return(lista)
#consultar()
def menu():
Opcion= input("\nIngresa la opcion deseada\n1.Inserta un valor en la tabla\n2.Consultar los valores de la tabla\n")
if Opcion==1:
insertar()
menu()
elif Opcion==2:
ListaNovelas = consultar()
for novela in ListaNovelas:
print(novela['nombre'],novela['autor'],novela['year'])
menu()
menu()
I get this error while testing the second method consultar().
$ python file.py
Ingresa la opcion deseada
1.Inserta un valor en la tabla
2.Consultar los valores de la tabla
2
Estas en la funcion insertar
Traceback (most recent call last):
File "insertar.py", line 56, in <module>
menu()
File "insertar.py", line 51, in menu
ListaNovelas = consultar()
File "insertar.py", line 33, in consultar
s['nombre'] = fila['nombre']
TypeError: tuple indices must be integers, not str
db2row_factory = sqlite3.Row
This is the problematic line. Instead you meant to set the row_factory factory on the db2 connection instance:
db2.row_factory = sqlite3.Row
Then, all the fetched rows would be now sqlite3.Row instances having dictionary-like access to field values.
I've got a problem with Python 2.7.3-32bits on Windows. I put this code to see if anyone can help me out with this error. The comments are in Spanish but it don't affect the code.
import gtk
import numpy
import math
import os
#Pedimos el nombre de la imagen de origen
nombreFich = input("Por favor, introduzca el nombre de la imagen de origen:")
#Validar que existe el fichero
imagen1 = gtk.Image()
imagen1.set_from_file('C:\\Users\\xxx\\Desktop\\xxxx.png')
pb1 = imagen1.get_pixbuf()
pm1 = pb1.get_pixels_array()
#Hacemos una copia de la imagen
pm2 = pm1.copy()
#Validamos los puntos de distorsion hasta que sean validos
puntos = " "
arrayPuntos = " "
while(puntos == " " and len(arrayPuntos) < 4):
print"Por favor, introduzca los puntos de distorsión xc yc r e:"
puntos= raw_input()
arrayPuntos = puntos.split(" ")
#Sacamos los puntos separando la cadena por el caracter espacio
xc =(puntos[0])
yc =(puntos[1])
r =(puntos[2])
e =(puntos[3])
#función que calcula el grado de distorsión
def grado(self,z,e):
if(z>1):
return 1
elif(e<0):
return (1/z)**(-e/(1-e))
else:
return z**e
#Distorsionamos la imagen
def distors(xc,yc,r,e,x,y):
d = math.sqrt(x**2+y**2)#Sacamos la distancia
z = d/r
if(z!=0):
g=grado(z,e)
xm=x*g
ym=y*g
return xm,ym
else:
xm=x
ym=y
return xm,ym
def recorrido (pm1, xc, yc, r, e):
pm2 = pm1.copy()
x= str(--r)
y= str(--r)
while (y <= r):
while (x <= r):
xm, ym = mover(xc, yc, r, e, x, y)
pm2[yc+y][xc+x] = pm1[yc+ym][xc+xm]
x = x+1
y= y+1
x= -r
return pm2
pm2 = recorrido(pm1, xc, yc, r, e)
#Guardamos los cambios
pb2 = gtk.gdk.pixbuf_new_from_array(pm2,pb1.get_colorspace(),pb1.get_bits_per_sample())
nomfich2 = nombreFich+"_copia"
ext = os.path.splitext("C:\\Users\xxx\Desktop\xxxx.png_copia")[1][1:].lower()
pb2.save("C:\\Users\xxx\Desktop\xxxx.png_copia",ext)
print"FINISH"
When I run the python code I get the following error:
Traceback (most recent call last):
File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 71, in <module>
pm2 = recorrido(pm1, xc, yc, r, e)
File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 59, in recorrido
x= str(--r)
TypeError: bad operand type for unary -: 'str'
The error message is telling you that r is a string. You can't negate a string.
Why is it a string? Well, it seems to come from here:
# ...
puntos= raw_input()
arrayPuntos = puntos.split(" ")
# ...
r =(puntos[2])
The split method on a string returns a list of strings.
So, how do you solve this? Well, if r is, say, the string "22", then float(r) is the float 22.0, and int(r) is the integer 22. One of those is probably what you want.
Once you add, say, r=int(r), your --r will no longer be an exception.
But it probably isn't what you want. In Python, --r just means the negation of the negation of r—in other words, it's the same as -(-(r)), which is just r. You're probably looking for the equivalent of the C prefix operator--, which decrements the variable and returns the new value. There is no such operator in Python; in fact, there are no operators that modify a variable and then return the value.
This is part of a larger issue. Python is designed to make statements and expressions as distinct as possible, to avoid confusion. C is designed to make as many things as possible expressions, to save typing. So, you often can't just translate one into the other line by line.
In this case, you have to do it in two steps, as Thanasis Petsas shows:
r -= 1
x = str(r)
Increment ++ and decrement -- operators are not supported in python.
You can use instead this:
r -= 1
x = str(r)