Home > Enterprise >  Python output not showing what i want it to show
Python output not showing what i want it to show

Time:09-22

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 !

CodePudding user response:

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!

CodePudding user response:

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.

  • Related