I am working on a crash game in python and im trying to make it crash when a value hits 1,50, or 100 but it keeps going. Does anyone know why?
import random
import time
game = 1
num = 1.00
while game == 1:
num += .01
print(round(num, 2))
time.sleep(.1)
if game != 1:
print("Crash!")
break
while game == 1:
crash = random.randint(1, 100)
time.sleep(.1)
if crash == 1 or crash == 50 or crash == 100:
game -= 1
else:
break
In first while loop game's value never changes from 1 therefore never exits the first while loop
BTW you do not have to break the loop because once game != 1 it will won't enter the loop again.
I think you mean to use only the second while loop you have written - so you can delete the first one and remove the else from the second - no need for it for the same reason you do not need the break in the first loop.
so if I understand your intention correctly than the code should be:
import time
game = 1
while game == 1:
crash = random.randint(1, 100)
time.sleep(.1)
if crash == 1 or crash == 50 or crash == 100:
game -= 1
If you're new to computer science, it can sometimes be useful to "play computer" when looking at code. Look at each step of the code and try to imagine what would happen. In a language like python, you can even test these statements one at a time to make sure they do what you think they do.
Let's skip to the important part.
The state of the memory is game and num both equal 1.
while game == 1: # loop until game is not 1
num += .01 # add 0.01 to num
print(round(num, 2)) #print round(num, 2); 1.01 the first time
time.sleep(.1) # sleep for 1 10th of a second
if game != 1: #game was not changed before this point, so game=1
print("Crash!") # this will never execute, ignore it.
break
# End of the loop: execution flow return to the start again, with num=1.01
You see the problem? This will never exit because game is never altered in the loop, this will continue to loop forever. The second loop won't ever even be reached because it's going to be stuck in the first one.
Related
import random
import itertools as it
def guessthenumber():
play = input("do you want to play ?\nanswer yes or no :")
while play != "yes" :
if play == "no" :
quit()
else:
guessthenumber()
break
guessthenumber()
answer = random.randint(1, 5)
def random_func():
gusse = int(input("choose a number between 0 and 10"))
count = 3
while gusse != answer and count != 0 :
count -= 1
print(count)
print("wrong")
random_func()
break
random_func()
print("won")
Why does the guess count stop at 2 even with for loop?
The primary issue is as pointed out by #quamrana. When you call random_func you are adding a new stack frame that has a new count variable initialized to 3, so it immediately decrements, but then you add another call to random_func. You never return and pop this call off the stack, so there is no way to continue.
I don't see why ask if the caller wants to play. If it is the only thing the program does, running it is a pretty good indication. Also, is "gusse" a thing or just a misspelling of "guess".
You should avoid using quit() unless you are in an interpreter. You can use sys.exit, but in simple scenarios like this, returning and finishing the program is more simple.
Consider the following implementation with some slight improvements.
import random
def start(answer, tries):
while tries: # Continue while tries remain.
guess = int(input("choose a number between 0 and 10: "))
if guess == answer:
print("won")
return # Just return from the function.
tries -= 1 # Otherwise, decrement and continue.
print(f"wrong; tries remaining: {tries}")
if __name__ == "__main__":
answer = random.randint(1, 5)
start(answer, 3) # Begin the guessing part of the game.
I am new to python and programming and having difficulty breaking out of a while loop that calls a few functions. I have tried a variety of different options but they all end the same, well they don't end it just keeps running. I am only on here because I have really researched and tried for a long time to fix this. Below is some of the code where you can see there might be confusion with a function. I am not posting the full program just the last part. Thank you for any assistance while I learn. This is also my first time posting, I've been using stackoverflow for the past year dabbling.
def main():
choice = input('''Hello,
Would you like to do basic math or return an average?
Please select 1 for basic math and 2 for average and 3 to quit:
''')
if choice == '1':
print(performCalculation())
elif choice == '2':
print(calculateAverage())
elif choice == '3':
print(main())
j = 0
k = 0
while j < 3:
print(main())
while k == 3:
break
print('All Done!')
Simply change
j = 0
k = 0
while j < 3:
print(main())
while k == 3:
break
print('All Done!')
to
j = 0
while j < 3:
print(main())
j += 1
print('All Done!')
The reason your while loop never breaks is because you have while j < 3:, but you never change the value of j, so if it was smaller to begin with, it will forever be smaller.
Also, k will never equal to 3, and even if it will, the break statement within that while loop will only make that while loop terminate, not the main one.
You have several basic mistakes here. I'll go in order of your program execution.
You aren't incrementing your loop variables.
You've started your loop variables with j and k (why not i and j?) set to zero, and are looped based on the value of these variables. Since they are never incremented, your loop never hits an exit condition.
You can increment the variables with j += 1, and k += 1 at the end of the respective loops.
Your loops are "unpythonic"
These would typically be written as my example below. You don't need to declare i separately, or increment it here. Python handles that for you.
for i in range(0, 3):
...
You're printing a function that doesn't return anything.
Your main function doesn't have a return value, so calling print(main()) is nonsense. You can replace this with simply main() unless you change main() to have some kind of return "foo" statement.
I'm working on a casino program that gets a bet ($1-$50) from the user, then pulls a slot machine to display a three-string combination of "7", "cherries", "bar", or "(space)". Certain combinations will trigger a bet multiplier, and the user will win back this amount. The run should look like this: ask user for bet, show user the pull and their winnings, then ask user for a new bet, display a new pull, and so on.
Right now, I have everything down except for a couple problems - I cannot make it so that the program generates a new random combination for each pull. Secondly, the main loop continues forever, printing the user's pull and winnings forever. Below is the method that generates either "7", "cherries", etc.
def rand_string(self):
random.seed(0)
# produces a number between 0 and 999
test_num = random.randrange(1000)
# precompute cutoffs
bar_cutoff = 10 * TripleString.BAR_PCT
cherries_cutoff = bar_cutoff + 10 * TripleString.CHERRIES_PCT
space_cutoff = cherries_cutoff + 10 * TripleString.SPACE_PCT
# bar = 38%, cherries = 40%, space = 7%, seven = 15%
if test_num < bar_cutoff:
return TripleString.BAR
elif test_num < cherries_cutoff:
return TripleString.CHERRIES
elif test_num < space_cutoff:
return TripleString.SPACE
else:
return TripleString.SEVEN
And here is the loop in main:
while(True):
if bet == 0: #a bet of $0 ends the program
print("Please come again!")
break
else:
print("whirrr...and your pull is " +\
object.pull())
object.display(None)
I thought I could solve this by somehow adding 1 to random.seed() for each loop (we begin with random.seed(0), but for each new pull 1 is added so that random.seed(1) and so on), but I don't know how to go about doing this and I'm not even sure if it's doable. If someone could point out my mistakes here, that'd be great. (sorry if this makes no sense, I'm very new to Python).
You should only call random.seed(0) once in the program. By seeding every time you are reseting the pseudo random number generator and forcing it to produce the same number.
random.seed(0)
while(True):
if bet == 0: #a bet of $0 ends the program
...
You can read more about random seeding here.
I'm a beginner to Python, so this might sound pretty easy.
Anyway, I'm a little confused on when to use break, pass, or continue. I want to have a loop where it breaks out of it, but then after all the code runs again, then the loop will run again. This is some example code:
score = 100
while True:
score + 1
# break, continue, or pass
score - 30
Basically, what I want to happen is have score go up by 1, then have it go down by 30, and then keep going up by 1.
How can I achieve this? Thanks in advance!
score = 100
first = True
while True:
while True:
score += 1
if first:
first = False
break
score -= 30
I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)