It always make sense to have a plan. In order to make plan we must make inventory i.e. what are the terms and conditions.
- accept only 10 integers on a list
- not accept 3 consecutive odd integers
Now we should try to decompose problem to subproblems and subsolutions.
How translate 'only 10 integers on a list' into Python? Every Python list knows it's length i.e. number of elements. So we can do whatever we need until length of the list is less than ten (note <10. Why so? Because on every iteration we add one value to list and we don't want to add additional item to list which has already 10 items)
- accept only 10 integers on a list
- not accept 3 consecutive odd integers
Now we should try to decompose problem to subproblems and subsolutions.
How translate 'only 10 integers on a list' into Python? Every Python list knows it's length i.e. number of elements. So we can do whatever we need until length of the list is less than ten (note <10. Why so? Because on every iteration we add one value to list and we don't want to add additional item to list which has already 10 items)
nums = [] while len(nums) < 10: ...In order to add items to nums and keep tab on consecutive odd numbers we can write:
consecutive = 0 if num % 2: # if odd consecutive += 1 # add one to counter nums.append(num) else: # if not odd i.e. even nums.append(num) consecutive = 0 # set counter to zeroWe count consecutives, but not taking any action based on that. So we should add condition before we append odd number to list (note that condition is
3 <= consecutive:
and not ==
. Why? Because counter increases before we check it's value, so with consecutively entering odd numbers counter increases and can be more than 3. Counter is reset only if user enters even number) if 3 <= consecutive: print("You can't enter 3 consecutive odd numbers.") else: nums.append(num)And putting it all together:
nums = [] consecutive = 0 while len(nums) < 10: num = int(input('Enter integer: ')) if num % 2: consecutive += 1 if 3 <= consecutive: print("You can't enter 3 consecutive odd integers.") else: nums.append(num) else: nums.append(num) consecutive = 0Note that program crashes if user enters any value which can't be converted into integer.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.