Reputation: 11
I'm trying to find a way of finding a specific character in an element in a list. The program is meant to check if the first letter of the input words are the same, and to output 'True' if so:
inp = input('Enter words: ')
inp2 = inp.split()
if inp2[0][len] in inp2[0][len]:
print('True')
and to have it do something like this:
Enter word: beetle btleee
True
or:
Enter word: beetle tleeeb
False
Upvotes: 1
Views: 166
Reputation: 168
I hope this is what you are asking for:
input1 = input('Enter the two words: ')
input2=input1.split()
def function(input2):
if input2[0][0]==input2[1][0]:
print('True')
else:
print('False')
function(input2) #and then call the function.
Upvotes: 0
Reputation: 26315
You need to compare the first character of the first word with inp2[0][0]
against first character of the second word with inp2[1][0]
. You can do this easily with the equals ==
operator.
if inp2[0][0] == inp2[1][0]:
print("First letters are equal") # or True
else:
print("First letters are not equal") # or False
For safety you should also ensure inp2
has 2 words. You can use an if
condition to do this:
if len(inp2) == 2:
if inp2[0][0] == inp2[1][0]:
print("First letters are equal")
else:
print("First letters are not equal")
else:
print("Please enter two words")
Also printing "True"
is a not necessary since you can use reserved boolean types True
and False
. You can have a look at Built-in Constants from the documentation for more information.
Another approach is using tuple unpacking with try..catch
exception handling:
inp = input('Enter words: ')
try:
word1, word2 = inp.split()
if word1[0] == word2[0]:
print("First letters are equal")
else:
print("First letters are not equal")
except ValueError:
print("Please enter only 2 words")
Which catches a ValueError: too many values to unpack
exception if more than two words were entered, or ValueError: not enough values to unpack
if less than 2 words were entered. You can have a look at Handling Exceptions from the documentation for more information on how to handle errors/exceptions.
You could also wrap the word comparison code inside a function that returns bool
:
def is_equal_first_letters(word1, word2):
if word1[0] == word2[0]:
return True
else:
return False
Alternatively with more terse syntax:
def is_equal_first_letters(word1, word2):
return word1[0] == word2[0]
Then call the function in the rest of your code:
inp = input('Enter words: ')
try:
word1, word2 = inp.split()
print(is_equal_first_letters(word1, word2))
except ValueError as ex:
print("Please enter only 2 words")
You can have a look at this Python Functions tutorial to learn more about functions.
Upvotes: 1