Python program won't append more than one value - python-3.x

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)

Related

If condition is "None" the loop starts somewhere else than I want

I try to code my first little text based role play game.
The first step would be to enter your character name and then type "y" if you are fine with the name and "n" if you want to change the name.
So I want that the Program is asking you again to enter "y" or "n" if you fatfinger a "g" for example. And only let you reenter your name if you type "n"
Instead of these the program will let you reenter your name directly if you enter "g".
I already tried to do a "while True or False" loop around the _yesorno function.
Here is the code:
main.py
from Classes.character import character
from functions.yesorno import _yesorno
#character
char = character()
while True:
print("please enter a name for your character")
char.set_name(input())
print("Your name is: " + char.name + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
if _yesorno(input()):
break
else:
continue
_yesorno.py
def _yesorno(input:str)->bool:
if input == "y":
return True
elif input == "n":
return False
else:
print("please use y for yes and n for no")
return None
As I am pretty new I would be happy, if you can explain your answer newbie friendly and not only with "your logic is wrong" :D
Thanks in advance!
if None is equal to while if False. Python have dynamic typing for types.
To check wrong input you can do things like:
def _yesorno(input_:str)->bool:
while input_ not in ['y', 'n']:
print("please use y for yes and n for no")
input_ = input()
return input_ == 'y'
That code check input directly instead itself. input_ not in ['y', 'n'] that part check if your input_ is one of array element.
After user enter 'y' or 'n' the function return proper result.
I would approach this with a pair of recursive functions. One that ran until the user gave a valid response, the other until a name was properly set.
Note that in many cases, recursive functions can be rewritten as loops and since python lacks tail call optimization, some people will prefer not using recursion. I think it is usually fine to do so though.
def get_input_restricted(prompt, allowed_responses):
choice = input(prompt)
if choice in allowed_responses:
return choice
print(f"\"{choice}\" must be one of {allowed_responses}")
return get_input_restricted(prompt, allowed_responses)
def set_character_name():
prospective_name = input("Enter a name for your character: ")
print(f"Your name will be: {prospective_name}.")
confirmation = get_input_restricted("Are you happy with your choice (y|n)? ", ["y", "n"])
if "y" == confirmation:
return prospective_name
return set_character_name()
character_name = set_character_name()
print(f"I am your character. Call me {character_name}.")
The reason why an input of 'g' is making the user reenter their name is because 'None' is treated as False therefore the loop will continue... you could try a simple if statement in a while loop and disregard your _yesorno function with
while(True):
print("please enter a name for your character")
charName = input()
while(True):
print("Your name is: " + charName + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
yesorno = input()
if(yesorno == 'y' or yesorno == 'n'):
break
if(yesorno == 'y'):
break
char.set_name(charName)
print("and your name is {0}".format(char.name))

limiting the number of character

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: ")

Returning to my if statement

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.

Option to save output printed on screen as a text file (Python)

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

cannot fix this "else" statement error

the second "else" statement gives a syntax error. I don't understand why. what is wrong with the code?
Pardon me, still a beginner
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break
You can see in the Python 3 flow control documentation an example of an if statement. It can only have one else statement because that is what is run when all other cases (if and elif) didn't match. When are you expecting the second else to run?
As was pointed out in another answer, indentation in python matters.
Is this perhaps the indentation you are looking for?
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break

Resources