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
Related
I found an error that says
File "", line 6, in
TypeError: not all arguments converted during string formatting"
while I'm trying to implement a while True loop in Python. I am trying to identify even and odd numbers with Python. Any suggestion for my problem?
Here's my code:
print("Identification Odd/Even number")
while True:
input = input ('Enter The Number ')
if input %2==0:
print("Even")
elif input %1==1:
print("Odd")
next_step = input ('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break
else:
print('You have input the wrong format')
The first thing you should not do is, that mixing variable names with function names. The line input = input('Enter number here: ') means that in the first pass the function input() will no longer be the function you want it to be, instead it will be string you got back from the first loop-pass.
Also you want to go on with some calculations. input (the function) will return a string, not an integer.
In order to get an integer from a string you should do a cast user_input = int(input('Enter number here: ')).
user_input is a integer and you can go on with you modulos operations.
So all in all I suggest based on your code:
change the variable name input to something else
do a cast after retrieving the user first user-input
for checking if a given number is odd or even there are only two cases to cover, which you can express with if-else-case.
input % 1 == 1 will always be False because there is no integer that is not divisible by 1.
If you want to continue to ask the user if he wants to go on, you probably want the user to give an answer you specified.
This will need another while-loop.
Why?
If the user gives an arbitrary answer, you want to continue to ask as long as the user gives an apropriate answer.
This is an answer you explicitly asked for.
To do that I have done something like this:
next_step = None
allowed_answers = ['No', 'Yes']
while next_step not in allowed_answer:
next_step = input('Want to go on? (Yes/No)')
If you want to give feedback to the user, something like this solved this riddle for me:
allowed_answers = ['No', 'Yes']
while True:
next_step = input('Want to go on? (Yes/No)')
if next_step not in allowed_ansers:
print('You have input the wrong format')
else:
break
All in all I would do something like this:
allowed_answers = ['No', 'Yes']
while True:
user_input = int(input('Enter The Number:'))
if user_input % 2 == 0:
print("Even")
else:
print("Odd")
next_step = None
while next_step not in allowed_answer:
next_step = input('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break
I'm trying to build a guessing game in Python. You have a limited number of around 5 guesses/lives and if you run out of them, you will lose the game. (for reference: it uses both random(for random number) and termcolor(for color) modules)
Program:
from termcolor import colored
import random
def lostit():
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
while decideto not in ("yes", "no"):
decideto = input(colored("Invalid response:", "red"))
if decideto is "yes":
guessnum()
elif decideto is "no":
print("Bye, bye.")
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 0 # Chances
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
print(colored("Great job! You guessed it!", "green"))
So far, it works when you type in the right number. However, I've experienced problems with the lives/guesses part. I've tried to set a limit to how many tries the player has, however the program seems to ignore this, meaning the player basically has infinite lives. How do I solve this?
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
should likely be indented.
This is also strange. You don't have a variable called lostit, but you have a loop with that variable:
while lostit not in ("yes", "no"):
The logic on your code is simply wrong. See this loop:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
You are looping while the guess isn't equal to number you selected.
I would reorg. Main function defines the number to guess, how many guesses they get, it loops while two things are true (guess isn't equal to number and guess count is less than total number of guesses). Also note the scope of variables.
from termcolor import colored
import random
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 1 # Chances, but they already used a guess
while (usernum != numtoguess) and (guesses >= usertries):
again = input("Try again? (yes/no):")
while again not in ("yes", "no"):
again = input(colored("Invalid response choose yes/no:", "red"))
if decideto is "yes":
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1
elif decideto is "no":
print("Bye, bye.")
return
if usernum == numtoguess:
print(colored("Great job! You guessed it!", "green"))
if guesses >= usertries:
print(colored("Sorry! You lost!", "red"))
Take a look at this section:
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
First of all, your if and elif are not mutually exclusive: let's say guesses is equal to usertries. It will enter to first if (since you use >=) and not the second elif (because it entered the first one). In other words, Elif code is not reachable.
Seoncd, your while loop is inside the if. It keeps running until you guess the right number, and only then compare your guess with "lives". You should substitute the statements to check the lives inside the loop:
while guesses >= usertries:
usernum = input(colored("Wrong! Guess again: ", "red"))
if usernum != numtoguess:
usertries += 1
# User is wrong. We add one to our counter
else
# user is right. Do something to break the loop
# When we reach here, we ended loop: means user lost
lostit()
The logic is: as long as user has guesses, ask him for another number. compare the number: if he is right, do something. else, keep loop.
I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))
Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')
I'm trying to create a word guessing game, after each guess the computer should return the frequency of letters in the right place, however it is this part that I have been unable to manage to get working. Can anyone help me?
import random
def guess(secret,testWord):
return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))
words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0
print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)
words = words.split('\n')
WordToGuess = random.choice(words)
GameOn = True
frequencies = []
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('Congragulations, You Won!')
GameOn = False
else:
print(correctLength, '/', len(WordToGuess), 'correct')
if Guesses >= 4:
GameOn = False
print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
In your guess function, you are printing the value, not returning it. Later, however, you try to assign something to correctLength. Just replace print by return, and your code should work.
Update to answer question in comments:
I think a very easy possibility (without a lot of changes to your code posted in the comment) would be to add an else clause, such that in case that the input is empty, you return directly to the start of the loop.
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
if len(currentguess) <=0:
print('Sorry you must enter a guess')
else:
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('statement')
GameOn = False
elif Guesses <= 0:
GameOn = False
print('statement')
else:
Guesses = Guesses -1
print('statement')
print('statment')