How to add tuples and print them out? [duplicate] - python

This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 2 years ago.
How would you implement the addition of tuples so that for every incorrect answer, it adds the answers to the tuple and prints them out for the user to check and see their previous guesses? I attempted multiple things, but they only served to replace the word within the tuple.
import random
words = ("blueberries", "intelligence", "reactor", "thorns", "nightmare",
"scars", "metal", "coronavirus", "industries", "heart", "workshop",
"assistant", "bots")
variable = random.choice(words)
beg = variable[:1]
end = variable[-1:]
length = len(variable)
name = input("Hello USER. Please input your name into the console.")
print("Hello " + name + ". Today, we will be playing a word guessing game. I will be giving you the first and last letter along with the length of the word. You must guess what the word is based on these clues.")
print("1st Letter: " + beg)
print("Last Letter: " + end)
print("Length of word: " + str(length))
guess = input("What is your guess?")
while variable != guess:
if guess != variable:
guess = input("Your answer is incorrect. Please try again.")
elif guess == variable:
break
print("Congratulations, you have guessed correctly.")

I think using a list is a better choice. Because tuples are immutable. That means for adding an item to a tuple, you should create a new tuple. But lists are more dynamic and you can add items to the lists simpler and better.
So you can just use the following code:
previous_choices = []
# Other codes
if guess != variable:
previous_choices.append(guess)
print(previous_choices)
But if you want to use tuples for some reasons, you can use the following code:
previous_choices = tuple()
# Other codes
if guess != variable:
previous_choices += (guess,) # In fact, every time a new tuple creates here.
print(previous_choices)
Also, I think it's better to change the way you are getting the first and last characters. You can simply use variable[0] for your beg variable and variable[-1] for your end variable.

You do not need to add the wrong guess but what you need is you need to concatenate them. And for that I initialised a list and then appending the wrong guesses in that list since tuples are immutable. However if you need the results in tuple then in the end you can convert the list in tuple. I have done few changes in the code. please check it.
words = ("blueberries", "intelligence", "reactor", "thorns", "nightmare", "scars", "metal", "coronavirus", "industries", "heart", "workshop", "assistant", "bots")
import random
variable = random.choice(words)
beg = variable[:1]
end = variable[-1:]
length = len(variable)
name = input("Hello USER. Please input your name into the console.")
print("Hello " + name + ". Today, we will be playing a word guessing game. I will be giving you the first and last letter along with the length of the word. You must guess what the word is based on these clues.")
print("1st Letter: " + beg)
print("Last Letter: " + end)
print("Length of word: " + str(length))
guess = input("What is your guess?")
wrong_guess=[]
while variable != guess:
if guess != variable:
wrong_guess.append(guess)
guess = input("Your answer is incorrect. Please try again.")
print("wrong guesses till now are:",wrong_guess)
elif guess == variable:
break
print("Congratulations, you have guessed correctly.")

Related

why does the index of "list_of_letters" not update for every while loop with "guessed_letter_string"? The problem occurs in the Try: section

Hangman. As you probobly understand i am new to coding and python, sorry for bad code.
The best way i can think of to describe this problem is through the following way: In the "try:" section i try to index = list_of_letters.index(guesssed_letter_string). i want to check if the guessed_letter_string is in list_of_letters: i earlier in the code translate the input from well the only input() in the code to guessed_letter_string (its the same thing). when you input a letter in the middel of the word it works like index[3] but when you input the first letter in the word the index locks at 0 and every other letter replaces it. is there a way to fix this
import random
list_of_words = ["mom", "dad", "sister", "brother"]
random_word = random.choice(list_of_words)
list_of_letters = list(random_word)
print(random_word)
print(list_of_letters)
rounds_failed = 1
rounds_max = 16
list_of_letters_guessed = []
under_grejer = []
count_of_right_letters_list = []
print(f"You have {rounds_max - rounds_failed} rounds left to find out the word")
for every in list_of_letters:
under_grejer.extend("_")
while True:
if rounds_failed == rounds_max:
print("To many attempts, no more rounds")
break
if len(list_of_letters) == 0:
print("YOU FUCKING WON")
break
print(f"This is round: {rounds_failed}")
print(" ".join(under_grejer))
print("Letters that are correct(not in order): "+", ".join(count_of_right_letters_list))
print("List of letters guessed: "+", ".join(list_of_letters_guessed))
guess = input("NAME A Letter: ")
guess_letters_list = (list(guess))
guess_count_letters = len(guess_letters_list)
if guess_count_letters > 1:
print("Dummy you just need to input a letter, nothing else")
guesssed_letter_string = " ".join(guess_letters_list)
try:
index = list_of_letters.index(guesssed_letter_string)
print("Congrats you got the letter: " + guesssed_letter_string)
print(f"thats the {index + 1}nd letter in the word")
rounds_failed += 1
count_of_right_letters_list.extend(guesssed_letter_string)
print(index)
list_of_letters.pop(index)
under_grejer[index] = guesssed_letter_string
except ValueError:
print("try again mate that letter was not in the word")
list_of_letters_guessed.append(guesssed_letter_string)
rounds_failed += 1
continue
It's not about the first letter only. Your problem is that with list_of_letters.pop(index) you remove the guessed letter form list_of_letters; parts of your code rely on this to check if you guessed all occurrences of that letter before already, but on the other hand this reduces the index of all letters behind the guessed one for later iterations.
For example, for brother, if you guess r it correctly says position 2, but if you then guess o next, it again says position 2 because your list_of_letters now reads ["b","o","t","h","e","r"].
You could either try to work with list_of_letters_org = list_of_letters.copy() which you will never change, and pick the right one for every task, or you could for example change the program structure by adding a list of booleans that store which letters were guessed already.

How can I tell the program only a certain type of input its allowed? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Im working on a program that asks the user to enter input twelve times. Those inputs must be included in a list in which there are included the first twelve letters of the alphabet.
letters=("A","B","C","D","E","F","G","H","I","J","K","L")
def gen_():
s = []
for i in range(1, 13):
in_ = input("Input the note number " + str(i) + ", please\n", )
if in_ in letters:
s.append(in_)
print(" \n"+str(s)+"\n " )
else:
print("not valid")
gen_()
I would like to tell the program that if a certain input is not valid, it should ask the user to try again and enter a valid input on that same instance. I tried setting "i" back to the value in which the input was not valid, by subtracting 1 to i, but it didnĀ“t work.
How can I code this? Thanks
You need a while loop to continuously verify if the entered input is valid. Please check this solution:
def gen():
s = []
for i in range(12):
in_ = input("Input the note number {i}, please: ".format(i=i))
while len(in_) != 1 or ord(in_) < 65 or ord(in_) > 76:
in_ = input("Invalid input, please enter again: ")
s.append(in_)
return s
I made some tweaks in the while loop to check for the ASCII values of the character entered instead of looking in a predefined tuple/list.
The reason why subtracting 1 from i probably didn't work is because python doesn't work like other programming languages where you can modify the index variable inside the for loop and it will react accordingly. To put it very simple since I don't want to get into details, any changes you make to i inside the loop won't change what value i will have in the next iteration.
One way to do what you're trying to do is to write a while loop that repeats as long as the user is giving an invalid input. Something like this:
in_ = input("Input the note number " + str(i) + ", please\n", )
while in_ not in letters:
print("not valid")
in_ = input("Input the note number " + str(i) + ", please\n")
s.append(in_)
print(" \n"+str(s)+"\n " )

Why doesnt my Code work? (Simple "Guess the Word"-Game in Python) [duplicate]

This question already has an answer here:
Python "if" statement not working
(1 answer)
Closed 4 years ago.
I'm learning Python for fun at the moment, and it went all well until now. I'm trying to extend the "Guess the Word"-Game, for example being able to let the Player choose a Word by himself (when 2 People play, 1 chooses the Word, the other guesses) I bet that my Mistake is obvious to me as soon as you point it out, but I'm gonna ask anyway. Well, here is the Code. I put in the entire Program, even tough only the top part should matter. I just put in the rest because it isn't much and maybe you guys can understand it better then.
print("Do you wish to set the Word yourself, or let the program choose?")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == 1:
Keyword = input("Type in the Word you want to use!")
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter!")
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
My problem is, I wanna add the Function to be able to choose if you want to set a Word yourself, or use the word the Program has, defined as "Keyword". But no matter what I input, it always starts with "Guess a Letter" instead of skipping down to where the program sets the Keyword. Thank you in advance for your answers! :)
There's 2 issues with your code.
You put the entire block of code into the else statement. This means that if the if user_input == 1: block ever executed, you would only ask your user for a word and then the program would end because the else statement would be skipped.
You are using if user_input == 1: as your check and this will never be true because user inputs are always read in as strings. A string 1 will never equal the integer 1. This is why your program always skips to the else statement. You need to do if int(user_input) == 1:
Whenever you collect a user's input using the input function, it is a string, not int. this means you will have to either parse the value into an int or evaluate it with a string.
option 1: parsing to int:
user_input = int(input("1 for own Input - 0 for Program-Input"))
option 2: evaluating with string:
if user_input == "1":
input returns a string not a integer so it can never be equal to 1 instead it will be equal to "1".
Plus the code for the user guessing only runs when the program chooses the word so it needs to be unindented.
As a side note your code currently registered capital letters as being different from lower case, you can fix this by putting a .lower() after each input which will turn all capital letters into lowercase.
print("Do you wish to set the Word yourself, or let the program choose?: ")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == "1":
Keyword = input("Type in the Word you want to use: ").lower()
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter: ").lower()
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')

How to get out of my while loop [duplicate]

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 6 years ago.
So my issue with my code is that even though I have enter the correctly guessed word, my code still reads it as incorrect; therefore, asks me to try again. How do I get out of this loop? Appreciate it.
import random
count = 1
word = ['orange' , 'apple' , 'chicken' , 'python' , 'zynga'] #original list
randomWord = list(random.choice(word)) #defining randomWord to make sure random
choice jumbled = ""
length = len(randomWord)
for wordLoop in range(length):
randomLetter = random.choice(randomWord)
randomWord.remove(randomLetter)
jumbled = jumbled + randomLetter
print("The jumbled word is:", jumbled)
guess = input("Please enter your guess: ").strip().lower()
while guess != randomWord:
print("Try again.")
guess = input("Please enter your guess: ").strip().lower()
count += 1
if guess == randomWord:
print("You got it!")
print("Number of guesses it took to get the right answer: ", count)
randomWord.remove(randomLetter)
This line removes every letter from your variable.
you can use:
randomWord2 = randomWord.copy()
for wordLoop in range(length):
randomLetter = random.choice(randomWord2)
randomWord2.remove(randomLetter)
jumbled = jumbled + randomLetter
This will copy your variable. If you wont do this your result will be two names for the same variable.
And you compare a list with a string try this instead:
while guess != ''.join(randomWord):
It will convert your list back into a string.

Checking through a variable to see if it doesn't contains anymore strings

def main():
#word = input("Word to guess for player 2:")
word = ['h','e','l','l','o']
word2 = "hello"
#make a list of _ the same length as the word
display =[]
for i in range (0,len(word)):
display.append("_")
chances = int(input("Number of chances to guess word:"))
if len(word)== 11:
print ("Your word is too long. It has to be 10 charecters or less")
else:
word = word
if chances < len(word):
answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
if answer == "no":
chances= int(input("Number of chances:"))
else:
chances = chances
("Ok then lets continue with the game")
print ("Player 2, you have {0} chances to guess the word.". format (chances))
won = False
underscore = False
while chances > 0 and won == False and underscore == False:
guess = input("Enter your guess: ")
gC=False
for i in range (0,len(word)):
if guess == word[i]:
gC=True
display[i]=guess
if not gC:
chances = chances - 1
display2 = ""
for i in display:
display2 = display2 + i + " "
For some reason the code doesn't work when I state my while loop as the game continues to go on until the user runs out of guess'. Does anybody have any suggestions as to how I can fix this?
You never set won to True when the user wins the game by guessing all the letters.
This is not an answer to your original question, instead more of a code-review, but maybe you'll find it useful.
word = list('hello') # replaces manual splitting of string into letters
display = [ '_' ] * len(word) # replaces build-up using for-loop
chances = input("Number ... ") # already returns int if the user enters an int
# but will evaluate any valid python expression the
# user enters; this is a security risk as what
# ever is done this way will be done using your
# permissions
chances = int(raw_input("Number ...")) # probably what you wanted
...
else:
word = word # does nothing. remove this line and the "else:" above
chances -= 1 # replaces 'chances = chances - 1' and does the same
display2 = ' '.join(display) # replaces the for-loop to build display2
Furthermore I suggest to use better names. Variables like display2 or gC aren't very helpful in this context. In professional programming you always have to keep in mind that you are writing your code (also or even mainly) for the next developer who has to maintain it. So make it readable and understandable. Choose names like displayString or guessedCorrectly instead.

Categories

Resources