Home > front end >  How do I use a for loop to repeat this input?
How do I use a for loop to repeat this input?

Time:01-28

I am having some difficulty understanding for loops. I need this input to be asked 4 times and the output to be shown 4 times as well.

# Take user input
coin_side = input('Heads or Tails ? Type H or T > ')
coin_side = coin_side.upper()

# Generate random number for players
player_1 = random.choice(['H', 'T'])
player_2 = random.choice(['H', 'T'])

print('Player 1 has tossed ', player_1)
print('Player 2 has tossed ', player_2)

if coin_side == player_1:
    print('Player 1 wins')
elif coin_side == player_2:
    print('Player 2 wins')

CodePudding user response:

You can use the for loop:

for _ in range(4):
    # Take user input
    coin_side = input('Heads or Tails ? Type H or T > ')
    coin_side = coin_side.upper()

    # Generate random number for players
    player_1 = random.choice(['H', 'T'])
    player_2 = random.choice(['H', 'T'])

    print('Player 1 has tossed ', player_1)
    print('Player 2 has tossed ', player_2)

    if coin_side == player_1:
        print('Player 1 wins')
    elif coin_side == player_2:
        print('Player 2 wins')

As you said that you're beggining I'll try to break it to you.

For loop syntax looks like this for part in all_:. To this syntax work, the all_ part should be iterable. So for each iteration you will have one piece of the all_ denoated by part that you can work with inside the for loop.

The function range returns a range from 0 to n-1, being n the number that you passed as parameter to the range function.

I won't go deeper into it, but the function range returns a range that is a immutable sequence type. But for the sake of simplicity you can imagine it as list for this example.

So using range(4) would return 0, 1, 2, 3 that are 4 numbers, making using for _ in range(4) iterate 4 times over the code that is inside the loop.

You may have noticed that we are using underscore as the variable on this for loop, this happens because as convention we use underscore when we won't use it inside the for loop.

You may face a situation in the future where you will need the value you are iterate over, so the for loop would look like this foor n in range(4) or for customer in customers

  •  Tags:  
  • Related