Python: Looping If Statement - python

friends = ["Bob","Mike","Ana","Tim","Dog"]
def is_buddy(name):
for friend in friends:
print friend
if friend == name:
return True
else:
return
print (is_buddy('Tim'))
What is the problem here? Why do I get False if I put in "Tim" or anyone else other than Bob?

Try:
def is_buddy(name):
for friend in friends:
if friend == name:
return True
return False
The problem is that you checked name against the first entry of the list which is Bob and you decided to make a boolean decision. You should have returned False only at the end where you checked against every element of the list.

The pythonic way to do what you want:
friends = ["Bob","Mike","Ana","Tim","Dog"]
def is_buddy(name):
if name in friends:
return True
else:
return False
print (is_buddy('Tim'))

Your problem is that else statement tigers return which causes the end of the for loop after 1'st iteration
What you probably want to do is to continue looping. So just remove else part from your function or replace return with something like print "not found"

Related

python if evaluating True for False value

I have the following object field:
is_vendor = models.BooleanField(default=False)
I have the following if statement:
print(customer.is_vendor) //This prints False
if customer.is_vendor:
print('im a vendor') //This prints even the value above is false
else:
print('im not a vendor')
Why is this occurring?
You have a string in the field -- "False" as opposed to False. Which is cool for Django but not python. Try customer.is_vendor.to_python() instead. That will wrangle it into a boolean for you.
if "False": print 'True!' # is True
if False: print 'True!' # Nope.
if customer.is_vendor.to_python():
print "Is a vendor!"

binary search for list in python

My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.
Can someone please explain me what I'm doing wrong?
The program is:
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
else:
return("false")
aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]
xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))
You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.
Your while loop cannot catch the else statement. you don't need that else. try this :
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
result = False
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
result = True
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
return result
aList=[2,3,5,7,5,67,89,101]
xnum=int(input("enter a number:"))
print(searchlist(xnum,aList))

How to make it run through my whole range?

def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) == a%n:
return True
else:
return False
When I check n for a given value it just check 2, then decides if it is true or false and doesn't check the rest of the range. Not sure how to make it check the rest of the range.
That's because you're using a return inside the if-else block. You might want to change the return statement by a print one indicating if it is a prime number or not.
If you want it to return True if all are prime-like or False if at least one is not, then do the following:
def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) != a%n:
print('One element is false')
return False
return True
The print statement is just to show something, but it's not relevant.
I would try making a list and allow your for loop to append the results of the range into the list then return the list as a whole so you can have access to all the results.
edit: Complely missed the point of your question. Here's the edit.
import sys
def isprimelike(n):
resultlist = []
for a in range(2,int(n)-1):
if pow(a,int(n),int(n)) == a%int(n):
result.append(True)
else:
result.append(False)
return resultlist
n = sys.argv[1]
resultlist = isprimelike(n)
if True in resultlist:
if False in resultlist:
print('List contains both True and False')
sys.exit(1)
else:
print('List is all True')
sys.exit(1)
if False in resultlist:
if True in resultlist:
print('List contains both True and False')
else:
print('List is all False')

How to differentiate different names?

FIGURED IT OUT! IT WASN'T LIKE THE ANSWERS BUT I ADDED A SPACE CHARACTER INTO firstName AND THEN EDITED THE VARIABLE lastName
def nameFinder(rollCall, aName):
spaceCharacter = aName.index(" ")
firstName = aName[0:spaceCharacter]
lastName = aName[spaceCharacter:len(aName)+1]
if (firstName in rollCall) or (lastName in rollCall):
return True
else:
return False
rollCall = "Bobby Lee", "Margaret Me"
print(nameFinder(rollCall, "Bob Ce"))
For this function, I have to find whether the first or last name is in the rollCall. It does not have to be both first and last, only first or last. For example "Bob Ce" would result in False because "Bob" was not in the rollCall. How can I make it like that, since it keeps resulting in True.
After removing (firstName in studentList) or from your code, I get False as output.
I believe your firstName in studentList in your if statement is True, so True or False result the output of True
Please also note, you are checking lastName in rollCall in your if statement, in your code lastName is ' Ce'
Your version, modified
Basically, we split aName and then loop through rollCall, trying to match all of the names. If one matches, return true. Otherwise, return false.
def nameFinder(rollCall, aName):
studentName = aName.split(" ")
for name in rollCall:
rollCallName = name.split(" ")
if rollCallName[0] == studentName[0] or rollCallName[1] == studentName[1]:
return True
return False
rollCall = "Bobby Lee", "Margaret Me"
print(nameFinder(rollCall, "Bob Ce"))
A version that takes up less lines
The following code will first merge both lists into First, Last, First2, Last2, then will scan against the name entered, and if at least one matches, then it will return true:
def nameFinder(rollCall, aName):
array_merged = [partName for fullname in rollCall for partName in fullname.split(" ")]
return any([checkingPartName in array_merged for checkingPartName in aName.split(" ")])
rollCall = ["Bobby Lee", "Margaret Me"]
print(nameFinder(rollCall, "Bob Ce"))
Note: Since we are checking if either name exists in the list, I think merging the two lists would simplify the code. However, if you are only given ["Bobby Lee", "Margaret Me"], then this function will work like a charm.

Python Nested If

hey im making a simple little grocery list on Python. I know it's not the most eloquent... but I am just learning the syntax right now. I want to get into learning Django.
list = []
def makeList():
listing = True
while listing:
addTo = raw_input("Add to list: ")
if addTo == 'q':
listing = False
else:
list.append(addTo)
def checkList():
if check in list:
print "Yay there is " + check + " here"
else:
print "No you have not added that..."
addAnother = raw_input("Would you like to add it? ")
if str.lower(addAnother) == "yes":
list.append(check)
elif str.lower(addAnother) == "no":
print "Okay then here is your list."
print list
else:
print check
makeList()
check = raw_input("What item: ")
checkList()
I know its pretty complex and hard to understand O_o... but you can see that the nested if statement is not registering when you run it.
What is making it do this? I think that's the best way to ask this.
I've rewritten it a bit to make it cleaner and more Pythonic;
def get_list(prompt, halt):
lst = []
while True:
item = raw_input(prompt)
if item == halt:
return lst
else:
lst.append(item)
def check_list(lst, item):
if item in lst:
print('Yay there is {} here'.format(item))
return True
else:
print('No you have not added {}'.format(item))
return False
def get_yesno(prompt):
while True:
yesno = raw_input(prompt).lower()
if yesno in {'y', 'yes'}:
return True
elif yesno in {'n', 'no'}:
return False
def main():
mylist = get_list('Add to list:', 'q')
check = raw_input('Look for item:')
if not check_list(mylist, check):
if get_yesno('Would you like to add it?'):
mylist.append(check)
print(mylist)
if __name__=="__main__":
main()
Some style tips:
Don't use list as a variable name; it's a built-in function, and you don't want to overwrite it.
Global variables are almost always a bad idea; passing data around explicitly makes it much easier to figure out where bad data is coming from, and makes functions more reusable.
camelCase is generally denigrated; use_underscores for function names instead.
You probably intended to keep going rather than break when you append the new item (or at least print something to indicate success), but the nested if statement works just fine, appends the thing to the list as specified and then the function and program terminate.

Categories