1

i have created a script that use user inputs to greet them by hello but it prints the alphabets not the complete name in one sentence. How?

val = input()

for i in val:
    print("Hello", i)

but this prints Hello p Hello r Hello i Hello n Hello c Hello e

8
  • Why did you create a for loop? Don't you just want print("Hello", val)? Commented Jun 14, 2017 at 20:02
  • The loop is doing what it's supposed to, giving you each letter of the string one at a time. Commented Jun 14, 2017 at 20:03
  • Is there any way i can use for loop and input prompt? Just for learning? Print hello prince at one go? Commented Jun 14, 2017 at 20:06
  • There are lots of ways you could combine those two things, but if you don't tell us what you want your program to do, we can't help. Commented Jun 14, 2017 at 20:10
  • there is no program sir, i am learning python, i am on for loop chapter, earlier to that i have done same in def function where function greets whenever user inputs name, so i thought why not in for loop. Commented Jun 14, 2017 at 20:16

1 Answer 1

1

The function input() takes in an input from the command line. For example, if you input prince into the command line, now the variable val has a value of "prince".

With the for loop, you are using the for-each notation. Strings are also a type of iterator--in fact, strings are simply arrays of characters. Think of it like a regular list, but instead of having a list like [1, 2, 3, 4], you have the list ['p', 'r', 'i', 'n', 'c', 'e']. So each iteration of the for loop only prints the character it is currently iterating on.

You could simplify your code by avoiding the for loop and only using the code print("Hello", val).

However, if you only want to practice with for loops, you can use the code below. Try to understand how and why you can simplify it!

val = input()            //stores the user input into val
name = ""                //creates an empty string called name

for s in val:            //iterates through each character in val
    name += s            //adds that character to name
                         //when the for loop ends, the user input is stored in name
print("Hello", name)     //prints "Hello" and the name
Sign up to request clarification or add additional context in comments.

4 Comments

Any way to combine input and forloop to print("hello" val), just for learning
Well this is extremely and unnecessarily overcomplicated haha, but yes, I will edit my response because it is a bit long.
Hi, i am asking bit more, can you please explain it to me also?
Victor C. Thank you so much sir, you made my day. It is great help. You rock sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.