Python vowel eater - python

Good evening everyone..... i wrote a vowel eater program with the code below
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
print(letter)
It run fine but i want to use concatenation operation to ask python to combine selected letters into a longer string during subsequent loop turns, and assign it to the wordWithoutVowels variable.....
I really appreciate any help or suggestions thanks in advance

is this what you need?
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
word = letter
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
wordWithoutVowels+=letter
print(wordWithoutVowels)

Another approach. You can prepare a set of vowels you want to filter-out before-hand and then use str.join() to obtain you string:
userWord = input("Please Enter a word: ")
vowels = set('aeiou')
wordWithoutVowels = ''.join(character for character in userWord if not character.lower() in vowels)
print(wordWithoutVowels)
Prints (for example):
Please Enter a word: Hello World
Hll Wrld

I'm sorry I didn't read the original post (OP) more carefully. Poster clearly asked for a way to do this by concatenation in a loop. So instead of excluding vowels, we want to include the good characters. Or instead of looking for membership, we can look for not in membership.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
vowels = 'aAeEiIoOuU'
wordWithoutVowels = '' # initialize to empty string
for letter in userWord:
if letter not in vowels:
wordWithoutVowels += letter # equivalent to wordWithoutVowels = wordWithoutVowels + letter
print(wordWithoutVowels)
Please Enter a word: Hello World
Hll Wrld

or you can try this:
wordWithoutVowels = ""
user = input("Enter a word: ")
userWord = user.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "O":
continue
elif letter == "I":
continue
elif letter == "U":
continue
else:
wordWithoutVowels += letter
print(wordWithoutVowels)

Using str.replace() seems like a natural way to go for a problem like this
Brute Force
Just go through all of the vowels. And if they exist in input string, replace them
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
# make a copy of userWord
output = userWord
# replace vowels
output = output.replace('A', '') # replace A with empty string
output = output.replace('E', '') # replace E with empty string
output = output.replace('I', '') # replace I with empty string
output = output.replace('O', '') # replace O with empty string
output = output.replace('U', '') # replace U with empty string
print(output)
Please Enter a word: Hello World
HLL WRLD
Use a loop
This is a little more elegant. And you won't have to convert the input to uppercase.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
# make a copy of userWord
output = userWord
# replace vowels
vowels = 'aAeEiIoOuU'
for letter in vowels:
output = output.replace(letter, '') # replace letter with empty string
print(output)
Please Enter a word: Hello World
Hll Wrld

Try this. I think it's the easiest way:
word_without_vowels = ""
user_word = input("Enter a word")
user_word = user_word.upper()
for letter in user_word:
# Complete the body of the loop.
if letter in ("A","E","I","O","U"):
continue
word_without_vowels+=letter
print(word_without_vowels)

user_word =str(input("Enter a Word"))
# and assign it to the user_word variable.
user_word = user_word.upper()
vowels = ('A','E','E','I','O','U')
for letter in user_word:
if letter in vowels:
continue
elif letter == vowels:
letter = letter - vowels
else:
print(letter)

A one liner that does what you need is:
wordWithoutVowels = ''.join([ x for x in userWord if x not in 'aeiou'])
or the equivalent:
wordWithoutVowels = ''.join(filter(lambda x : x not in 'aeiou', userWord))
The code is creating a list containing the letters in the string that are not vowels and then joining them into a new string.
You just need to figure out how to handle the lower/capital cases. You could do x.lower() not in 'aeiou', check if x is in 'aeiouAEIOU', ... you have plenty of choices.

user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in ('A','E','I','O','U'):
continue
print(letter)

word_without_vowels = ""
vowels = 'A', 'E', 'I', 'O', 'U'
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in vowels:
continue
word_without_vowels += letter
print(word_without_vowels)

Related

Infinite loop not checking for string size and belonging to alphabet

I've been trying to make a check for if the input (guesses) belongs to the alphabet and if it's a single character for my simple hangman game, but when I try to run the program it just ignores the entire if sentence. It's been working everywhere else and I just can't find the source of the problem.
Here is my code:
def eng():
letter_list = []
global word
global letter
g = 0
lives = 10
while True:
word = input("Insert The Word: ")
if not word.isalpha():
print("Only letters of the English alphabet are allowed")
else:
print(letter)
break
cls = lambda: print('\n' * 256)
cls()
ready_letters = list(set(word.lower()))
while True:
q = len(ready_letters)
print(q)
while True:
letter = input("Your guess: ")
if not letter.isalpha() and len(letter) != 1:
print("You can make a guess with only one letter of the English alphabet")
else:
break
print(letter_list)
if letter in ready_letters and letter not in letter_list:
letter_list += letter
print("Nice")
g += 1
if g == q:
print(f"The word was: {word}")
print("GG, 🎉🎊")
print("\n")
return
print(f"{g}/{q} letters guessed correctly!")
elif letter in letter_list:
print("You already wrote this letter, try again")
else:
letter_list += letter
print("Oh noie")
lives -= 1
print(f"You have {lives} lives left")
if lives == 0:
print("GG, 웃💀")
return
(read comment)
General tips not related to the issue would also be appreciated.
Thanks for your time!
Simple mistake, instead of using and you should be using or. You want to print our your error message if they type a non-alpha character OR they type more than one letter.

how to replace element in list python 3

I have a list (display) that I need to update as the user does their input. So, if the user input the letter A, I need the letter A to replace an element in the new list called display. I might not be writing this code correctly, but I'm stuck at the code below. I'm not sure how I can write the code to replace the element in the list called display. Any help or guidance would be much appreciated. TIA
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)
display = []
guess = input("Guess a letter: ").lower()
for numChar in range(len(chosen_word)):
display += "_"
for letter in chosen_word:
if letter == guess:
EXPECTED OUTPUT:
If the user input was "a" and the chosen_word is babs, since it has an "a" in it, I need it to replace the list ('', '', '', '') with the corresponding letter. ('', 'a', '', '_')
You're trying to make hangman, aren't you?
Try this:
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)
display = []
guess = input("Guess a letter: ").lower()
if guess == chosen_word:
display = list(chosen_word)
else
for numChar in range(len(chosen_word)):
if numChar == guess[0]:
display.append(numChar)
else
display.append("_")
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)
display = []
guess = input("Guess a letter: ").lower()
display[:] = [guess if x == guess else "_" for x in chosen_word]
Use enumerate to get each letter as well as its index:
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = list(random.choice(name_list))
display = ["_" for _ in chosen_word]
while display != chosen_word:
print(display)
guess = input("Guess a letter: ").lower()
for i, letter in enumerate(chosen_word):
if letter == guess:
display[i] = letter

Python Hangman not ending when player guesses all letters

My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.
import random
import time
name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")
lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"
if start == "y":
print("One game of Hangman comin' right up,",name)
letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
letter = input("Guess a letter: ")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter," ")
guesscomb = "".join(guess)
letter = input("Guess a letter: ")
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:",wrongcount)
letter = input("Guess a letter: ")
elif start == "n":
input("Shame.")
quit()
print("Good Job!")
time.sleep(10)
The thing variable is equal to ___ while lis is always equal to "yet".
guesscomb cannot be equal to thing as you validate a letter when the guess is equal to a letter in lis
You can use print with the parameter end="" so that the cursor don't go new line.
You can use the method isalpha on string to check if it is all characters instead of comparing it with the alphabets.
And as Ben said, thing is always ___
Modify this part of your code, and it will work
if start == "y":
print("One game of Hangman comin' right up,", name)
print("Alright then, ", end="")
# letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
letter = input("Guess a letter: ")
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter, " ")
guesscomb = "".join(guess)
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:", wrongcount)
thing = ''.join(dash)

Python hangman replacing

So I'm writing a hangman program and I'm having trouble getting the current guesses to display as underscores with the correct letters guessed replacing an underscore. I can get the function to work once (thats the insert_letter function) and I know its just replacing every time it goes through the loop, but I can't return the new current without quitting the loop so if someone could offer another way to get the guesses to keep updating that would be great!
def insert_letter(letter, current, word):
current = "_" * len(word)
for i in range (len(word)):
if letter in word[i]:
current = current[:i] + letter + current[i+1:]
return current
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
letter = input("Please enter a letter: ")
while num_guess < incorrect:
letter = input()
if letter in secret_word:
current = insert_letter(letter, current, secret_word)
print(current)
else:
num_guess += 1
current = "_" * len(secret_word)
print(current)
letters_guessed.add(letter)
You didn't show the code for your insert_letter() function so I wrote an alternative -- display_remaining(). Give this a try:
import random, sys
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
while num_guess < incorrect:
letter = input("Please enter a letter: ")
letters_guessed.add(letter)
current = display_remaining(secret_word, letters_guessed)
print(current)
if not letter in secret_word:
print("Incorrect guess.")
num_guess += 1
if not '_' in current:
print("Congratulations! You've won!")
sys.exit(0)
print("Sorry. You've run out of guesses. Game over.")
def display_remaining(word, guessed):
replaced = word[:]
for letter in word:
if (not letter == '_') and letter not in guessed:
replaced = replaced.replace(letter, '_', 1)
return replaced
def read_words(filename):
with open(filename, 'rU') as f:
return [line.strip() for line in f]
if __name__ == '__main__':
play_hangman('words.txt', 6)
NOTE: With this implementation, your words file shouldn't have any words containing the underscore character.

Programming Python vowel counter

I am currently using this code for my program, but I need the program to stop when the user doesn't enter an input. Except I do not know how to do that. Please help. Thankyou!
line = input("Enter a word: ")
vowels = 0
for word in line:
if word == 'a':
vowels += 1 #more than or equal to 1
if word == 'e':
vowels += 1
if word == 'i':
vowels += 1
if word == 'o':
vowels += 1
if word == 'u':
vowels += 1
print (line, "contains", vowels, "vowels ." )
Might I suggest this:
import sys
line = input("enter a word: ").strip()
if not line:
sys.exit(0)
vowels = set('aeiouAEIOU')
numVowels = 0
for char in line:
if char in vowels:
numVowels += 1
print(line, "contains", numVowels, "vowels." )
Here's a more terse version:
import sys
line = input("enter a word: ").strip()
if not line:
sys.exit(0)
vowels = set('aeiouAEIOU')
numVowels = sum(1 for char in line if char in vowels)
print(line, "contains", numVowels, "vowels." )
while True:
line = raw_input('enter a word: ')
if not line:
break
vowels = 0
for word in line:
if word == 'a':
vowels += 1
if word == 'e':
vowels += 1
print (line, 'contains', vowels, 'vowels.')
Here is another way of doing it:
#!/usr/bin/python
vowel = set('aeiou')
while True:
line = input("enter a word: ")
if not line.strip():
break
else:
count = len([x for x in line if x in vowel])
print('%s: contains: %d vowels' % (line, count))
print('Exiting.')
output:
[what_you_got]:[~/script/python]:$ python f.py
enter a word: oh my god
oh my god: contains: 2 vowels
enter a word: really are u kidding me
really are u kidding me: contains: 8 vowels
enter a word:
Exiting.
[what_you_got]:[~/script/python]:$

Categories

Resources