You're returning immediately in both the if and else blocks. That ends the loop in both cases.
You should only return in the if block. If you make it through the entire loop without returning, you know that all the words are title case.
def all_title_case(word_list):
for word in word_list:
if not word.istitle():
return False
return True
You can also use the all() function instead of a loop.
def all_title_case(word_list):
return all(word.istitle() for word in word_list)
Answer from Barmar on Stack OverflowYou're returning immediately in both the if and else blocks. That ends the loop in both cases.
You should only return in the if block. If you make it through the entire loop without returning, you know that all the words are title case.
def all_title_case(word_list):
for word in word_list:
if not word.istitle():
return False
return True
You can also use the all() function instead of a loop.
def all_title_case(word_list):
return all(word.istitle() for word in word_list)
Return statement ends the execution of your function, if you return True only when your for iteration is done you will have what you want
In other words your return statement ends your for loop, you can read some about it on this question: How to use a return statement in a for loop?
word_list=["ABC", "abc", "Abc"]
def all_title_case(word_list):
for word in word_list:
if not word.istitle():
return False
return True
print(all_title_case(word_list))
First "for loop" stops after first iteration python - Stack Overflow
Python for loop stops working after first iteration - Stack Overflow
For Loop stops after first iteration
python - How do I stop this from exiting after the first iteration? - Stack Overflow
As the title implies, I'm attempting to use a for loop to send multiple requests to an API. When running the code, it only sends the first request. However, when updating the for loop to simply print the data in the multiple requests I'm sending, it prints all of the expected data, iterating without issue. Anyone know what's going on here?
This will iterate completely
def stuff():
for i in thing():
print(i)When using the API information applied to the for loop, it only sends the first iterable.
def stuff():
for i in thing():
#api stuff
payload['fields']['name'] = i[0]
payload['fields']['date'] = i[1]
url = 'https://stuff.com'
response = requests.post(url, data = json.dumps(payload), headers = HEADERS)
result = json.loads(response.text)
if response.status_code == 200:
result = {'result' : 'progressing', 'message' : 'Task Scheduled.'}
return {
'statusCode': response.status_code,
'headers': { 'Content-Type': 'application/json' },
'body': json.dumps(result)
}There are two things you need to change.
Instead of using a while-loop and breaking, just use an if-statement. Your code will still work the same way, but it'll be much more readable.
Move the return statement outside of the for-loop, i.e. unindent it. This way
newstringwon't be returned until the entire for-loop has been executed, which is the desired behavior.
The full corrected code is below:
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
if (ch == old_ch):
newstring += new_ch
else:
newstring += ch
return newstring
print(test("Megalovania", "a", "o"))
# Prints Megolovonio
for ch in s statement is used to loop over every character of the string.
Hence the while loop inside the for loop is not required.
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
if(ch == old_ch):
newstring = newstring+new_ch
if(ch != old_ch):
newstring = newstring + ch
return newstring
This code does the intended work you want to achieve.
Replace spread = game['odds'] with spread = game.get('odds',[]) so that spread gets an empty list when there is no 'odds' key and the rest of the code will behave correctly.
I'm going to assume that it stops because of a KeyError Here, you have two choices to overcome it.
dict().get()
d = {}
d.get('foo') #Returns None
The .get() method is handy because if the specified key doesn't exist, then it will simply return None. Use where you don't want to deal with errors raining from the sky.
try except
Slightly more complex.
try:
raise ValueError('ya goofed m8')
except ValueError:
print('How the tables have turned...')
This will listen for an error and then execute some code if that error happens
try is the code you want to listen for an error in.
except is the code for the error.
return immediately leaves the function, even if you are only on the first pass through your for loop.
Instead, try
def first_vowel(word):
for offset,ch in enumerate(word):
if ch in "aeiou":
return offset
return 0
def modify_word(word):
v = first_vowel(word)
return word[v:] + word[:v] + "xx"
def modify(s):
words = s.split()
return ' '.join(modify_word(word) for word in words)
def format(s):
return s
def final(s):
return format(modify(s))
final("This is a test case") # => 'isThxx isxx axx esttxx asecxx'
Increase the indention of the else block as following:
def format(x):
return x
def modify(string):
for x in words:
if statement:
return x[v:] + x[:v] + "xx"
else:
return x + "xx"
def final(string):
return format(modify(string))
You can do it in one line:
def whence(g, v):
return [key for key, values in g.items() if v in values]
The return statement indented too much.
def whence(g, v):
# Your code here
lov = []
count = 0
for key, value in g.items():
if v in value:
lov.append(count)
count += 1
print(lov)
return lov
return causes the function to exit completely. The way you've written it, you've told the function to return immediately after the first iteration - so it's no wonder it stops then. :)
This is an indenting issue - what you really want is:
def get_venue_link_list(links):
for link in links:
linkset.add(link.get("href"))
return linkset
This lets the loop finish first, and then exit.
That's because you don't give it a change to continue the iteration. You return inside the loop, so it doesn't get to the second iteration. You need to un-indent that line:
def get_venue_link_list(links):
for link in links:
linkset.add(link.get("href"))
return linkset
Return exits the function, which exits the loop. You could try printing x in the loop or build up and then return x outside of the loop.
Well You need to simply change the return in check function to yield thereby converting it to a generator and we can use the next function to iterate through the output
def fac(n) :
f = []
for i in range(2,int(n/2)) :
if n % i == 0 : f.append(i)
return f
def check(n) :
for j in fac(n) :
g=[]
g.append(n)
g.append(j)
g.append(int(n/j))
x = int("".join(map(str, g)))
yield x
print("using for loop")
#print (check(28))
for i in check(28):
print(i)
print("Using next function")
n=check(28)
print(next(n))
print(next(n))
print(next(n))
OUTPUT
using for loop
28214
2847
2874
Using next function
28214
2847
2874