Python Forum
Unable to implement loop count
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unable to implement loop count
#1
Hello all,
I have difficulty trying to count and print number of loops and implement it as solution number.
The codes are below. Any help would be appreciated!

def solutionnames():
    numofsol= input("How many solutions are there?")
    listofnames= []
    loops=0
    for i in range(int(numofsol)):
        loops +=1
        NamesofSol=input("Name of Solution",str(loops))
        listofnames.extend([NamesofSol])
    print(listofnames)
    return(listofnames)

solutionnames()  
Reply
#2
you are going about this the wrong way:
def solutionnames():
    listofnames  = []
 
    while True:
        name = (input("Name of Solution: 'quit' to stop: "))
        if name == 'quit':
            break
        listofnames.append(name)
    return(listofnames)
  
 
if __name__ == '__main__':
    print(solutionnames())
test:
Output:
arz60p@linux-nnem: src:$python ziggy.py Name of Solution: 'quit' to stop: Jeff Name of Solution: 'quit' to stop: Mary Name of Solution: 'quit' to stop: Susan Name of Solution: 'quit' to stop: Glugger Name of Solution: 'quit' to stop: Toff Name of Solution: 'quit' to stop: quit ['Jeff', 'Mary', 'Susan', 'Glugger', 'Toff']
Reply
#3
Hello Larz60+,
Thanks for replying to my request.
However, my desired outcome is
Name of Solution 1: 'quit' to stop: Jeff
Name of Solution 2: 'quit' to stop: Mary
Name of Solution 3: 'quit' to stop: Susan
Name of Solution 4: 'quit' to stop: Glugger
Name of Solution 5: 'quit' to stop: Toff
Name of Solution: 'quit' to stop: quit

The difference is the number input after "Name of Solution". I apologise for not clarifying beforehand.
Reply
#4
Use string formatting:

input("Name of Solution {}: 'quit' to stop: ".format(loops))
Format puts the item passed to it in place of the braces ({}). If you pass it multiple arguments, it can replace multiple braces. And far more complicated stuff.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  While loop that needs to count up ImLearningPython 4 3,024 Dec-17-2018, 02:30 PM
Last Post: ImLearningPython
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,065 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020