Python Forum
Why do these codes give different answers?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why do these codes give different answers?
#1
Question 
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?!
Reply
#2
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?
pooyan89 likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(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?
Reply
#4
(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
Reply
#5
(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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help setting questions and answers in quiz game? yoyoitsjess 3 3,667 May-10-2018, 07:35 AM
Last Post: buran
  Just some second choice answers help please ajaY 6 5,120 Apr-07-2017, 08:25 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020