简体   繁体   中英

Resetting a Variable to its Initial Value

Is there a way to reset a value to its initial state. For example, if a=5 and then throughout the program a-=1 continuously until a=0. How would I reset the program so a=5 again?

Variables don't remember their initial (or any previous) value. You'll need to store that somewhere else.

initial_a = 5
a = initial_a
...
a = initial_a if a == 0 else a - 1
...

You might, however, want a generator that produces an infinite stream of repeating values.

import itertools
a_values = itertools.cycle([5,4,3,2,1,0])
a = next(a_values)  # a == 5
a = next(a_values)  # a == 4
a = next(a_values)  # a == 3
a = next(a_values)  # a == 2
a = next(a_values)  # a == 1
a = next(a_values)  # a == 0
a = next(a_values)  # a == 5
# etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM