How can i get out of this nested while loop? (Python) - python

Good afternoon! I'm a beginner in coding and i'm trying to do an exercise done for Python.
Building a nested While Loop, i'm with a bug in my little he last line of the code says elif continua == "N"or "n": i = -1 and it should exit all the while loop (the nested and the first one), since i=-1 and the condition for the while loop to work in this code is i > 0 (or at least this is my purpose doing this line of coding.). But all of the sudden the loop starts again and i dont know why.
Can someone help me to get out of this loop?
b = 0
i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:
a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
i=a+1
while i>1:
a=0
v = float(input ("Insira os valores: "))
valorTotal = valorTotal + v
b+=1
i-=1
listadevalores.append(v)
if b>1:
if listadevalores[b-1] < listadevalores[b-2]:
Audiencia = False
else:
if Audiencia == True
print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
elif Audiencia == False
print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
continua = input ("Deseja continuar? S/N")
if continua == "S"or "s":
b=0
valorTotal = 0.00
Audiencia = True
listadevalores = []
i=0
elif continua == "N"or "n":
i = -1

There were several errors in your code.
missing : at the end of if or elif statemennts
several incorrect intendations (maybe a formating issue while copy paste)
You cannot chain bool checks lile continua == "N" or "n" use continua == 'n' or continua == 'N' or in this case even better continua.lower() == 'n'
You are searching for break. Here is a working version of your code:
b = 0
i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:
a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
i=a+1
while i>1:
a=0
v = float(input ("Insira os valores: "))
valorTotal = valorTotal + v
b+=1
i-=1
listadevalores.append(v)
if b>1:
if listadevalores[b-1] < listadevalores[b-2]:
Audiencia = False
else:
if Audiencia == True:
print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
elif Audiencia == False:
print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
continua = input ("Deseja continuar? S/N")
if continua.lower() == "s":
b=0
valorTotal = 0.0
Audiencia = True
listadevalores = []
i=0
elif continua.lower() == "n":
break
The flow of your code is a bit hard to read. Especially it is difficult to understand what your i,a,b variables are doing. Here is a second version which showes how to make your code a bit easier to understand.
def floatInput(input_str):
number = None
while not number:
try:
number = float(input (input_str))
except:
print('not a float number in Portuguese')
return number
while True:
a = int(floatInput("Digite a quantidade de itens de audiência que serão calculados: "))
listadevalores = []
for i in range(a):
v = floatInput("Insira os valores: ")
listadevalores.append(v)
mean = sum(listadevalores) / len(listadevalores)
if sorted(listadevalores) == listadevalores:
print ("Audiência sempre crescente. Média de audiência: ", (mean))
else:
print ("Audiência nem sempre crescente. Média de audiência: ",(mean))
continua = input ("Deseja continuar? S/N")
if continua.lower() == "s":
continue
break
Here is some explanation to the improved parts.
Inputs
The input may be not a number although it is needed. This might create crashes. The exception for strings that cannot be parsed are handled by try: ... except: The second while loop is moved in a seperate function and out of the main flow to make it easier to read. Also it now can be called several times without the need for reapeating code. The while loop is self terminating when number gets a valid value.
Variabels
The meaning of i,a and b are not directly self explanatory. Also they are set at different positions in the code. You already have all information you need in the list.
Ascending lists by definition does not change when they get sorted. We can use this trick to check if the sorted list is the original list sorted(listadevalores) == listadevalores. So we don't need to work on the list elements.
The mean value can be calculated by dividing the sum of all list elements, using the build in sum by the lengt of the list sum(listadevalores) / len(listadevalores).

It seems that you have wrong indentation in question. Please fix this.
Also, it may help you:
create variable that tells your loops to proceed and set it to False when you need to stop the loops. An example:
loop = True
while your_condition and loop:
// Do some stuff here
while your_next_condition and loop:
// Do some stuff here
if something_happened:
loop = False

Related

how data array input

pyton 3.x i'm trying to do append,pop,insert in this ,in insert you need 2 integer to make it work so it need 3 input(1.tambah/buang/sisip | 2.first string(for append)/integer | 3.second string/integer(for insert)
def isNumber(s):
for i in range(len(s)):
if s[i].isdigit() != True:
return False
return True
deret = [1,3,5]
#driver code
if __name__ == "__main__":
j,a,b =(input("H :")).split()
if isNumber(a):
a = int(a)
b = int(b)
else:
a = a
so if i want to do the append one,i only need 2 input (j and a) so i will not insert the (b) one,but it will become an error.and if i want to do the insert one i need 3 input(j,a,b)
j,a,b =(input("H :")).split(),but if i want to do the append or pop one it will become an error because it need 3 value,how i can fix this?
try:
if j == "tambah":
deret.append(a)
print(deret)
elif j == "buang":
deret.pop(a)
print(deret)
elif j == "sisip":
deret.insert(a,b)
print(deret)
else:
print("Perintah tidak dapat dieksekusi!")
except IndexError:
print("Perintah tidak dapat dieksekusi!")
any help and solution for this situation?
if you don't mind could you give the full fix code pls?
the input output should be like this
I believe that the problem you have is that you're expecting to receive 3 inputs every time although that you may receive 2, or 3 inputs depending on your choice ("tambah" / "buang" / "sisip").
so I think you firstly need to receive the input as follows:
input_line = input("H :")
command = input_line.split()[0] # to get the command
try:
if command == "tambah":
a = input_line.split()[1]
if isNumber(a):
deret.append(int(a))
print(deret)
else:
print("Only accepts numbers")
elif command == "buang":
a = input_line.split()[1]
if isNumber(a):
deret.pop(int(a))
print(deret)
else:
print("Only accepts numbers")
elif command == "sisip":
a = input_line.split()[1]
b = input_line.split()[2]
if isNumber(a) and isNumber(b):
deret.insert(int(a), int(b))
print(deret)
else:
print("Only accepts numbers")
else:
print("Perintah tidak dapat dieksekusi!")
except IndexError:
print("Perintah tidak dapat dieksekusi!")
According to what I get from your question is, you want to take two inputs from the user in case you want to append or pop an element from the array, and three inputs in case you want to insert an element. For this I have done:
deret = [1,3,5]
l = list(input().split())
if len(l) == 2:
j = l[0]
a = l[1]
elif len(l) == 3:
j = l[0]
a = l[1]
b = l[2]
appending an element is easy, as whatever element you give as a parameter gets added to the list in the end. But in the case of pop() the parameter you give is not an element, it is the index who's element you want out. It can be left empty. (To deal with this, in that case except will run!)
try:
if j == 'tambah':
if a.isdigit():
deret.append(int(a))
else:
deret.append(a)
elif j == 'buang':
deret.pop(int(a))
elif j == 'sisip':
if b.isdigit():
deret.insert(int(a),int(b))
else:
deret.insert(int(a),b)
else:
print("Perintah tidak dapat dieksekusi!")
print(deret)
except IndexError:
print("Perintah tidak dapat dieksekusi!")
Hope, this worked for you!

How to pick largest element from list?

I wrote a program to count grades and the students' names and I want to implement a feature that shows the highest grade and the respective student. The whole program works except for this part, since I'm not sure how to pick the element with the highest value since it comes with a string attached.
I'll leave the entire program down but the part that I'm refering to is this:
mediafinal = []
elif resposta.upper() == 'N':
resposta = input('Check best student and grade? (Y/N):')
if resposta.upper() == 'Y':
print('Best student and grade is: ', max(mediafinal))
break
The rest of the code
media1 = []
media2 = []
media3 = []
mediafinal = []
nomes = []
while True:
resposta = input('Pretende introduzir um aluno? (Y/N): ')
if resposta.upper() == 'Y':
nome = (input('Indique o nome do aluno: '))
nomes.append(nome)
nota1 = eval((input(f'Indique a nota do primeiro teste {nome}: ')))
nota2 = eval((input(f'Indique a nota do segundo teste {nome}: ')))
m1 = ((nota1 + nota2)/2)
infoaluno1 = []
infoaluno1.extend([nome, m1])
media1.append(infoaluno1)
print(f'O nome e média do primeiro período do aluno é: {nome} {m1}')
nota3 = eval((input(f'Indique a nota do terceiro teste {nome}: ')))
nota4 = eval((input(f'Indique a nota do quarto teste {nome}: ')))
m2 = ((nota3 + nota4) / 2)
infoaluno2 = []
infoaluno2.extend([nome, m2])
media2.append(infoaluno2)
print(f'O nome e média do segundo período do aluno é: {nome} {m2}')
nota5 = eval((input(f'Indique a nota do quinto teste {nome}: ')))
nota6 = eval((input(f'Indique a nota do sexto teste {nome}: ')))
m3 = ((nota5 + nota6) / 2)
infoaluno3 = []
infoaluno3.extend([nome, m3])
media3.append(infoaluno3)
print(f'O nome e média do terceiro período do aluno é: {nome} {m3}')
mf = ((m1 + m2 + m3)/3)
mediafinal.extend([nome, mf])
print(f'Classificação final do aluno: {nome} {mf}')
elif resposta.upper() == 'N':
resposta = input('Pretende verificar o melhor aluno e nota? (Y/N):')
if resposta.upper() == 'Y':
print('O melhor aluno é:', max(mediafinal))
break
elif resposta.upper() == 'N':
print('Ok!')
break
The problem is much much MUCH simpler if you have a list of tuples instead of alternating strings and numbers:
mediafinal.extend([nome, mf])
should be:
mediafinal.append((mf, nome))
Then your max call just works out of the box like this:
mf, nome = max(mediafinal)
print('Best student and grade is: ', nome, mf)
Note that putting the score (mf) first in the tuple means that max will pick based on that. You could change the ordering, but then you need to tell max to make its selection based on the 2nd element:
mediafinal.append((nome, mf))
...
nome, mf = max(mediafinal, key=lambda m: m[1])
So without changing any of your code logic, and just fixing the max() line, I would have it as:
max(a, key=lambda el: el[1])

How to remove a variable in a list a loop as already gone through

My goal here is to create a loop where I get a list ordered by beginning in Inicial and then the item closest to Inicial and then the one closest to the previous one and so on.
The casa_mais_proxima function gives me the closest item in a list to a given item.
I keep getting a list.remove(x): x not in list in grupo.remove(resultado[casa]) and don't know how to change this so that I can remove the items on the list the loop has already gone through.
Inicial = (3,2)
Casas = [(0,1),(1,0),(1,2),(2,3)]
def percurso(Inicial,Casas):
grupo = [Inicial]
grupo.extend(Casas)
resultado = [Inicial]
casas = Casas
for casa in range(len(Casas)):
grupo.remove(resultado[casa])
proxima = casa_mais_proxima(resultado[casa],grupo)
resultado.append(proxima)
return(resultado)
print(percurso(Inicial,Casas))
I think there may be an issue with the other function but i can't spot it
Casas = [(0,1),(1,0),(1,2),(2,3)]
def casa_mais_proxima(P,Casas):
menor_distancia = 0
resultado = []
for elemento in Casas:
if menor_distancia == 0:
menor_distancia = distancia_casas(P,elemento)
if menor_distancia == distancia_casas(P,elemento):
resultado.append(elemento)
if menor_distancia > distancia_casas(P,elemento):
resultado = [elemento]
else:
continue
if len(resultado) == 1:
return resultado
else:
resultado_a = []
for elemento in resultado:
if len(resultado_a) == 0:
resultado_a.append(elemento)
if elemento[0] < resultado_a[0][0]:
resultado_a = [elemento]
if elemento[0] == resultado_a[0][0]:
resultado_a.append(elemento)
else:
continue
if len(resultado_a) == 1:
return resultado_a
else:
resultado_b = []
for elemento in resultado_a:
if len(resultado_b) == 0:
resultado_b.append(elemento)
if elemento[1] < resultado_b[1][1]:
resultado_b = list(elemento)
if elemento[1] == resultado_b[1][1]:
resultado_b.append(elemento)
else:
continue
return resultado_b
print (casa_mais_proxima((1,1),[(0,2),(1,3),(2,1)]))

How do i use correctly the isinstance()

def convBin():
cont = []
rest = []
dev = []
decimal = []
print("Give me a number: ")
valor = input()
if isinstance(valor, int):
while valor > 0:
z = valor // 2
resto = x%2
valor = valor // 2
cont.append(z)
rest.append(resto)
cont.reverse()
rest.pop()
dev.append(cont[1])
for i in rest:
dev.append(rest[i])
print(" ")
print("Lista de devoluciones: ")
print(dev)
print("")
elif isinstance(valor, float):
a = valor // 1
b = valor % 1
while a > 0:
z = a // 2
resto = a%2
a = a // 2
cont.append(z)
rest.append(resto)
cont.reverse()
rest.pop()
dev.append(cont[1])
for i in rest:
dev.append(rest[i])
print("How many decimals do you want?")
num = input()
while num > 0:
dec = b * 1
dec2 = dec//1
dec %= 1
decimal.append(dec2)
print("Full part: ")
print(dev)
print("Decimal part:")
print(num)
else:
print("An error has appeared")
I'm studying Python on my own, so I know that I have big mistakes in the code. Any advice is welcome.
This code is for a binary converter.
Got a problem with the isinstance(). When I try the code, at the moment that read by keyboard it ignores the "if" and it goes directly to the "else".
For example:
1. It asks you a number.
2. It goes to the first if and compare the x type with int(for some reason it is false).
3. It goes to the `elif` and does the same(check if its float).
4. Both are false so it goes to else and prints the error.
You can use ast.literal_eval() instead to parse the string returned by the input() function into an object represented by the content of the string, so that you can use isinstance() to test its type as you intended:
import ast
while True:
try:
valor = ast.literal_eval(input("Give me a number: "))
break
except SyntaxError, ValueError:
print("Please enter a valid number.")

Change from base Shadocks to Base 10 in Python

I have a little problem who block me, I've a work where I must to convert a number to Shadocks (base 4 it seems), and I must to make a decrypter.
So I made the first part, but my code won't work on the second.
Here it's :
def Base10toShadocks(n):
q = n
r = 0
Base4=[]
Shads=["GA","BU","ZO","MEU"]
if q == 0:
Base4.append(0)
else:
while q > 0:
q = n//4
r = n%4
n = q
Base4.append(r)
Base4.reverse()
VocShad = [Shads[i] for i in Base4]
print(VocShad)
def ShadockstoBase10(n):
l=len(n)
Erc_finale=[]
for i in range(l):
Sh=(n[i])
i=i+1
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale)
print(F)
F=F.replace("[","")
F=F.replace("]","")
F=F.replace(",","")
F=F.replace(" ","")
L2=len(F)
F=int(F)
print(L2)
print(F)
r=0
while f < 4 or F ==4:
d=(F%4)-1
F=F//4
print(d)
r=r+d*(4**i)
print(r)
inp = 0
inp2 = 0
print("Tapez \"1\" pour choisir de traduire votre nombre en shadock, ou \"2\" pour inversement")
inp = int(input())
if inp == 1:
print("Quel est le nombre ?")
inp2 = int(input())
if inp2 != None:
Base10toShadocks(inp2)
elif inp == 2:
print("Quel est le nombre ?")
inp2 = str(input())
if inp2 != None:
ShadockstoBase10(inp2)
It blocks at the F=int(F), I don't understand why.
Thanks for your help.
First, some errors in your code:
for i in range(l):
Sh=(n[i])
i=i+1 #### Won't work. range() will override
##### Where do "a","b","o","e" come from
##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")?
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale) ### Not how you join an array into a string
Here's a corrected way:
def ShadockstoBase10(n):
n = n.upper(); # Convert string to upper case
l = len(n)
Erc_finale = "" # Using a string instead of an array to avoid conversion later
i = 0
while i < l: # while loop so we can modify i in the loop
Sh = n[i:i+2] # Get next 2 chars
i += 2 # Skip 2nd char
if Sh == "GA":
Erc_finale += "0"
elif Sh == "BU":
Erc_finale += "1"
elif Sh == "ZO":
Erc_finale += "2"
elif Sh =="ME" and "U" == n[i]:
Erc_finale += "3"
i += 1; # MEU is 3 chars
else:
break; # bad char
return int(Erc_finale, 4) # Let Python do the heavy work
Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.

Categories