I am trying to add the character value of the ord function, from a user input. I am able to get it to print out the value of each letter but I am stuck on adding up the entire value for the word the user inputs.
Here is what I have so far:
def main():
key_word = "quit"
word = ""
while word != key_word:
word = input(str("Enter a word: "))
word = word.lower()
for letter in word:
value = ord(letter)
character = value - 96
print(character)
if word == key_word:
print(end="")
main()
Are you asking for the sum of the ord values?
If so:
key_word = "quit"
word = ""
total = 0
while word != key_word:
word = input(str("Enter a word: "))
word = word.lower()
for letter in word:
value = ord(letter)
total += ord(letter)
character = value - 96
print(character)
if word == key_word:
print(end="")
print(total)
You want adds up the value of each letter of the word :
while word != key_word:
word = input(str("Enter a word: "))
word = word.lower()
word_value = 0
for letter in word:
value = ord(letter)
character = value - 96
word_value += character
print(character)
print('Total word value', word_value)
if word == key_word:
print(end="")
Related
I tried to make a simple version of the hangman game. But when I run it, I can't add the letters in order.
The 'count' variable may be the problem. Any can help me ?
Thank you! :)
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
count = 0
while word != p2:
letter = input("enter a letter: ")
if letter in word:
for x in word:
if x == letter:
p2[count] = letter
#print("cont: ", count)
else:
continue
count+=1
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
Well i wasn't able to understand your point of view about the Hangman but following code is the optimized form of your code and also the my playing interpretation of this game e.g. how this should be played
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
while word != p2:
letter = input("enter a letter: ")
if letter in word and letter not in p2:
locations = [i for i, x in enumerate(word) if x == letter ]
for location in locations:
p2[location] = letter
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
print('You LOST' if lives == 0 else 'You WON')
Screenshot of the Both Executions of the game (Win & Loss)
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)
I am trying to create a program that asks for a word input until '' is entered. Then the program will print out all of the words joined in a sentence. Then take the first letter of each word to make an acrostic. I am using python. Example shown below. Thank you in advance. This is due really soon. :)
What I have coded:
sentence = []
acrostic = []
word = -1
while word:
sentence.append(word)
acrostic.append(sentence[0].upper())
print(sentence)
print("-- {}".format(acrostic))
What I want the code to do:
Word: A
Word: cross
Word: tick
Word: is
Word: very
Word: evil
Word:
A cross tick is very evil
-- ACTIVE
For input:
in a loop, ask the user a word, if it nothing just stop
if it's a word, save it in sentence and it's first letter in acrostic (word[0] not sentence[0])
For output:
for the sentence join the words with a space : " ".join(sentence)
for the acrostic, join the letters with nothing : "".join(acrostic)
sentence = []
acrostic = []
while True:
word = input('Please enter a word, or enter to stop : ')
if not word:
break
sentence.append(word)
acrostic.append(word[0].upper())
print(" ".join(sentence))
print("-- {}".format("".join(acrostic)))
Gives
Please enter a word, or " to stop : A
Please enter a word, or " to stop : cross
Please enter a word, or " to stop : tick
Please enter a word, or " to stop : is
Please enter a word, or " to stop : very
Please enter a word, or " to stop : evil
Please enter a word, or " to stop :
A cross tick is very evil
-- ACTIVE
python 3.8 or later
sentence = []
acrostic = []
while user_input := input('word: '):
sentence.append(user_input)
acrostic.append(user_input[0].upper())
print(' '.join(sentence))
print(f"-- {''.join(acrostic)}")
output:
word: A
word: cross
word: tick
word: is
word: very
word: evil
word:
A cross tick is very evil
-- ACTIVE
python 3.6 and 3.7
sentence = []
acrostic = []
while True:
user_input = input('word: ')
if not user_input:
break
sentence.append(user_input)
acrostic.append(user_input[0].upper())
print(' '.join(sentence))
print(f"-- {''.join(acrostic)}")
python 3.5 or earlier
sentence = []
acrostic = []
while True:
user_input = input('word: ')
if not user_input:
break
sentence.append(user_input)
acrostic.append(user_input[0].upper())
print(' '.join(sentence))
print('-- {}'.format(''.join(acrostic)))
Maybe you're looking for something like this:
sentence = []
acrostic = []
word = -1
while word != "":
word = input("Word: ")
if word:
sentence.append(word)
acrostic.append(word[0].upper())
print(" ".join(sentence))
print("-- {}".format("".join(acrostic)))
Goal: To extract first letter of each word untill '' is entered.
acrostic = ""
sentence = ""
while(True):
word = input("enter a word= ")
if(word!=''):
acrostic+=word[0].upper()
sentence+=word+" "
else:
break
print(sentence)
print(acrostic)
With your sample input;
enter a word= A
enter a word= cross
enter a word= tick
enter a word= is
enter a word= very
enter a word= evil
enter a word=
output
A cross tick is very evil
ACTIVE
While everybody has you covered for basic loops, this is a nice example to use the iter(callable, sentinel) pattern:
def initial():
return input('Word: ')[:1]
print('-- ' + ''.join(iter(initial, '')))
Will produce:
Word: A
Word: cross
Word: tick
Word: is
Word: very
Word: evil
Word:
-- Active
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.
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]:$