i would like to know how to put limit on how many character can player put
thinking to limit it by one letter per answer.
it's a guessing game but the computer can only answer yes or no.
five chances to guess a letter.
then need to guess the right word after 5 tries.
import random
words = dict(
helium = "type of element",
korea="a country in asia",
peugeot="brand of a car",
bournemouth="a good place for holiday")
word=list(words)
choice=random.choice(word)
x=list(choice)
score=0
chance=5
print("\n\n\t\t\t WELCOME TO GUESSING GAME")
print("\t\t\tYOU HAVE 5 CHANCES TO GUESS THE WORD")
print("\nit has a", len(choice),"letters word")
print("and this is a clue", (words[choice]))
while word:
guess = input("is there a letter :")
if guess in choice:
print("yes")
else:
print("no")
score +=1
if score == chance:
print("time to guess the right word")
guess = input("and the word is :")
if guess == choice:
print("well done you guess the right word which is ", choice.upper())
break
else:
print("better luck next time the right word is ", choice.upper())
break
Hope this is what you want:
First you should make a new function:
def own_input(text=""):
user_input = ""
# While the length of the input string is not 1
while len(user_input) != 1:
# Ask user for input with message
user_input = input(text)
Now you can use it like this:
a = own_input("Character: ")
Related
This may sound like a stupid question but I had to ask. The following code checks whether a word entered by the user is a palindrome or not. When I use the below code, it says "This word is a Palindrome" for all the words.
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
k-=1
b=True
else:
b=False
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
But when I do this small change in the next block of code, it correctly detects whether the word is palindrome or not. I got this in a trial and error basis.
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
b=True
else:
b=False
k-=1
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
Please help. Thanks in advance.
At the moment, some of the issue is that your "final" answer is based on the "last" test. What you really want to do is say "Not a Palindrome" as soon as you determine that and then stop.
Try:
is_a_palindrome = True
for index in range(len(word)):
if word[index] != word[- (index+1)]:
is_a_palindrome = False
break
Note as well, that this can be technically simplified to:
is_a_palindrome = word == "".join(reversed(word))
I am creating a guess a letter game in python. the program chooses a random word from a file and the user has the amount of letters to guess the letters to the word. There is one part I am having trouble coding. I need to display the word as dashes and after every guess change the dashed word to include the correctly guessed letters in their corresponding position. So the output looks something like this.
Welcome to Guess a Letter!
Your word has 10 letters
You have 10 incorrect guesses.
Here is the word:
Enter a letter: e
Awe, shucks. You missed with that letter
Enter a letter: a
You got a hit! Here's what the word looks like now:
-------a-a
Enter a letter: o
Awe, shucks. You missed with that letter
Enter a letter: u
Awe, shucks. You missed with that letter
Enter a letter: i
You got a hit! Here's what the word looks like now:
---i---a-a
Enter a letter: y
You got a hit! Here's what the word looks like now:
-y-i---a-a
Enter a letter: t
You got a hit! Here's what the word looks like now:
-y-i-t-ata
Enter a letter: l
You got a hit! Here's what the word looks like now:
ly-i-t-ata
Enter a letter: s
You got a hit! Here's what the word looks like now:
lysist-ata
Enter a letter: r
You got a hit! Here's what the word looks like now:
lysistrata
You won!
Great job!
so here is what i have so far
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = ""
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word = hidden_word + "-"
print(hidden_word)
list(hidden_word)
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
hidden_word.join(' ')
print(hidden_word)
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
Just need help with what is in the game() function
Since strings a immutable, I would use a list to keep track of the guesses and then transfer that to a string in order to print it out. Here is your code modified to reflect those changes :
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = []
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word.append ("-")
print_out = ''
print(print_out.join (hidden_word))
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
print_out = ''
print(print_out.join (hidden_word))
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
I group all functions into one so we don't need to declare global variables. I also add something:
use .lower() to accept uppercase input
a statement telling user how many guesses left
win and lose condition
import random
def game():
# pick_word_from_file()
# using with to close the file automatically
with open("wordlist.txt") as f:
wordlist = f.readlines()
word = random.choice(wordlist).strip("\n")
# game_intro()
print("Welcome to Guess a Word!\n")
print("Your word has", len(word), "letters")
# why we need to say incorrect guesses from the start?
# print("You have", len(word), "incorrect guesses.")
# dashed_word()
# use a list to save letters because string is immutable
hidden_word = ["-" for w in word]
print("".join(hidden_word))
# number of guesses equal to length of word
for guesses in range(len(word)):
# tell user how many guesses left
print(f"You have {len(word) - guesses} guesses left.")
# use .lower() so user can also input uppercase letter
guess = input("Please enter a letter as your guess: ").lower()
change = False
for i in range(len(word)):
if word[i] == guess:
hidden_word[i] = guess
change = True
if change:
print("You got a hit! Here's what the word looks like now:")
print("".join(hidden_word))
else:
print("Awe, shucks. You missed with that letter.")
if "".join(hidden_word) == word:
print("You won! Great job!")
break
# you lose when you are out of guesses
else:
print("You lose.")
game()
Output:
"""
Welcome to Guess a Word!
Your word has 10 letters
----------
You have 10 guesses left.
Please enter a letter as your guess: E
Awe, shucks. You missed with that letter.
You have 9 guesses left.
Please enter a letter as your guess: A
You got a hit! Here's what the word looks like now:
-------a-a
You have 8 guesses left.
Please enter a letter as your guess: O
Awe, shucks. You missed with that letter.
You have 7 guesses left.
Please enter a letter as your guess: U
Awe, shucks. You missed with that letter.
You have 6 guesses left.
Please enter a letter as your guess: I
You got a hit! Here's what the word looks like now:
---i---a-a
You have 5 guesses left.
Please enter a letter as your guess: Y
You got a hit! Here's what the word looks like now:
-y-i---a-a
You have 4 guesses left.
Please enter a letter as your guess: T
You got a hit! Here's what the word looks like now:
-y-i-t-ata
You have 3 guesses left.
Please enter a letter as your guess: L
You got a hit! Here's what the word looks like now:
ly-i-t-ata
You have 2 guesses left.
Please enter a letter as your guess: S
You got a hit! Here's what the word looks like now:
lysist-ata
You have 1 guesses left.
Please enter a letter as your guess: R
You got a hit! Here's what the word looks like now:
lysistrata
You won! Great job!
"""
Whenever I try to append(guesses) to the all_guesses variable it seemingly replaces the existing value from the previous loop. I want the program to record down all the player's number of guesses per game round but it only record the most recent value. I made sure the variable isn't in the while loop so that it doesn't overwrite it, so what's wrong? I'm really new to python programming so I can't seem to figure this out. Each time I run the loop the guessed and all_guesses values are reset to their original.
This is a snippet of my program:
def main():
guesses = 0
guessed = []
all_guesses = []
guess = input('\nPlease guess a letter: ').lower()
letter = 'abcdefghi'
answer = random.choice(letter)
while len(guess) != 1 or guess not in letter:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ')
while len(guess) < 2 and guess in letter:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
else:
if guess == answer:
guesses = guesses + 1
played = played + 1
print("\nCongratulations, that is correct!")
replay = input('Would you like to play again? Type y/n: ').lower()
all_guesses.append(guesses)
The short answer would be that all_guesses needs to be a global defined outside of main and the replay logic also needs to wrapped around main.
You seem to be missing logic, as you never modify guessed but expect to find things in there. And there are dead ends and other missing parts to the code. As best as I can guess, this is roughly what you're trying to do:
from random import choice
from string import ascii_lowercase as LETTERS
all_guesses = []
def main():
guessed = []
answer = choice(LETTERS)
guess = input('\nPlease guess a letter: ').lower()
while len(guess) != 1 or guess not in LETTERS:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ').lower()
while len(guess) == 1 and guess in LETTERS:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
continue
guessed.append(guess)
if guess == answer:
print("\nCongratulations, that is correct!")
break
guess = input("\nIt's not that letter. Try again: ").lower()
all_guesses.append(len(guessed))
while True:
main()
replay = input('Would you like to play again? Type y/n: ').lower()
if replay == 'n':
break
print(all_guesses)
This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the while statements. Any advice would be appreciated.
print('Welcome to Word Madness!!')
vowels = list('aeioyu')
consonants = list('bcdfghjklmnpqrstvwxz')
wordCount = 0
complete = False
while not complete:
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
print('You chose to enter: ',str(mode))
#When user chooses to quit program will system exit
if mode == 'quit':
print('Sorry to see you go! Come back to Word Madness soon!')
import sys
sys.exit(0)
#If vowels are selected then they will be counted
if mode == 'vowels':
word = input('Please enter your word!')
number_of_vowels = sum(word.count(i) for i in vowels)
print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice == 'n':
averageV = int(number_of_vowels // wordCount)
print('Your average number of Vowels was: ',averageV)
print('Thank you for using Word Madness!')
complete = True
else:
mode = 'vowels'
#If consonants are selected then they will be counted
elif mode == 'consonants':
word = input('Please enter your word!')
number_of_consonants = sum(word.count(i) for i in consonants)
print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
#If user has no more words to enter then they are given an average
else:
mode == 'consonants'
else:
print('ERROR! INVALID INPUT DETECTED!')
From your question and the comment, I assume that you want to ask
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
only once. If that is the case, you can move that statement just above the while loop.
Or also, you can give an option whether user really wants to specify the mode again.
Ok,for what I understood you don't know how to go back in the code. For this you should learn how to use functions in Python.
What is a function?
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. (Definition taken from internet)
So I would suggest you to find more about functions, because it's very useful.
After learning functions you should add that:
After every
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
Add
elif choice == 'n':
function()
Function() --> Calling the main function.
Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break