Comparing the first and last character of a string in python - 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]

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

String index comparison

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]

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

Creating a Password Criteria Module for Python 3

So here is the issue. I have a series of functions with which an inputString from the user gets checked to meet all of the set password criteria:
Passwords must be at least 5 characters long
Passwords must contain at least one upper case letter
Passwords must contain at least two numbers
Passwords may not contain the characters "E" or "e"
Passwords must include at least one non-alphanumeric character.
A password may not be a frequently used password: 'password', '12345',
'qwerty', 'letmein', 'trustno1', '000000', 'passw0rd,'Password'
My last function attempts to collect all of the functions defined into a single usable module function. There are no errors running the program but there is a bug which always prints, "Invalid! Password must contain special character." Why is that so? And what other bugs or fixed do you guys suggest to make this code more efficient or readable?
def isFiveCharacters(inputString):
while len(inputString) > 5:
return True #print('Contains at least 5 characters, ')
else:
print('Invalid! Password must cantain more than 5 characters')
return False
def hasUpperCase(inputString):
x = any(char.isupper() for char in inputString)
if x == True:
return True #print ('an uppercase letter, ')
if x == False:
print('Invalid! Password must contain an upper case letter')
return False
def hasNumbers(inputString):
count = 0
for char in inputString:
if char == char.isdigit():
count += 1
if count >= 2:
#print ('two numbers, ')
return True
elif count < 2:
print ('Invalid! Password must contain two numbers')
return False
def hasLetterE(inputString):
for char in inputString:
if 'E' and 'e' in inputString:
print('Invalid! Password cannot contain the letter "E"')
return False
else:
#print('does not contain the letter E, ')
return True
#if 'e' in inputString:
# print('Password cannot contain the letter "e"')
# return None
def nonAlphaNumChar(inputString):
special_char = ['!','#','$','%','#','^','&','*']
if inputString == special_char * 2:
#print('a special character, ')
return True
else:
print('Invalid! Password must contain a special character')
return None
def usedPasswords(inputString):
used_passwords = ('password','12345','qwerty','letmein','trustno1','000000','passw0rd','Password')
if used_passwords == inputString:
print('Invalid! Password must be original.')
return False
def passwordCriteria(inputString):
isFiveCharacters(inputString)
hasUpperCase(inputString)
hasNumbers(inputString)
hasLetterE(inputString)
nonAlphaNumChar(inputString)
usedPasswords(inputString)
while inputString == True:
print('Valid Password')
return True
if inputString == False:
print('Error, invalid password')
return False
return None
I am just going to point out the obvious mistake:
You should collect the values returned by the functions like this
valid = isFiveCharacters(inputString)
# then just use the boolean values with an `and`
valid = valid and hasUpperCase(inputString)
valid = valid and hasNumbers(inputString)
# and so on
# then use
if valid:
print("Valid Password")
else:
print("Invalid Password")
I suggest reading about functions the return statement and the while loop in detail and getting a clear understanding of how they work.

Categories