How to have 3 random objects spawn on 3 places - python

The goal is having random objects spawn on 3 positions once .
the code works and looks like this but with more if statements and 3 small stataments:
if mainloop != 3:
if smallloop1 != 1:
if randomnumber == x:
object.goto(x, y)
mainloop += 1
smallloop += 1
the problem is that the if statement doesnt stop so multiple objects spawn
im also not getting any error messages
I tried changing the if statements to while loops which didnt change anything except having to stop them with the break command or using a list instead of a random number which made the thing more complicated and again didnt change anything
Thanks in advance
Edit: small reproducible example:
if bigloop < 1:
if mediumloop1 < 1:
if random1 == 1 or 2 or 3:
print("first loop")
bigloop += 1
mediumloop1 += 1
if random1 == 4 or 5 or 6:
print("first loop")
bigloop += 1
mediumloop1 += 1
The problem is that it prints "first loop" twice.

Related

Is there a way to not give a point if they get it wrong the first time, quiz, python

I am new to python and am doing a basic quiz. I'm running into a problem for scoring.
trials = 3
for i in range(trials):
ans_2 = ansTwo()
results.append(ans_2)
if ans_2 in ('c','C'):
print("Good Job",name)
score+=1
break
else:
remaining = trials-i-1
s = '' if remaining == 1 else 's'
print("Oops Try Again? [{0} Chance{1} Remaining]".format(remaining, s))
This is my code and I'm trying to make it that if they do not get the answer the first time they do not get any points, but if they get the answer the first time they get a point.
Just add an if statement before score += 1 that checks if the loop is running for the first time. In your case:
if i == 0:
score += 1

While Loop Counter Confusion

I'm working with while loops and I'm just a bit confused on how to break out of it in the way that I want. So I've nested a for loop within a while loop:
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
for x in range(7):
y += 1
print('test')
The output that I'm looking for is 5 tests printed out and one break. However, every time I run the program it prints out 7 tests before it goes to the break. I'm not exactly sure, but I think I'm just confused about something within while loops! If someone could explain this to me please let me know :) I have found ways around this, but I'd like to get an understanding of why it doesn't work.
This is because it's performing the entire for loop within the while loop therefore y will become 7 before it checks again. Removing the for loop will resolve this.
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
y += 1
print('test')
y = 0
while y < 5:
print("test")
y += 1
print("break")
Would work.
There is no point in having another variable like "x" for the while loop when it allows for you to set the condition directly.
Because inner loop will complete before the next iteration of the outer loop. I.e. once the inner loop starts it does all 7 iterations before starting the next iteration of the while loop.
You can do this by just using one loop. Print out “test” increase counter and put in an if condition to break when counter is 5.
The reason 7 tests print rather than 5 is that your entire for loop is executed before you go back to the beginning of your while statement. I think your understanding is that, after one iteration of a for loop, you go back to the beginning of the while loop, but this is incorrect: your for loop is executed completely before going back to the beginning of the while loop.
After you step into the for loop, you increment y 7 times and print test 7 times. y is now >= 5, and you go back into your if statement. The if statement turns x false, thereby "turning off" the while loop, and a break statement is printed. If you just want to print out 5 tests and one break, it would be much easier to simplify your code as such:
y = 0
while True:
if y < 5:
print('test')
y += 1
else:
print('break')
break
Try
i = 0
while True:
if i == 5:
break
print('test')
i = i + 1

Python Programming for the Absolute Beginner: chapter 3 ERROR

So in this book chapter 3 subsection "Creating Intentional Infinite Loops" author gives this example:
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
But it doesn't work. It only spits out break-outside-loop and continue-not-properly-in-loop errors. From what I've read break/continue can't be used to break out of an if - it can only break out of loops, and that I should use sys.exit() or return. The question arises, what the author meant, and why he made this -basic?- mistake? Or maybe it isn't a mistake and I'm missing something.
Could you help me grasp this concept of break/continue function with fairly similar and simple example? :)
Indentations matter in python. So it must be,
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
Cuz you miss-indented it, so do:
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
So the lines:
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
Got all a extra tab, so it becomes:
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
Note: even if you remove break and continue, there will be still a problem, it will be an infinite loop.

Coin Acceptor With Python Timer

I'm having trouble figuring out this code. I am currently making a script in python where a it's kind of how an arcade machine works when you have 30 seconds to continue and you can insert more coins to go again. The trouble I'm having is I cant get the coins to count up while the timer counts down. Here is my code so far:
while True:
start = GPIO.input(startBtn)
input_state = GPIO.input(counterPin)
if input_state == False:
coins += 1
print(str(coins) + "¢ inserted")
time.sleep(0.09)
if coins == 100:
coins -= 100
creditss += 1
print("You currently have: " +str(creditss) + " credits")
timer = creditss * 5
if start == False:
if creditss > 0:
print("You have: " +str(timer) + " minutes to play!")
print("Have Fun!")
x = timer
for i in range(x + 1):
time.sleep(1)
print(formatTime(x))
x -= 1
timer -= creditss * 5
creditss = 0
if timer == 0:
pause()
timer += 30
print("Continue? : Insert more money to keep playing!")
x = timer
if input_state == False:
coins += 1
print(str(coins) + "¢ inserted")
time.sleep(0.09)
else:
for i in range(x + 1):
time.sleep(1)
print(formatTime(x))
x -= 1
if coins == 100:
coins -= 100
creditss += 1
print(creditss)
if creditss > 0 & timer != 0:
print("Good")
pause()
else:
print("exit")
os.system('/home/pi/exit.sh')
Thanks for any help!
Okay...the best help I can give you is this:
At this point you need to refactor your code. When you get a program with more than two - three levels of nesting (you have four if statements nested) then you should be defining functions and splitting out different parts of your program into logical chunks. This makes debugging easier, as you can drop I/O print statements to see where your script is failing.
To help you know what to split out first - look for sections where you're repeating yourself. If you type it more than once, it deserves its own function (DRY Principle - Don't repeat yourself).
for example you have:
if coins == 100:
coins -= 100
creditss += 1
print("You currently have: " +str(creditss) + " credits")
timer = creditss * 5
and
if coins == 100:
coins -= 100
creditss += 1
print(creditss)
This functionality is extremely similar and can likely be split off into a function. The other thing you want to think about: You only want /one/ part of the program to be able to change the number of coins so that you know when you're calling it what's happening (explicit is better than implicit). That should be a function and anything that needs to operate it can call it. The easier your program is to read, the easier it will be to debug. At least until you get issues that silently fail.
The sleep function stops execution, so during countdown every time you sleep you stop checking the GPIO state for a whole second and then just check it once more until sleeping again for another second. For this strategy to work you need to be checking your input very fast as to not miss a fast event. My guess is that checking once every one second is probably not enough for what you are doing.
A sightly better solution would be to not sleep and to use time.clock() to check when the play time has ended. So when the game starts you store the current value of time.clock() and after that you continue checking it until enough time has elapsed. There could still be an input which unsets and sets your input pin faster your loop can detect it so it's not bulletproof.
I don't have experience with python on raspberry-pi but a quick google search shows me there are GPIO.add_event_detect() and GPIO.add_event_callback() functions which can be set up so a callback function is called on a GPIO pin state change, which I would guess relies on interrupts so that you wouldn't miss an event. It could be a good idea to look into that.

How to add to a variable outside of the loop so that it remembers

I am making a program where a car will accelerate by 5 or decelerate by 5 every time they input a "1" for accelerate, a "2" for decelerate, or a "3" to exit.
My problem is that the way that I have it setup at the moment is that it doesn't remember the speed after it goes through the loop once.
This is what I have at the moment:
def main():
speed = 0
question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit:"))
while question == 1:
speed = speed + 5
print("Car speed:", speed)
main()
while question == 2:
speed = speed - 5
print("Car speed:", speed)
main()
if question == 3:
print("done")
main()
How do I make it remember the speed?
Don't call main() again. Keep one while loop that checks that the entered value is not 3 for exiting:
question = 0
while question != 3:
# do checks for non-exit values (1 and 2) here
question = int(input("Enter ..."))
When you call main again, you have a new namespace, and are declaring new variables within that. Your values are saved, just just not where you think they are.
Alternatively, don't call your function again
def main():
speed = 0
while True:
question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit:"))
if question == 1:
speed = speed + 5
elif question == 2:
speed = speed - 5
elif question == 3:
print("done")
break
print("Car speed:", speed)
Why use recursion? You just need a while cycle, right?
def main():
speed = 0
question = 0
while question != 3:
question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit:"))
if question == 1:
speed = speed + 5
print("Car speed:", speed)
if question == 2:
speed = speed - 5
print("Car speed:", speed)
if question == 3:
print("done")
print("Final speed is", speed)
main()
As they mentioned in the comments, what happens is that you are calling main in each case. Therefore the environment of main is a totally new var environment where speed was set to 0 as in the second line of your code.
For your particular problem I think recursion is note necessary. However, if you would like to use it, then you must pass speed as a parameter.
You can create a function in which you do your calculations then return the final speed.
Beware, your code may break if the user enter non integer value. This is why in my example i'm using a try...except to catch the error without breaking the processing.
Also, beware that with this actual algorithm, the final speed can have a negative value, which is incorrect. You should add a test for this case to handle this issue.
def get_speed(speed = 0):
while 1:
try:
# Here your program may crash and can give an error of type ValueError
# This is why i'm using try ... except to catch the exception
question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit: "))
if question == 1:
speed += 5
elif question == 2:
speed -= 5
elif question == 3:
print("done")
print("Car speed: ", speed)
return speed # Return and save your speed
break
except ValueError:
pass
# You can initialize your begenning speed
# or use the default speed which is equal to 0
# NB: output_speed will store the returned speed
# if you need it for further calculations
output_speed = get_speed()

Categories

Resources