Home > OS >  Python: How can I assign names different messages while iterating through a list?
Python: How can I assign names different messages while iterating through a list?

Time:07-20

Is there a way I can assign names different messages when iterating through a list?

E.g.:

Names = [Owen, Sophie, Max, Karen, Zedd]

Wished output:

Hello, Owen!
Hello, Sophie!
Hello, Max!
Hello, Karen!
Good morning, Zedd!

CodePudding user response:

This is very simple. Just separate your names into different lists and then apply if conditions like this.

Names = ['Owen', 'Sophie', 'Max', 'Karen', 'Zedd']

Hello_Names = ['Owen', 'Sophie', 'Max', 'Karen']
Good_Morning_Names = ['Zedd']

for name in Names:
    if name in Hello_Names:
        print(f'Hello, {name}!')
    elif name in Good_Morning_Names:
        print(f'Good Morning, {name}!')

If you want this assigned at random you can do this:

import random
Names = ['Owen', 'Sophie', 'Max', 'Karen', 'Zedd']

for name in Names:
    k = random.choice([0, 1])
    if k==0:
        print(f'Hello, {name}!')
    else:
        print(f'Good Morning, {name}!')

CodePudding user response:

use an if statement in a for loop.

    Names = ("Owen", "Sophie", "Max", "Karen", "Zedd")

for name in (Names):
    if name == "Zedd":
        print("Good Morning, "  name   "!")
    else:
        print("Hello, "  name  "!")
  • Related