Python Forum

Full Version: Why do these codes give different answers?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My goal is to write a function that takes a letter as an argument, it loops through its words and gives me False if it contains 'e' otherwise it is True.
The correct code is:
def has_no_e(letter):
    for i in letter:
        if i=='e':
            return False
        
    return True
But I tried with one another attempt:
def has_no_e2(letter):
    for i in letter:
        if i!='e':
            return True
        
    return False
But this code does not give me the correct answer if I try for example
print(has_no_e2('Robert'))
What is wrong?!
for char in "Robert":
    print(char)
Output:
R o b e r t
The first element is the str R. What do you think will happen, if you return True?
(Dec-14-2020, 10:21 AM)DeaD_EyE Wrote: [ -> ]
for char in "Robert":
    print(char)
Output:
R o b e r t
I thought it would loop through all the words in there.
The first element is the str R. What do you think will happen, if you return True?
(Dec-14-2020, 10:21 AM)DeaD_EyE Wrote: [ -> ]
for char in "Robert":
    print(char)
Output:
R o b e r t
The first element is the str R. What do you think will happen, if you return True?
f
Allright ! I've got it now! I missunderstood the Boolean! True or False will terminate the whole loop
(Dec-14-2020, 11:43 AM)pooyan89 Wrote: [ -> ]True or False will terminate the whole loo
No, not the True or False, but the return statement.
def function():
    for _ in range(10):
        return # <-- function will return None
               # the loop does not continue if you return from a function
               # in this case the first iteration will return None
               # the None is implicit
It's not the True or False, the return statement is what will return something.

A plain return returns None.
A return in a for-loop will imminently return and the for-loop won't do further iterations.