While loop without expected behavior - python

I am starting in Python. In the current code, A1 is "returned" infinitely, as if there was no sum of the variable célula. What can I do to get a "return" from A1 and A2?
import xlwings as xw
wb = xw.Book(r'C:\Users\Guilh\bin\teste\Contabilização Automática\myproject\myproject.xlsx')
sht = wb.sheets[0]
def buscar():
linha = '1'
célula = 'A' + linha
valor_célula = sht.range(célula).value
while valor_célula != None:
print('A1')
linha = int(linha) + 1
célula = 'A' + str(linha)
else:
print('A2')

You have neglected to update valor_célula and thus are stuck in the while loop.
I believe you want to update your code to be:
def buscar():
linha = '1'
célula = 'A' + linha
valor_célula = sht.range(célula).value
while valor_célula != None:
print('A1')
linha = int(linha) + 1
célula = 'A' + str(linha)
valor_célula = sht.range(célula).value # Update Value
else:
print('A2')

Related

loop for, and arrays in python

VALOR_VETOR = 6
nota1 = []
nota2 = []
nota3 = []
mediaAluno = []
soma1 = 0
soma2 = 0
soma3 = 0
somaMedia = 0
mediaTurma = 0
print("Digite as notas dos alunos\n\n")
for i in range (VALOR_VETOR):
print(f"Aluno {i}")
valor = float(input(f"Nota 1: "))
nota1.append(valor)
valor = float(input(f"Nota 2: "))
nota2.append(valor)
valor = float(input(f"Nota 3: "))
nota3.append(valor)
valor = (nota1 + nota2 + nota3)/3
mediaAluno.append(valor)
print (f"Nota final = {mediaAluno[i]:.1f}")
for i in range (VALOR_VETOR):
soma1 = soma1 + nota1
soma2 = soma2 + nota2
soma3 = soma3 + nota3
somaMedia = somaMedia + mediaAluno
mediaProva1 = soma1/VALOR_VETOR
print(f"A media da primeira prova é = {mediaProva1:.1f}")
mediaProva2 = soma2/VALOR_VETOR
print(f"A media da segunda prova é = {mediaProva2:.1f}")
mediaProva3 = soma3/VALOR_VETOR
print(f"A media da primeira prova é = {mediaProva1:.1f}")
mediaTurma = somaMedia/VALOR_VETOR
I am a python learner
try, searched, but could not do.
please help me.
line 23, in
valor = (nota1 + nota2 + nota3)/3
TypeError: unsupported operand type(s) for /: 'list' and 'int'
When you use the '+' operator with lists it will return a list with all the 3
lists concatenated
for example:
l1 = [1,2]
l2 = [5,7]
l = l1 + l2 # [1,2,5,4]
I think you expect to get l =[6,9]
also the operator '/' is not defined for a list
so l/3 will return an error
if you want to to sum individual elements in a list you can use below code
i used for loop for clarity but you can use list comprehension or lambda or ...
l =[]
for i in range(len(l1)):
l.append(l1[i] + l2[i])
""" to make the division we can use the same for loop or make another
loop"""
for x in range(len(l)):
l[x] = l[x]/3
valor = (nota1 + nota2 + nota3)/3 //error
try this line of code as:
valor=(sum(nota1)+sum(nota2)+sum(nota3))/3 //it should work

List of dictionaries to json file

I want to convert a list of dictionaries to one json file.
I´ve done it but in the wrong format.
I kind of did it but the file is missing some ',' and some '[]'
import re
import json
listadics = []
N=20
with open("processos.txt", "r") as fileoriginal:
fileN = [next(fileoriginal) for x in range(N)]
for v in fileN:
lista = re.split(r'::|[ ]+[ ]+',v)
dic = {}
contador = 0
nome = 1
linha = 0
for elemento in lista:
if elemento != '\n' and elemento != '':
if contador == 0:
dic["numero processo"] = elemento
elif contador == 1:
dic["data"] = elemento
elif contador >= 2:
dic["nome(s)" + str(nome)] = elemento
nome += 1
contador += 1
listadics.append(dic)
with open("json.json", 'a') as file:
file.write((json.dumps(dic, indent=4, sort_keys= False)))
I solve´d it:
import re
import json
listadics = []
N=20
with open("processos.txt", "r") as fileoriginal:
fileN = [next(fileoriginal) for x in range(N)]
for v in fileN:
lista = re.split(r'::|[ ]+[ ]+',v)
dic = {}
contador = 0
nome = 1
linha = 0
for elemento in lista:
if elemento != '\n' and elemento != '':
if contador == 0:
dic["numero processo"] = elemento
elif contador == 1:
dic["data"] = elemento
elif contador >= 2:
dic["nome(s)" + str(nome)] = elemento
nome += 1
contador += 1
listadics.append(dic)
with open("json.json", 'a') as file:
file.write((json.dumps(listadics, indent=4, sort_keys= False)))

Error name values is not defined in MYSQL With Python in the system register

In the my loop "while true" in option "if" below, i received the error "name 'declaracao' is not defined".
And as a test to see if the INSERT command is working, I'm just printing to the screen.
Some light from friends. Eu sou novato na programação sql.
Regards,
But the result is:
name 'declaracao' is not defined
INSERT INTO cadteste(nrpedido, nome, endereco, numero) VALUES ('{nrkpedido}', '{knome}', '{kendereco}',}', '{knumero}')
Code:
if window == cadastro1 and event == 'Cadastrar' and values['knome'] == ''\
and values['kpedido'] == '' and values['kendereco'] == '' and values['kcep'] == '' and values['kbairro'] == ''\
and values['kestado'] == '' and values['kcomplemento'] == '' and values['ktelefone'] == ''\
and values['kcidade'] == '':
sg.popup('Preencha todos os campos')
continue
elif event == 'Cadastrar':
p = 'kpedido'
n = 'knome'
e = 'kendereco'
nu = 'knumero'
my_data = (p, n, e, nu)
dados = p + ',' + n + ',' + nu + ','')'
declaracao1 = ("INSERT INTO cadteste(nrpedido, nome, endereco, numero) VALUES ('{nrkpedido}', '{knome}', '{kendereco}',}', '{knumero}')")
sql = declaracao1
print(declaracao1)

how to feed strings in an empty list?

I am trying to store the values obtained from excel sheet cells to a list. The code provided basically collects data from different continuous rows and columns and creates a string of those values. I could work upt o storing the string value but I don't really know how to store the strings in a list, Can anyone help me with this?
for i in range(NR):
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
# need to create a list here to store the commentstr for each iteration
NR = no. of rows, NC = no. of columns
my_list=[]
for i in range(NR):
x=0
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
my_list[x]=Commentstr
x+=1

Error with copying values from one sheet to other

I am trying to copy the values from some cells but it give me this error, i tried even without using the def cell(x,y) but still the same error.
This is the error:
learn_tar.cell(row=learn_tar, column=1).value = sheet.cell(row=learn_tar, column=1).value
AttributeError: 'int' object has no attribute 'cell'
Source:
import openpyxl
def cell(x,y):
cell = sheet.cell(row=x,column=y).value
return cell;
def percentage(percent, whole):
return int((percent * whole) / 100.0);
ex = openpyxl.load_workbook("Final_excel2.xlsx")
sheet = ex.get_sheet_by_name('Sheet1')
num = [0,0,0]
per = [0,0,0]
for row in range(2,4798):
if cell(row,1) == '1: Progression':
num[0] = num[0] + 1
elif cell(row,1) == '2: Incidence':
num[1] = num[1] + 1
elif cell(row,1) == '3: Non-exposed control group':
num[2] = num[2] + 1
for column in range(2,49):
#doing stuff
per[0] = percentage(70,num[0])
per[1] = percentage(70,num[1])
per[2] = percentage(70,num[2])
learn_att = ex.create_sheet('Learn-Att',2)
learn_tar = ex.create_sheet('Learn-Tar',3)
test_att = ex.create_sheet('Test-Att',4)
test_tar = ex.create_sheet('Test-Tar',5)
learn_att = 1
learn_tar = 1
test_att = 1
test_tar = 1
for row in range(2,4798):
if row<=1391:
if row<=974:
learn_tar.cell(row=learn_tar, column=1).value = cell(row,1)
learn_att+= 1
learn_tar+= 1
else:
test_tar.cell(row = test_tar,column = 1).value = cell(row,1)
test_att+= 1
test_tar+= 1
for column in range(2,49):
if row<=1391:
if row<=974:
learn_att.cell(row = learn_att,column = column - 1).value = cell(row,column)
else:
test_att.cell(row = test_att,column = column - 1).value = cell(row,column)
You override learn_tar with 1:
learn_tar = ex.create_sheet('Learn-Tar',3)
...
learn_tar = 1
Remove:
learn_tar = 1
and:
learn_tar+= 1
from your code.

Categories

Resources