Stuck With Loops in Python - Only Returning First Value

Stuck with loops in python - only returning first value

Functions end as soon as a return is reached. You'll need to return once at the end instead of inside the loop:

def func1(x):
# The string to work on
new_str = ""

for (a,b) in enumerate (x):
# Add to the new string instead of returning immediately
if a%2 == 0:
new_str += b.upper()
else:
new_str += b.lower()

# Then return the complete string
return new_str

Python for loop returns only the first value

I'm guessing that you want to loop over json_data['imdata']. Your original code never refers to the node in the loop. Try this:

def get_nodeid1():
url='https://%s/api/node/class/fabricNode.json' % apic
response = requests.get(url, cookies=session_cookie, timeout=2, verify=False)
json_data = json.loads(response.text)
for node in json_data['imdata']:
m1 = node['fabricNode']['attributes']['name']
m2 = node['fabricNode']['attributes']['serial']
m3 = node['fabricNode']['attributes']['address']
print(f"Node ID: {m1} Serial: {m2} Address: {m3}")

My for loop randomly gets stuck and doesnt complete its range

The reason it is getting stuck is because there is an error in the boundary condition. If the number is not equal to mid and the left and right should be equal to mid + 1 and mid - 1 respectively. No need to consider mid again. Since you are considering mid again and again, your condition is never coming out of this cycle and hence the infinite loop.

elif x > mid:
left = mid + 1

elif x < mid:
right = mid - 1

These should be your new values for left and right. No need to consider mid again because it is not equal to the target value, if it were, the top most if the condition would have been true.

Why am I stuck in an endless loop?

Change this part:

except Exception as e:
print e

to this:

except Exception as e:
print(e)
break

And if you are breaking while catching the exception, there seems to be no point in having a while True, remove this part:

while True:
print ("test")
sleep(2)

But if you go with the while True approach, put a break state somewhere in the loop:

while True:
print ("test")
sleep(2)
try:
doc = html.fromstring(page.content)
if some_cond:
break

EDIT:

Let me try making it simpler. There are two ways from where we are:

First Approach:

def some_function():
try:
#Your expected code here
return True
except:
# will come to this clause when an exception occurs.
return False

Second Approach:

while True:
if some_cond
break
else:
continue

Considering your Code, I would suggest to opt for the first approach.

OR:

If the intention is to still keep try-ing unless a specific cond and not break on exception:

bFlag = False
while bFlag == False:
try:
if some_cond:
bFlag = True
except:
continue

Recursive function gets stuck in a temporary loop

You can solve this by maintaining a set of the nodes that you have already visited on the current path. To facilitate the use of this set, I personally prefer to create a nested function that will take care of the recursion, and keep define that set at the main function's scope, accessible to the inner function.

Also, I think your base case needs a little adjustment, as the distance of equality is one less (0) than the (remaining) distance when you have a positive in result (1).

def had_contact_with(meetings, person_X, person_Y, distance=-1):
visited = set()
if distance == -1:
distance = len(meetings)
if person_X == person_Y:
return True
if distance == 0:
return False

def recur(person_X, distance):
if person_Y in meetings[person_X]:
return True
if distance == 1 or person_X in visited:
return False
visited.add(person_X)
for person in meetings[person_X]:
if recur(person, distance - 1):
return True
visited.remove(person_X)
return False

return recur(person_X, distance)

why is my function not adding up all my numbers? it only gives the first number

You have a problem with indentation.

Try this:

def add(*numbers):
total = 0
for number in numbers:
total = total + number

return (total)

Get stuck in a 'while True' loop python

With the for-else construct you only enter the else block if the for loop does not break, which your for loop always does because i inevitably becomes 3 with your range generator. Your infinite while loop is therefore never able to reach the return statement, which is only in the said else block.



Related Topics



Leave a reply



Submit