String index comparison - python

I am having issues understanding this concept. I am trying to use [-1] index of message[-1] and compare it to the first index message[0] to compare the first letter and the last letter of a string in the function.
def first_and_last(message):
message = " "
if message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))

You are setting your message to the same value every time. You need to instead use the message that is passed to the function.
def first_and_last(message):
if message and message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
True
False
False
You can also get the same result with less work by recognizing that you're performing a test and returning the result of that test.
def first_and_last_improved(message):
return message[0] == message[-1] if message else False

Hey you are initialising the message = " " inside the function so no matter what you sent as a parameter to function it will always initialise it. Remove that line and you will get the expected output.

Firstly, you are overwriting message variable. So whatever you pass to the function returns the same result.
You can think of a string of array of chars. In Haskell string is actually array of chars.
For example... "str" would be ["s", "t", "r"]. So "str"[0] returns s, while -1 returns r.
Also your code can be short by like this.
def first_and_last(message):
return message[0] == message[-1]

Related

trying to determine whether the first and last letters of a string are the same

first and last () is used to call a function that determines whether the first and last letters of a string are the same
def first_and_last(message):
if message[0] == message[-1]:
return True
elif message[0] != message[-1]:
return False
elif message == "":
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
C:\Users\angel\PycharmProjects\pythonProject1\venv\Scripts\python.exe C:\Users\angel\PycharmProjects\pythonProject1\app.py
Traceback (most recent call last):
File "C:\Users\angel\PycharmProjects\pythonProject1\app.py", line 13, in <module>
print(first_and_last(""))
File "C:\Users\angel\PycharmProjects\pythonProject1\app.py", line 2, in first_and_last
if message[0] == message[-1]:
IndexError: string index out of range
True
False
Process finished with exit code 1
The issue is with the empty string input "", as python cannot find a 0th or -1st index of this, it throws an error before reaching the elif statement. If you check for an empty string first, then you will avoid this error:
def first_and_last(message):
if message == "":
return False
elif message[0] == message[-1]:
return True
elif message[0] != message[-1]:
return False
Output:
True
False
False
Edit: there are many comments on the question and this answer on shorter ways to achieve this goal, which are all valuable. This answer is just explaining why OP gets the error and how to fix it using only their code

Comparing the first and last character of a string in python

first_and_last function returns True if the first letter of the string is the same as the last letter of the string, False if they’re different, by accessing characters using message[0] or message[-1]. While checking the condition for an empty string I get tihis error:
Error on line 2:
if message[0] == message[1] :
IndexError: string index out of range
I dont understand why am I getting this error.
Here's my code below:
def first_and_last(message):
if message[0] == message[-1] or len(message) == 0:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
or stops evaluating operands on the first truthy operand. Hence, you must check the message length first in order to avoid the indexed access into the empty string:
def first_and_last(message):
if len(message) == 0 or message[0] == message[-1]:
return True
return False
Or shorter:
def first_and_last(message):
return not message or message[0] == message[-1]

Received a python syntax error while running the below code

Errors is thrown to verify if the character in a string is empty:
Python code
def first_and_last(message):
if(message[0] == message[-1] or len(message[0])==0):
return True
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
Error
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(first_and_last(""))
File "main.py", line 2, in first_and_last
if(message[0] == message[-1] or len(message[0])==0):
IndexError: **string index out of range**
You need to compare for an empty string before you access its elements. Your condition should be:
if(len(message)==0 or message[0] == message[-1]):
And it should be len(message) and not len(message[0]) because if your message is empty, there would not be any message[0].
You first need to make sure that the message is not empty string.
use this method, it returns 0 which evaluates false, and true when first and last chars are same.
def first_and_last(message):
return len(message) and message[0] == message[-1]
try this :
def first_and_last(message):
if(len(message)==0):
return True
elif(message[0] == message[-1] or len(message[0])==0):
return True
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
The error was you have to mention the case of checking empty string as well since you were passing the empty string in the function.

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))

Python if( ): vs if:

On Code Academy there is this course where in the example they show
def speak(message):
return message
if happy():
speak("I'm happy!")
elif sad():
speak("I'm sad.")
else:
speak("I don't know what I'm feeling.")
The above example will NOT be related to the rest of the code I show. That was just an example for the if statement. Now I was under the impression that when ever writing an if statement it had to end in an ():like the above example.
However when doing the assignments this does not work:
def shut_down(s):
if s == "yes"():
return "Shutting down"
elif s == "no"():
return "Shutdown aborted"
else:
return "Sorry"
However this works:
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
My question is how come the () is not needed next to the "yes" and "no" but :is still needed. I thought whenever writing an if statement it will automatically have to end with ():. In that very first example, that's how it is shown. Do you understand my confusion.
In the example given, happy() and sad() are functions, and as such require parentheses. The if itself does not need parentheses at the end (and it shouldn't have them)
No, if has nothing to do with ()
happy is a function. happy() is a call to that function. So, if happy(): tests if the happy function returns true when called.
In other words, if happy(): speak("I'm happy!") is equivalent to
result_of_happy = happy()
if result_of_happy:
speak("I'm happy!")
As has been mentioned happy() / sad() are functions so they require (). In example two of your question you are comparing your value to the string "yes" because it is a string it does not require ().
Within an if statement you can use parentheses to make the code more readable and ensure certain operations are evaluated before others.
if (1+1)*2 == 4:
print 'here'
else:
print 'there'
Differs from:
if 1+1*2 == 4:
print 'here'
else:
print 'there'
Because string objects are not callable so what are you expecting then:
Then use lambda not that efficient tho:
def shut_down(s):
if (lambda: s == "yes")():
return "Shutting down"
elif (lambda: s == "no")():
return "Shutdown aborted"
else:
return "Sorry"

Categories