Python output not showing what i want it to show

Question:

phone = input("Phone: ")
digits_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for ch in phone:
    output += digits_mapping.get(ch, "!") + " "
    print(output)
exit()

input: 1345

output:

One 
One Three 
One Three Four 
One Three Four ! 

need output to show
one three four !

Asked By: Mirco Susan

||

Answers:

Simply remove the print statement from the for loop and put it at the end of the loop instead.

phone = input("Phone: ")
digits_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for ch in phone:
    output += digits_mapping.get(ch, "!") + " "
print(output)
exit()

Your code is printing the output for every number, instead of once at the end. I hope I could help!

Answered By: SimplyDev

Try this:

phone = input("Phone: ")
digits_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for ch in phone:
    output += digits_mapping.get(ch, "!") + " "
print(output)

In your original code, you are printing output every time something is appended to it. Instead, you want to print it once your loop is finished appending text to output.

You also do not need exit(). It is implied at the end of your program. As a comment on your answer cites from documentation, you should also not use exit() or quit() outside of the interpreter. It is unidiomatic because it breaks code flow.

Answered By: Michael M.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.