For some reason it works great but on some sentences that are palindrome it says they are not
palindrome = input("Enter a word: ")
palindrome = palindrome.lower()
palindrome.replace(" ", "")
if palindrome == palindrome[::-1]:
print("OK")
else:
print("NOT")
An example:"Mr Owl ate my metal worm"
but on other sentences it works good and i don't understand whats different
please help me btw the level of the code needs to be at this level
instead of using replace whitespace ( if they are not require much ) then, you can convert the word to list of words sperated on whitespace and then create a new word joining all word inside the list and reverse it to check if the sentence is palindrome or not
here is code
palindrome = input("enter the word ")
palindrome = ''.join(palindrome.split()).lower()
if palindrome == palindrome[::-1]:
print("OK")
else:
print("NOT")
without using join
palindrome = input("enter the word ")
new_palin = ''
for chars in palindrome:
if chars != ' ' :
new_palin+=chars
new_palin = new_palin.lower()
if new_palin == new_palin[::-1]:
print("OK")
else:
print("NOT")
So I am stuck with the part of checking if the letter is present in the word or not. The game needs to let a person guess a letter in the word, and tell if this letter is present in word or not(5 attempts only)
import random
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
for j in range(0,len(word)):
if inp == word[j]:
print("Yes, we have this letter.")
else:
print("No, we don't have this letter.")
i=i+1
The expected output would be one sentence, either confirming that the letter is present in word, or disproving. However, the actual output is that is prints one sentence per each of letters in the given word, like this:
What's your guess for a letter in the word?
p
Yes, we have this letter.
No, we don't have this letter.
Instead of checking against each letter of the word (and thereby printing it each time), just check whether the letter is in the word:
while i<5:
inp = input("What's your guess for a letter in the word?\n")
if inp in word:
print("Yes, we have this letter.")
You can try regular expression:
import random
import re
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
res = re.findall(inp, word)
length = len(res)
if length == 0:
print("Your guess is wrong :( ")
else:
print(f"You guess is right :) ")
i +=1
here the output of regular expression is a list so you can do whatever you want with it, e.g. hangman game or ...
I am working on an assignment where we have to ask the user for a word, and then if the word has a letter that repeats the initial letter in the word, such as: ApplesAuce (the A repeats), the program will store the word in the list and then print out the list when the user is done entering words.
I am getting this error
if word[0].lower() in word[1:].lower(): IndexError: string index out
of range
Here is my code:
wordlist = []
word = input("Please enter a hilariously long word: ")
# I said "hilariously long" to increase the likelihood of a repeat letter
while wordlist != '':
word = input("Please enter another hilariously long word: ")
if word[0].lower() in word[1:].lower():
wordlist.append(word)
word = input("Please enter another hilariously long word: ")
print("All of the words that had repeated first letters are: ")
print(wordlist)
Test for the presence of a word and break out of the while loop if it isn't there.
wordlist = []
msg = "Please enter a hilariously long word: "
# I said "hilariously long" to increase the likelihood of a repeat letter
while True:
word = input(msg)
if word:
if word[0].lower() in word[1:].lower():
wordlist.append(word)
else:
break
print("All of the words that had repeated first letters are: ")
print(wordlist)
Note also that wordlist is a list so the test while wordlist != "" will always be the case because a list is not a string
This should work.I have introduced the breaker that is quit or done will break the loop. I have also moved your first input inside which will add another if wordlist is populated.
wordlist = []
# I said "hilariously long" to increase the likelihood of a repeat letter
while 1:
word = input("Please enter {}hilariously long word: ".format('another ' if wordlist else ''))
# get out if done or quit is typed
if word in ('done','quit'):
break
if word[0].lower() in word[1:].lower():
wordlist.append(word)
print("All of the words that had repeated first letters are: ")
print(wordlist)
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.
def guess():
letter = input ("Please enter a letter:")
if letter in word:
print ("Correct!")
letterPlace = word.index(letter)
answer[letterPlace] = letter
print (*answer)
else:
print ("Wrong!")
if answer == word :
print ("You guessed it! Well Done!")
#end here
else:
guess()
from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
In that part:
if letter in word:
print ("Correct!")
letterPlace = word.index(letter)
answer[letterPlace] = letter
word.index(letter) will return the index of the first occurrence of the letter.
So you'll replace only the first underscore by the letter. Do that instead:
if letter in word:
print ("Correct!")
for letterPlace in (idx for idx,l in enumerate(word) if l==letter):
answer[letterPlace] = letter
the code loops and if it finds the letter, the generator expression yields the index, to replace the underscore.
you can try this if you want. pretty easy to understand if you don't want anything too complicated:
def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
def guess():
letter = input ("Please enter a letter:")
if letter in word:
print ("Correct!")
letterPlace = findOccurences(word,letter)
for i in letterPlace:
answer[i] = letter
print (*answer)
else:
print ("Wrong!")
if answer == word :
print ("You guessed it! Well Done!")
#end here
else:
guess()
from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
Nice game by the way.
The issue here is that you are replacing only the first occurrence of the letter. In order to replace all occurances, use the re function like this:
def guess():
letter = input ("Please enter a letter:")
if letter in word:
print ("Correct!")
letterPlace = [m.start() for m in re.finditer(letter, word)]
for index in letterPlace:
answer[index] = letter
I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So for instance:
#here is a variable containing a word:
my_word = "Acrobat"
#letters in vowel as a list
the_vowel = ["a","e","i","o","u"]
How do a check that the first letter in "Acrobat" is one of the vowels in the list? I also need to take into consideration whether it is upper or lowercase?
try my_word[0].lower() in the_vowel
I don't know if it is better than the answers already posted here, but you could also do:
vowels = ('a','e','i','o','u','A','E','I','O','U')
myWord.startswith(vowels)
Here are some hints to help you figure it out.
To get a single letter from a string subscript the string.
>>> 'abcd'[2]
'c'
Note that the first character is character zero, the second character is character one, and so forth.
The next thing to note is that an upper case letter does not compare equal to a lower case letter:
>>> 'a' == 'A'
False
Luckily, python strings have the methods upper and lower to change the case of a string:
>>> 'abc'.upper()
'ABC'
>>> 'a' == 'A'.lower()
True
To test for membership in a list us in:
>>> 3 in [1, 2, 3]
True
>>> 8 in [1, 2, 3]
False
So in order to solve your problem, tie together subscripting to get a single letter, upper/lower to adjust case, and testing for membership using in.
my_word = "Acrobat"
the_vowel = "aeiou"
if myword[0].lower() in the_vowel:
print('1st letter is a vowel')
else:
print('Not vowel')
My code looks like this.
original = raw_input("Enter a word:")
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print word
print first
print "vowel!"
else:
print word
print first
print "consonant
x = (input ("Enter any word: "))
vowel = "aeiouAEIOU"
if x[0] in vowel:
print ("1st letter is vowel: ",x)
else:
print ("1st letter is consonant: ",x)
Here's how I did it since the inputted word needs to be checked first before storing it as a variable:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
else:
print 'empty'
changes:
if my_word[0] in ('a','e','i','o','u'):
print(' Yes, the first letter is vowel ')
else:
print(' No, the first letter is not vowel ')
So, Here is the simple code for finding out that the first letter is either vowel or not!! If you have any further query in python or js, then comment it down.
import ast,sys
input_str = sys.stdin.read()
if input_str[0] in ['a','e','i','o','u','A','E','I','O','U']:
print('YES')
else:
print('NO')
Here is the solution to the exercise on codecadmy.com:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print 'vowel'
else:
print 'consonant'
else:
print 'empty'
Will it not be (slightly) faster to define the_vowel as a dictionary than a list?
the_vowel = {"a":1,"e":1,"i":1,"o":1,"u":1}
my_word[0].lower() in the_vowel
anti vowel Function
def anti_vowel(text):
vowel = ["a","e","i","o","u"]
new_text = ''
for char in text:
if char.lower() in vowel:
continue
else:
new_text += char
print new_text
return new_text
x = raw_input("Enter a word: ")
vowels=['a','e','i','o','u']
for vowel in vowels:
if vowel in x:
print "Vowels"
else:
print "No vowels"
This would print out 5 lines, if any of those includes a line that says Vowels then that means there is a vowel. I know this isn't the best way but it works.
Let's do it in more simply way
def check_vowel(s1):
v=['a','e','i','o','u']
for i in v:
if s1[0].lower()==i:
return (f'{s1} start with Vowel word {i}')
else:
return (f" {s1} start with Consonants word {s1[0]}")
print(check_vowel("orange"))
inp = input('Enter a name to check if it starts with vowel : ') *# Here we ask for a word*
vowel = ['A','E','I','O','U', 'a','e','i','o','u'] *# This is the list of all vowels*
if inp[0] in vowel:
print('YES') *# Here with the if statement we check if the first alphabet is a vowel (alphabet from the list vowel)*
else:
print('NO') *# Here we get the response as NO if the first alphabet is not a vowel*
my_word = "Acrobat"
the_vowel = ["a", "e", "i", "o", "u"]
if my_word[0].lower() in the_vowel:
print(my_word + " starts with a vowel")
else:
print(my_word + " doesnt start with a vowel")
input_str="aeroplane"
if input_str[0].lower() in ['a','e','i','o','u']:
print('YES')
else:
print('NO')
Output will be YES as the input string starts with a here.