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.
Related
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
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]
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]
def reverse(string):
return string[::-1]
def isPalindrome(string):
temp=reverse(string)
if temp==string:
return True
else:
return False
string='tanmay' # input('enter a word')
ans=isPalindrome(string)
if ans==1:
print' Yes palindrome'
else:
print' no its not a palindrome'
if I ask for an input from the user the error what I got was Traceback (most recent call last):
File "C:/Python27/prac06-2.py", line 10, in <module>
string=input('enter a word')
File "<string>", line 1, in <module>
NameError: name 'tanmay' is not defined
but when I enter a string by myself the program is executed successfully
in python 2.7 input() evaluates the given input, you should use raw_input() to read in the data as a string. On another note, temp==string evaluates to a boolean so you do not need to put it in an if statement you can simply return temp==string
def reverse(string):
return string[::-1]
def isPalindrome(string):
temp=reverse(string)
return temp==string
string=raw_input('enter a word')
if isPalindrome(string):
print(' Yes palindrome')
else:
print(' no its not a palindrome')
You can simplify isPalindrome() further by removing reverse() to:
def isPalindrome(string):
return string == string[::-1]
You are returning a boolean True or False and you are trying to compare the result with a value 1. Here is how you should invoke it.
ans = isPalindrome(string)
if ans: # you can also do (if ans == True)
print 'Yes, it is a palindrome'
else:
print 'No, it is not a palindrome'
I'm currently working through Automate the Boring Stuff with Python book and run into curious issue on chapter 7.
When trying to execute the following code:
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != "-":
return False
for i in range(4, 7):
if not text(i).isdecimal():
return False
if text[7] != "-":
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print("415-555-4242 is a phone number:")
print(isPhoneNumber("415-555-4242"))
print("Moshi moshi is a phone number:")
print(isPhoneNumber("Moshi moshi"))
I get the following error message:
Traceback (most recent call last):
File "automation.py", line 27, in <module>
print(isPhoneNumber("415-555-4242"))
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
Switching the str.isdecimal() method for str.isdigit() method allows me to execute the code properly, but I would like to know why the isdecimal() method will not work?
The error has nothing to do with isdecimal(). You have a typo in how you extract the character from text. The
if not text(i).isdecimal():
should read
if not text[i].isdecimal():
(note the square brackets.)
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
The typeError is on line 13, where you are calling a string object. Use [] not ()