I am a very beginner in Python and I want to repeat this code. But I don't really know how to do this without "goto". I tried to learn about loops but did not understand how to apply them.
import requestsaddr = input()vendor = requests.get('http://api.macvendors.com/' + addr).textprint(addr, vendor)
Best Answer
Create a function repeat
and add your code in it. Then use while True
to call it infinitely or for i in range(6)
to call it 6 times:
import requestsdef repeat():addr = input()vendor = requests.get('http://api.macvendors.com/' + addr).textprint(addr, vendor)while True:repeat()
Note that goto is not recommended in any language and is not available in python. It causes a lot of problems.
A loop is the best way to achieve this. For example check out this pseudo code:
While person is hungryEat food a bite of foodIncrease amount of food in stomachIf amount of food ate fills stomachperson is no longer hungrystop eating food
In code this would look something like this:
food_in_stomach = 0while food_in_stomach <= 8:eat_bite_of_food()food_in_stomach += 1
You could therefore implement your code like the following:
times_to_repeat = 3while times_to_repeat > 0:addr = input()vendor = requests.get('http://api.macvendors.com/' + addr).textprint(addr, vendor)times_to_repeat -= 1
You can create a variable, and then say that as long as the variable is true to its value, to repeat the code in the for loop.