Python Forum
name.split() + (And) + print question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: name.split() + (And) + print question (/thread-36746.html)

Pages: 1 2


RE: name.split() + (And) + print question - Coricoco_fr - Mar-26-2022

for display:
>>> out = ["Bob", "Alice"]
>>> print(f"Hello {' and '.join(out) if out else 'stranger'}")
Hello Bob and Alice
>>> out.pop()
'Alice'
>>> print(f"Hello {' and '.join(out) if out else 'stranger'}")
Hello Bob
>>> out = []
>>> print(f"Hello {' and '.join(out) if out else 'stranger'}")
Hello stranger
>>> 



RE: name.split() + (And) + print question - sklord - Mar-26-2022

(Mar-26-2022, 02:53 PM)deanhystad Wrote: Your latest question is how do you print "Hello Bob!" or "Hello Bob & Alice!" depending on if you have 1 name or 2 names (or "Hello Stranger!" if there are no names). Or am I way off base?

Assuming I am correct, are you allowed to use str.join()? That might be helpful.

You do not need to cover all possible combinations in your logic. You only have three possibilities:
If no names print "Hello Stranger!"
If one name print "Hello name!" replacing name with the actual name.
if more than one name print "Hello name0 and name1!" replacing name0 and name1 with actual names. This last case can be extended to any number of names > 1.

Collecting the names can be easily done if you know all the possible names.
names = []
for word in input("Hello! ").split():
    if word in ("Bob", "Alice"):
        names.append(word)

Thats interesting! I am trying to wrap my head around .join() , i understand what it does but i cant figure out how to apply it to your idea of the code!
how would i add ".append" the names into the variable "word" , so it basically prints out the demanding names?

Basically I am on day 5 learning python as my first language, i am going to become a front end webbapp developer in JavaScript/Typescript with react as my first job. But i wanted to use python as a back end for my long journey as a developer and i know python will be very useful in my career.. I am sitting like 6-10 hours a day trying to learn now. So i am just messing around and figure things out as they come. So i am allowed to use anything.

Learning alot from this thank you guys!


RE: name.split() + (And) + print question - deanhystad - Mar-26-2022

names = ['Bob', 'Carol', 'Ted', 'Alice']
print(f"Hello {' & '.join(names)}!")

names=["Alice"]
print(f"Hello {' & '.join(names)}!"))
Output:
Hello Bob & Carol & Ted & Alice! Hello Alice!