I'm making a simple python survival game and I want one day to pass every five turns (so every time x hits a multiple of 5, y = 1 + 1). Is there a simple way to do this?
Asked
Active
Viewed 147 times
-2
-
Yes, the key word is "modulo operator". – Sergio Tulentsev Sep 14 '20 at 18:43
-
sergio tulentsev, could you give me example code using my situation? – Ethen Dixon Sep 14 '20 at 18:47
-
In ruby it'd be `days += 1 if turns % 5 == 0`. I leave it to you to translate this to python. It should turn out largely the same. – Sergio Tulentsev Sep 14 '20 at 18:50
-
Does this answer your question? [Modulo operator in Python](https://stackoverflow.com/questions/12754680/modulo-operator-in-python) – Pranav Hosangadi Sep 14 '20 at 18:54
1 Answers
0
Try below:
y=0
for x in range(50):
if x > 0 and x % 5 == 0:
y+=1
print ('x', x)
print ('y', y)
Explanation:
for x in range(50)
: Will iterate value of x from 0 to 49if x > 0 and x % 5 == 0
: Checks if x is greater than 0 (you can remove this), and checks if x modulo 5 is zeroy += 1
: Will increment value of y by 1

Pranav Hosangadi
- 23,755
- 7
- 44
- 70

Homer
- 424
- 3
- 7
-
`for x in range(50)` does not _print_ anything. `if x > 0` is unnecessary, just start `range` at 1. – Pranav Hosangadi Sep 14 '20 at 18:56
-
I am printing x in the second last line. x > 0 is totally optional, depending on user's requirement. – Homer Sep 14 '20 at 19:00
-
1. Right. Your explanation says "for x in range(50): --> Will print value of x from 0 to 49". `for ...` _iterates_ over those values, it doesn't print anything. 2. Having an `if` in every iteration to filter out something that could be done by just changing the range of iterations instead is not efficient code. – Pranav Hosangadi Sep 14 '20 at 19:05