Home > Enterprise >  Python: How to alternate between two values/strings depending on user input
Python: How to alternate between two values/strings depending on user input

Time:07-03

I am a beginner in python so bear with me with the question. I want to know that how we can alternate between two values such as [1,2,1,2,.....] or [yes, no , yes , no,....] based on the numbers of user inputs, which in this case the users input is 4, which creates a list of 4 values. Thank you in advance

CodePudding user response:

A list comprehension will do that for any type of list, numbers or strings.

n = int(input()) 
lst = ['Yes', 'No']
[lst[i % len(lst)] for i in range(n)]

CodePudding user response:

def alternate(x, y, n):
    a = n * [x]
    a[1::2] = n//2 * [y]
    return a

print(alternate(1, 2, 4))
print(alternate('yes', 'no', 5))

Output:

[1, 2, 1, 2]
['yes', 'no', 'yes', 'no', 'yes']

Try it online!

CodePudding user response:

Something like this, maybe?

n = 5     # it's your user input < 
words = ['yes', 'no']

for i in range(n):
    print(i % 2   1)             # 1 2 1 2 1
    print(f' {words[i% 2]} ')   # yes no yes no yes  - each in sep. line

Or you prefer functional way:

from itertools import count, cycle

ct = count(1)             # infinite count, specify starting 1

n = 5

for x  in cycle(['yes', 'no']):
    print(x)
    
    if next(ct) == n:
       break

CodePudding user response:

A list comprehension solves your issue nicely.

pattern = [1, 2]

lst = [pattern[i % len(pattern)] for i in range(int(input()))]

It also scales nciely to accommodate patterns of more than two values.

>>> pattern = [1, 2, 3]
>>> [pattern[i % len(pattern)] for i in range(int(input()))]
5
[1, 2, 3, 1, 2]
>>> 
  • Related