Python 3: How to exit loop without stopping function - python-3.x

I am a complete newbie and have tried solving this problem (with my own head and with online research) for the last 5 hours.
Below is a snippet of a function we have written to simulate a game. We want to offer the ooportunity to start a new round - meaning if a player hits "b", the game should start again at the beginning of the range (0, players). But right now it just goes onto the next player in the range (if player 1 enters "b", the program calls player 2)
players = input(4)
if players in range(3, 9):
for player in range(0, players):
sum_points = 0
throw_per_player_counter = 0
print("\nIt is player no.", player+1, "'s turn!\n")
print("\nPress 'return' to roll the dice.\n"
"To start a new round press 'b'.\n"
"Player", player+1)
roll_dice = input(">>> ")
if roll_dice == "b":
player = 0
throw_per_player_counter = 0
sum_points = 0
print("\n * A new round was started. * \n")
I have tried return and break, also tried to put it all in another while-loop... failed. Break and return just ended the function.
Any hints highly appreciated!

you could change the for loop to a while loop. instead of using a range, make player a counter
players = 4
if 3 <= players < 9:
player = 0 # here's where you make your counter
while player < players:
sum_points = 0
throw_per_player_counter = 0
print("\nIt is player no.", player+1, "'s turn!\n")
print("\nPress 'return' to roll the dice.\n"
"To start a new round press 'b'.\n"
"Player", player+1)
roll_dice = input(">>> ")
player += 1 # increment it
if roll_dice == "b":
player = 0 # now your reset should work
throw_per_player_counter = 0
sum_points = 0
print("\n * A new round was started. * \n")

Related

I want to be able to restart my program after a user input error

I am making a program using the python module pypokedex, to make a program that will ask for a pokemon's name, and the generation, and pull up a https://www.serebii.net/ page about it. But, if the user spells a pokemon incorrectly, it just errors and shuts down the program. I want it to restart the program.
I also have it so that if the code succeeded, it will still loop, the problem is when it fails, (again, this is only a problem if the user spells a name wrong)
the reason this:Asking the user for input until they give a valid response doesn't work is because I need to have it be certain words, not a range of numbers.
import pypokedex
import webbrowser
while 1==1:
name = input("What pokemon are you searching for? ")
p = pypokedex.get(name = name)
zero = 3-len(str(p.dex))
if(zero == 2):
num = "00" + str(p.dex)
if(zero == 1):
num = "0" +str(p.dex)
if(zero == 0):
num = str(p.dex)
ngen = input("What generation number are you looking for? ")
if(ngen == str(1)):
gen = "pokedex"
if(ngen == str(2)):
gen ="pokedex-gs"
if(ngen == str(3)):
gen = "pokedex-rs"
if(ngen == str(4)):
gen = "pokedex-dp"
if(ngen == str(5)):
gen = "pokedex-bw"
if(ngen == str(6)):
gen = "pokedex-xy"
if(ngen == str(7)):
gen = "pokedex-sm"
url = "https://www.serebii.net/" + str(gen) + "/" + str(num) + ".shtml"\
webbrowser.open(url , 2)

How to create a watchdog on a program in python?

I want to know is it even possible to create a watchdog on a program,
I am trying to do Discrete event simulation to simulate a functioning machine,
the problem is, once I inspect my machine at let's say time = 12 (inspection duration is 2 hours lets say) if the event failure is at 13-time units) there is no way that it can be because I am "busy inspecting"
so is there a sort of "watchdog" to constantly test if the value of a variable reached a certain limit to stop doing what the program is doing,
Here is my inspection program
def machine_inspection(tt, R, Dpmi, Dinv, FA, TRF0, Tswitch, Trfn):
End = 0
TPM = 0
logging.debug(' cycle time %f' % tt)
TRF0 = TRF0 - Dinv
Tswitch = Tswitch - Dinv
Trfn = Trfn - Dinv
if R == 0:
if falsealarm == 1:
FA += 1
else:
tt = tt + Dpmi
TPM = 1
End = 1
return (tt, End, R, TPM, FA, TRF0, Trfn, Tswitch)
Thank you very much!
basically you can't be inspecting during x time if tt + x will be superior to the time to failure TRF0 or Trfn

Pygame pong ball

Here I give the speed and the direction to the ball
if collision_ball_pad_l == True:
print("ball hit the left pad")
ball_movement = -ball_movement
if first_collision == 0:
ball_movement_y = random.choice([1,-1])*speed
first_collision +=1
If ball hits the edge it must change the direction but it prints me that the speed is 0
if collision_ball_shield_u == True:
print("ball hit the left pad")
ball_movement_y -= ball_movement_y
print (ball_movement_y)
You have to change sign of variable - from + to - or from - to +
You can do it in one line - see - in code
ball_movement_y = -ball_movement_y

The concise 'how many beers' issue?

Where I'm at
I'm trying to figure out how many beers I can buy with 10 RMB after recycling every bottle I get. It's obvious to me that I'm doing something wrong, procedurally, but it's not occurring to me what that is. I'm currently reading "How To Think Like a Computer Scientist: Think Python" on chapter 9. I feel like this should be an easy program for me, but I'm not sure how to loop in the recycling portion of the app. What would be the most concise way to rinse and repeat beer purchases?
The question
Basically, one beer costs 2 RMB. 2 bins gets 1 RMB. 4 caps gets 1 RMB. I'm starting out with 10 RMB. How many beers can I buy (recycling all the bins and caps)?
#5 bottles 5 caps
#= 3 rmb + 1 caps 1 bottles
#6th bottle bought
#= 2rmb + 2 caps
#7th bottle bought
#= 0rmb + 3 caps 1 bottles.
import math
def countbeers(rmb):
beers = 0;
caps = 0;
bins = 0;
bcost = 2;
for i in range (0,rmb):
beers += 1/2
for i in range (0,math.floor(beers)):
caps += 1
bins += 1
rmb = rmb - bcost
for i in range (0,caps):
rmb += 1/4
for i in range (0,bins):
rmb += 1/2
# if rmb > 2 what goes here, trying to loop back through
return beers
print(countbeers(10))
Second attempt
#5 bottles 5 caps
#= 3 wallet + 1 caps 1 bottles
#6th bottle bought
#= 2wallet + 2 caps
#7th bottle bought
#= 0wallet + 3 caps 1 bottles.
import math
global beers
global caps
global bins
global bcost
beers = 0
caps = 0
bins = 0
bcost = 2
def buybeers(wallet):
beers = 0
for i in range (0,wallet):
beers += 1/2
wallet -= 2
return beers
def drinkbeers(beers):
for i in range (0,math.floor(beers)):
caps += 1
bins += 1
wallet = wallet - bcost
return wallet, caps, bins
def recycle(caps, bins):
for i in range (0,caps):
wallet += 1/4
for i in range (0,bins):
wallet += 1/2
return wallet
def maxbeers(wallet):
if wallet > 2:
buybeers(wallet)
if math.floor(beers) > 1:
drinkbeers(beers)
if caps > 4 | bins > 2:
recycle(caps, bins)
return wallet
wallet = int(input("How many wallet do you have?"))
maxbeers(wallet)
if wallet >= 2:
maxbeers(wallet)
elif wallet < 2:
print(beers)
Your main problem is that you are not looping. Every beer you bought from rmb gives you one more bottle, and one more cap. This new bottle and cap might be enough to earn you another rmb, which might be enough for another beer. Your implementation handles this to a limited extent, since you call maxbeers multiple times, but it will not give the correct answer if you give it a truckload of beers, i.e. 25656 bottles.
If you know the number of rmb you have, you can do the calculation by hand on paper and write this:
def maxbeers(rmb):
return 7 # totally correct, I promise. Checked this by hand.
but that's no fun. What if rmb is 25656?
Assuming we can exchange:
2 bottles -> 1 rmb
4 caps -> 1 rmb
2 rmb -> 1 beer + 1 cap + 1 bottle
we calculate it like this, through simulation:
def q(rmb):
beers = 0
caps = 0
bottles = 0
while rmb > 0:
# buy a beer with rmb
rmb -= 2
beers += 1
caps += 1
bottles += 1
# exchange all caps for rmb
while caps >= 4:
rmb += 1
caps -= 4
# exchange all bottles for rmb
while bottles >= 2:
rmb += 1
bottles -= 2
return beers
for a in range(20):
print("rmb:", a, "beers:", q(a))
Then we can buy 20525 beers.

Python while/if statements not working

I am currently learning Python and I am trying to get this game to work. Basically I assigned a word to be guessed and then sliced the word and assigned it to several other variables. Basically, each variable assigned as "letterx" is a letter which makes up part of the string variable word. The problem is getting the while statement with nested if statements to work. For some reason I can't get the guess input to equal letterx. All I get when I run the code is "No." and then the amount of turns left. However, I can't get the elif statement to work. Pretty much everything else works. I'm used to programming in Java and I am fairly new to Python so any tips or help would be greatly appreciated. Thank you for your time and help! Here's the code:
#Guess The Word
word = "action"
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
print("Welcome to Guess the Word!\n")
count = 6
while(count != 0):
guess = input("Take a guess: \n")
if(guess != letter1 or guess != letter2 or guess != letter3 or guess !=
letter4 or guess != letter5 or guess != letter6):
count -= 1
print("No.\n")
print("Turns left: \n", count)
elif(guess == letter1 or guess == letter2 or guess == letter3
or guess == letter4 or guess == letter5 or guess == letter6):
count -= 1
print("Yes.\n")
if(count == 0):
print("Your turns are up, what do you think the word is?")
guess = input("The word is...: \n")
if(guess == word):
print("You win! That's the word")
elif(guess != word):
print("Sorry, you lose.")
Here's the program running in the Python shell:
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Welcome to Guess the Word!
Take a guess:
a
No.
Turns left:
5
Take a guess:
c
No.
Turns left:
4
Take a guess:
t
No.
Turns left:
3
Take a guess:
i
No.
Turns left:
2
Take a guess:
o
No.
Turns left:
1
Take a guess:
n
No.
Turns left:
0
Your turns are up, what do you think the word is?
The word is...:
action
You win! That's the word
Let's say guess equals letter1. Then even though
guess == letter1, the first condition is still True since guess != letter2. And similarly, no matter what guess is, there is some letter (amongst letter1, letter2, etc.) which it is not equal.
So the first if condition is always True.
Instead, you could use
while(count != 0):
guess = input("Take a guess: \n")
if not guess in word:
count -= 1
print("No.\nTurns left: \n", count)
else:
count -= 1
print("Yes.\n")
By the way, it should be entirely possible to code the game without defining letter1, letter2, etc. All this code should be deleted:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
Just use word[0] in place of letter1, and word[1] in place of letter2, etc.
And note you may not even need word[0], word[1]. For example,
with Python you can use
guess in word
instead of
guess in (word[0], word[1], word[2], word[3], word[4], word[5])
It's not only a lot less typing, it is more general, since guess in word does the right thing with words of any length.

Resources