Home > Blockchain >  Python Beginner Question: How to use for/while loop to solve this question?
Python Beginner Question: How to use for/while loop to solve this question?

Time:03-25

Situation:

  • let the user enter a full name
  • with space to separate
  • Can show "Hi" before each "sub-name"

Example:

  • User entered: Zoe Xander Young
  • Expected result: Hi Zoe Hi Xander Hi Young

My question:

How to solve this problem by Python? (Because I'm learning Python and this exercise got from a book)

I'm not sure whether I should indicate the index of space and then slice the full name.

Here's what I did so far:

user_input = "name name name"

for i in range(len(user_input)):
    if user_input[i] == " ":
        index_space = i
        print(i)
        continue
    print(user_input[i], end = " ")

CodePudding user response:

This is a pytonic way of resolving the question with a for loop:

user_input = "Zoe Xander Young"


for n in user_input.split():
    print('hi '   n)

And here is an alternative method using list comprehension:

user_input = "Zoe Xander Young"
[print('hi ' n) for n in user_input.split()]

For both of the above the output would be:

hi Zoe
hi Xander
hi Young
  • Related