How to break this code if return is two equal numbers

Asked

Viewed 50 times

-2

good afternoon!

I have a problem where if the user type, two equal cities, the loop is interrupted. However, even putting a conditional and adding BREAK, the loop does not stop, you can help me?

import numpy as np

print("Cidade disponíveis:1,2,3,4,5,6,7")

tp = np.array([[],[0,0,2,11,6,15,11,1],[0,2,0,7,12,4,2,15],[0,11,7,0,11,8,3,13],[0,6,12,11,0,10,2,1], 
[0,15,4,8,10,0,5,13],[0,11,2,3,2,5,0,14],[0,1,15,13,1,13,14,0]])  

for x in range(0,6):
    for y in range(0,6):

        def soma2(x,y):
            resultado3 = tp[x][y]
            return resultado3

        while True:
            
            tp1 = int(input("Digite a cidade origem: "))
            while (tp1 > 7):
                tip1 = int(input("Tente novamente: "))

            tp4 = int(input("Digite a cidade destino obrigatorio: "))
            while (tp4 > 7):
                tp4 = int(input("Tente novamente: "))
                if (tp1 == tp4):
                    break


            destinofinal = soma2(tp1,tp4)
            print(f"A distancia da origem para o destino é: {destinofinal} \n")
  • if you want for the program, the simplest way is to have a main function, and use a Return instead of break

  • 1

    You have one loop inside another, inside another, inside another. Which one do you want to stop? Tip: break always interrupts the inner loop it belongs to. If you want to stop another, you have to change the logic...

1 answer

0

import numpy as np

print("Cidade disponíveis:1,2,3,4,5,6,7")

tp = np.array([[],[0,0,2,11,6,15,11,1],[0,2,0,7,12,4,2,15],[0,11,7,0,11,8,3,13],[0,6,12,11,0,10,2,1], 
[0,15,4,8,10,0,5,13],[0,11,2,3,2,5,0,14],[0,1,15,13,1,13,14,0]])  

for x in range(0,6):
    for y in range(0,6):

        def soma2(x,y):
            resultado3 = tp[x][y]
            return resultado3

        while True:
            
            tp1 = int(input("Digite a cidade origem: "))
            while (tp1 > 7):
                tip1 = int(input("Tente novamente: "))

            tp4 = int(input("Digite a cidade destino obrigatorio: "))
            while (tp4 > 7):
                tp4 = int(input("Tente novamente: "))
            if (tp1 == tp4):
                break


            destinofinal = soma2(tp1,tp4)
            print(f"A distancia da origem para o destino é: {destinofinal} \n")

Hi! Hey, Drohmar! It seems that the if structure is inside another repeat structure (line 15), when you break, it does not leave the "While True" and ends up executing the sum. I wanted to test it here, but you’re not getting the numpy library. I hope it works!

nandapand4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.