Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - Assistance with while loops

In the below code I would like the counter to remain on 0 rather than go into negative figures when one of the stock hits 0 which continuing to count the other items down.

cheese = 1
sausage = 3
tomato = 3

while cheese > 0 or sausage > 0 or tomato > 0:
  print("Cheese stock:")
  print(cheese)
  print("Sausage stock:")
  print(sausage)
  print("Tomato stock:")
  print(tomato)
  cheese -=1
  sausage -=1
  tomato -=1

I totally understand why this runs to negative numbers - the "or" operator means that it will do so however if I use the "and" operator it will only run once, understandably so.

question from:https://stackoverflow.com/questions/65857455/assistance-with-while-loops

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use conditional statement to achieve this:

cheese = 1
sausage = 3
tomato = 3

while cheese > 0 or sausage > 0 or tomato > 0:
  print("Cheese stock:")
  print(cheese)
  print("Sausage stock:")
  print(sausage)
  print("Tomato stock:")
  print(tomato)
  if cheese > 0:
      cheese -=1
  if sausage > 0:
      sausage -=1
  if tomato > 0:
      tomato -=1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...