I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
if ans=='Q':
print("Now I'll see if I can break your score...")
break
A couple of changes mean that only an R or r will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:
myScore = 0
while ans := input("Roll...").lower() == "r":
# ... do something
else:
print("Now I'll see if I can break your score...")
Related
I am using The Big Book of Small Python projects to increase my skills in python, and on the very first project, which is making a simple logic game, On the first try, the code goes all the way however if you get it wrong you it won't run properly.
Here is the code and a description of the game, the while loop with chances is supposed to run for the whole game, until you run out of chances, the second while loop is supposed to run in case user enters below or more than length three for the number
import re
import random
#In Bagels, a deductive logic game, you
#must guess a secret three-digit number
#based on clues. The game offers one of
#the following hints in response to your guess:
#“Pico” when your guess has a correct digit in the
#wrong place, “Fermi” when your guess has a correct
#digit in the correct place, and “Bagels” if your guess
#has no correct digits. You have 10 tries to guess the
#secret number.
choice_of_nums=['123','345','674','887','356','487','916']
random_three_num=random.choices(choice_of_nums)
count_bagel=0
count_fermi=0
Chances=10
while Chances!=0:
guess = input(f'Guess the three digit number! You have {Chances} to guess! ')
while len(guess)!=3:
guess=input('You must choose a three digit number! Try again! ')
for i in range(0,len(random_three_num)):
if guess==random_three_num:
print('YOU WIN! Well done')
break
elif guess[i] not in random_three_num:
count_bagel+=1
if count_bagel==len(random_three_num):
print('Bagels')
Chances=Chances-1
elif guess[i]==random_three_num[i]:
count_fermi+=1
Chances=Chances-1
print('Fermi')
elif guess in random_three_num:
print('Pico')
import random
choice_of_nums = ['123', '345', '674', '887', '356', '487', '916']
random_three_num = random.choice(choice_of_nums)
count_bagel = 0
count_fermi = 0
chances = 10
while chances > 0:
guess = input(f'Guess the three digit number! You have {chances} to guess! ')
while len(guess) != 3:
guess = input('You must choose a three digit number! Try again! ')
while not guess.isdigit():
guess = input('You must choose integer values! ')
number_is_present = any(number in guess for number in random_three_num)
if guess == random_three_num:
print('YOU WIN! Well done')
chances = 1 # combined w/ the last line, chances will become = 0
elif not number_is_present:
print('Bagel')
else:
index_is_right = False
for i in range(len(guess)):
if guess[i] == random_three_num[i]:
index_is_right = True
if index_is_right:
print('Fermi')
else:
print('Pico')
chances -= 1
(06/28/22) added chances = 1 if the guess is right, so to exit the while loop
random.choices returns a list
you don't need the re module
use snake case as suggested in PEP8
The break after print('YOU WIN! Well done') exits the for loop not the while loop. Put Chances = 0 before the break:
if guess==random_three_num:
print('YOU WIN! Well done')
Chances = 0
break
You should never check a while loop with a condition like x != 0. Always use <= or >=. The reason being, that if somehow the number zero is skipped and you end up at -1 then the loop will still exit.
Couldn't your check if guess==random_three_num: be done before the for loop? Then the break statement would actually break the while loop. Now it's only breaking the for loop. This is one reason that could lead to a infinite loop.
Your second to last line elif guess in random_three_num: should probably be elif guess[1] in random_three_num:.
Chances=Chances-1 could probably be outside the for loop also, as the number of chances should decreasing only one per guess. Currently the number of chances decreases up to 3 times during the for loop (every time you hit 'Fermi'). This could lead to issue described in "1."
I have tried to figure out a way on how to restart my code in Python, but I can't get it to work properly.
if keepLooping == True:
if userInput == randomNumber:
if attempt == 1:
print()
print("Correct, First try!")
stop = time.time()
print("It took", int(stop - start), "seconds.")
replay = input("Do you want to play again?: ")
if replay.lower() in ("yes"):
print()
os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv) # Restart code. You are here
elif replay.lower() in ("no"):
break
else:
print("Invalid input, Yes or No?")
continue # Restart segment. You are here
replayAttempt += 1
print()
As you can see, I have tried using os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv). Sure, it works, but then one of my inputs turn red, as you can see here. I have been trying to solve this but I can't find a solution.
I found a solution for the text being red, I added '\033[37m' before my inputs. The only problem I have now is that it can only restart once. When I try it again I get this error code here.
One way to this is to encapsulate thing into function
going from this
#start of scrip
#... game logic
#end of script
to
def game():
#...game logic
game()
encapsulated like this allow for easier reuse of stuff, and allow you to reduce repetition, if you do same thing in your code two or more times that is when you should factor that out into its own function, that is the DRY principle, Don't Repeat Yourself.
You can do something like this for example
def game():
#...game logic
return game_result
def main():
done=False
result=[]
while not done:
result.append( game() )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
#display the result in a nice way
main()
Here the main function do a couple of simple thing, play one round of the game, save the result, ask if you want to play again and display the result, and the game function do all the heavy work of playing the game.
Here is a simple working example of guess the number between 0 and 10
import random
def game(lower,upper):
answer = str(random.randint(lower, upper))
user_answer = input(f"Guess a number between {lower} and {upper}: ")
game_result = user_answer == answer
if game_result:
print("you win")
else:
print("you lose, the answer was:",answer)
return game_result
def main(lower=0,upper=10):
done=False
result=[]
while not done:
result.append( game(lower,upper) )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
print("Your result were",sum(result),"/",len(result) )
main()
Notice that the game function take 2 arguments, so you can play this game not just with 0 and 10, but any two number you desire, in turn the main function also take those same arguments but assign them default value so if you don't call this function with any of them it will use those default value and use them to call the game function, doing so allow for flexibility that you wouldn't have if you lock it to just 0 and 10 in this case.
(the sum(result) is because boolean are a subclass of int(numbers) so in math operation they are True==1 and False==0)
Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1
This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.
I have created a program where the user can select a certain sided dice then it rolls and outputs the number generated, it then asks if the user wants to roll again and by using a while loop. i have wrote the program and for some reason it keeps on repeating the input dice side number prompt and i don't know why, here is the code
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
I suspect it is something to do with the while loop or the indentation, but I have been fiddling with it for like 3o mins and i cant get it to work properly, so if someone could help me out here it would be appreciated, Thanks !
The indentation on else: roll_agn=input is such that it only runs after you exit the while loop - but the while loop can never end until you run the else clause, therefore infinite loop.
Here is a cleaned-up, better-structured version:
# assumes Python 3.x
from random import randint
def get_int(prompt):
while True:
try:
return int(input(prompt)) # if Python 2.x use raw_input instead of input
except ValueError:
# not an int
pass
def get_yn(prompt):
while True:
value = input(prompt).strip().lower() # if Python 2.x use raw_input instead of input
if value in {'y', 'yes'}:
return True
elif value in {'n', 'no'}:
return False
def roll(sides):
return randint(1, sides)
def main():
while True:
sides = get_int("Number of sides on die (4, 6, or 12)? ")
if sides in {4, 6, 12}:
print("You rolled a {}".format(roll(sides)))
else:
print("U no reed gud?")
if not get_yn("Play again (y/n)? "):
print("Thanks for playing!")
break
if __name__=="__main__":
main()
It looks like you have indentation problems with the if statements. Try lining up elif with if.
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))