Python Forum
Adding string numbers, while loop and exit without input.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding string numbers, while loop and exit without input.
#1
Python 3.7 / PySripter x64
So my homework requires that I write a program that asks the user to enter a series of single digit numbers with nothing separating them. The program will display the sum of all the single digits in the string. For example, if user enters 2514 the program should display 12, which is the sum of 2, 5, 1, 4.

The program will loop continuously and prompt the user:
"Enter a sequence of digits with nothing separating them (no input terminates):"

in order to terminate the loop no input should be made and an EOFError should raise and be dealt with an exemption that will terminate the program with a message that reads:
***Program has completed successfully***

I am suppose to have at least two functions:
main()
stringTotal(string) # main calls stringTotal() passing the string

Here are a couple of my attempts:


def main():
    user_string = input('Enter a sequence of digits with nothing separating '
'them (no input terminates): ')

    # Create header + what program does.
    print ('Welcome to the Sum of the Digits Program \n\n'
'This program will sum the digits of an input string.')



    while user_string != '':         # I've tried other variations in my while loop other then a sentinel
        total = 0                    # but I haven't had any luck yet 
        for num in user_string:
            numbers = int(num)
            total += numbers

        print ('The sum of input string', user_string, 'is:', total)

        user_string = input('Enter a sequence of digits with nothing separating '
'them (no input terminates): ')



# Call strinTotal() passing the string.
def stringTotal(string):
    pass
main()
def main():
    # Create header + what program does.
    print ('Welcome to the Sum of the Digits Program \n\n'
'This program will sum the digits of an input string.')

    num = int(input('Enter a sequence of digits with nothing separating '
'them (no input terminates): '))

    # Create an empty list.
    string = []

    end = ''

    while end != '':
        # Get a number and added to the list.
        num = int(input('Enter a sequence of digits with nothing separating '
'them (no input terminates): '))
        string.append(num)

        num = int(input('Enter a sequence of digits with nothing separating '
'them (no input terminates): '))

    print ('The sum of input string', string, 'is:', stringTotal(string))


def stringTotal(string):                                 
    total = 0
    for num in string:
        numbers = int(num)
        total += numbers

    return total

main()
Output:
This is an example of how the output should look like: Welcome to the Sum of the Digits Program This program will sum the digits of an input string. The sum of input string [2514] is: 12 The sum of input string [123456789] is: 45 *** Program has completed successfully***
I don't think I'm successfully creating a list. Part of the problem for me is that the way I understand it, that list has to be made with a continuous loop that doesn't end unless no input is given in the prompt screen when you press enter.
Reply
#2
First: Please do not use variable names like "string". Thus your variables may hide an internal. Choose meaningful mames like "list_of_digits".

Second:
(Apr-12-2020, 01:24 AM)Jose Wrote: num = int(input('Enter a sequence of digits with nothing separating '
But you do not want an int() here. You want a string of digits. So remove the int().

Third:
    end = ''
    while end != '':
        ...
This while loop will not execute. It will not even start the first loop.

Does that help you?
Reply
#3
Maybe some problem solving techniques should be applied before coding?

If I understand correctly:

- ask user input
- output calculation based on user input or a message


Subproblems can be defined:

- how to ask user input
- how to convert numbers in string format into integers
- how to sum integers
- how to output message

I would write a pseudocode (as this is homework I ignore some of the requirements):

# ask user input
# iterate all symbols in user input, convert every symbol into integer and sum result
# if user input, output sum, otherwise message about successful execution of program

Based on this pseudocode I would write Python code.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
So with input from a couple of people I can focus the problems a bit more. Right now my immediate issue is with my while loop. Because I'm using this loop to create a list of numbers to be processed I'm assuming it should only accept integers (unless I could change the list afterwards to take out letters). The other part of my problem with the loop is that when no input is given and you press enter, the assignment requires that an EOFError is raised and an exception is used to deal with it and terminate the program, I'm using a sentinel to control the loop but I don't know what to use in the sentinel to make this happen.

This is what I have now:

def main():
    
    # Create an empty list.
    list_of_num = []

    num = 0

    # Create a loop to uppent numbers to list_of_num list.
    while num != '':                          # At this moment I'm using a blank space to control the loop
                                              # but this doesn't work because I need no input to raise an error
                                              # and terminate the program with an exception per the assignment.
        # Ask user for input and give directions
        num = input('Enter a sequence of digits with nothing separating '
'them (no input terminates): ')
        # Add input from user to list_of_num.
        list_of_num.append(num)


    # Test list
    print (list_of_num)


main()


Right now everything goes into the list and even no input is added in it.
Output:
Enter a sequence of digits with nothing separating them (no input terminates): 11 Enter a sequence of digits with nothing separating them (no input terminates): 22 Enter a sequence of digits with nothing separating them (no input terminates): 33 Enter a sequence of digits with nothing separating them (no input terminates): 44 Enter a sequence of digits with nothing separating them (no input terminates): xx Enter a sequence of digits with nothing separating them (no input terminates): tt Enter a sequence of digits with nothing separating them (no input terminates): // Enter a sequence of digits with nothing separating them (no input terminates): ['11', '22', '33', '44', 'xx', 'tt', '//', '']
Reply
#5
Hi Jose,
That is nice, but the program still does not do what you want.

Let me tell you something about characters and integers. What a users enters at a keyboard are characters. A character can be a letter (a-z, A-Z), a digit (0-9) or anything that can be entered at the keyboard (. , + etc). You cannot calculate with characters. But you can get the integer value of a digit with int(). When you do int("1") it returns a binary value of '00000001'. And the computer can calculate with that.

Furtheron I see you are struggeling with the order of the statements. Perfringo suggests you should first write the program in in pseudocode. Meaning: write the steps to achieve the result in plain English (or any language that suits you). That is a good method.

Another method is make a drawing of the algorithm. When I have to make a program that gets a bit complicated I always first draw it as a Nassi Shneiderman diagram. Such a diagram is drawn from top to bottom and it consists of blocks. There are essentially three types of blocks. A rectangle which means a simple operation. An upside-down triangle is a choice (if). An enclosed block is a loop (while, for). Like this.

[Image: attachment.php?aid=835]

On top the program starts with showing a welcome message.
Next there is an block enclosed with "while (True) # until break". This block starts with asking the user for input.
Then there is an inverted triangle, an "if" statement. If the user enters an empty string, the T (True) block is executed: a break statement so the while block exits.
If the user entered a string, the block continues with calling the function "stringTotal(userinput)", assigning the returned value to the variable name "total".
The next block prints the result.

Then the while-block repeats asking the user for the next string of digits etc.

When the while-block ends (with the break statement) the next block is executed and the program prints a message it has completed successfully.

Do you know now how to code this in Python?

Attached Files

Thumbnail(s)
   
Reply
#6
I couldn't figure out how to make it work. This is what I got:
def main():

    # Create header + what program does.
    print ('Welcome to the Sum of the Digits Program \n\n'
'This program will sum the digits of an input string.')

    while (True):         # Until break.
        user_input = input('Enter a sequence of digits with nothing separating '
'them (no input terminates): ')
        if user_input == '':
            print ('*** Program has completed successfully ***')
            break # Exit while loop.

        else:
            # Get the total
            total = stringTotal(user_input)

            print ('The sum of input string', user_input, 'is:', total)

def stringTotal(user_input):
    total = 0
    for num in user_input:
        numbers = int(num)
        total += numbers
    return total
Reply
#7
Almost there, but my output doesn't look the way my teacher wants it to look.
I'm assuming that I have to make a loop that prints my outcome with each input but by now my brain is fried, if anyone has any suggestions please give me a hand.
This is what I got so far:

def main():
    try:

        user_input = input('Enter a sequence of digits with nothing separating '
    'them (no input terminates): ')

        # Create header + what program does.
        print ('\n\n\nWelcome to the Sum of the Digits Program \n\n'
    'This program will sum the digits of an input string.\n')



        while user_input != '':

            print ('The sum of input string', user_input, 'is:', stringTotal(user_input))

            user_input = input('Enter a sequence of digits with nothing separating '
    'them (no input terminates): ')

            if user_input == '':
                raise EOFError

    except ValueError:
        print('ERROR enter only numbers with no spaces.')


    except EOFError:
        print('\n\n*** Program has completed successfully ***')



# Call strinTotal() passing the string.
def stringTotal(user_input):
    total = 0
    for num in user_input:
        numbers = int(num)
        total += numbers
    return total


main()
Current output:
Output:
Enter a sequence of digits with nothing separating them (no input terminates): 22 Welcome to the Sum of the Digits Program This program will sum the digits of an input string. The sum of input string 22 is: 4 Enter a sequence of digits with nothing separating them (no input terminates): 23 The sum of input string 23 is: 5 Enter a sequence of digits with nothing separating them (no input terminates): 46 The sum of input string 46 is: 10 Enter a sequence of digits with nothing separating them (no input terminates): *** Program has completed successfully ***
Reply
#8
Current code and output

# Creat main func. to process input int.
def main():
    # Create list that holds multiple processed inputs to output together.
    output = []

    # Start try/except block to deal with error codes.
    try:
        # Create user input with direction for int.
        user_input = input('Enter a sequence of digits with nothing separating '
    'them (no input terminates): ')

        # Create while loop with with sentinel to iterate user input.
        while user_input != '':

            # Create variable that contains message with input and calls
            # stringTotal passing user input.
            output_accumulator = ('The sum of input string', user_input, 'is:',
        stringTotal(user_input))
            # Add output_accumulator to output list.
            output.append(output_accumulator)

            # Repeat user input to complete loop
            user_input = input('Enter a sequence of digits with nothing '
        'separating them (no input terminates): ')


            if user_input == '':          # Create if statement with no input to
                raise EOFError            # raise EOFError.

    except ValueError:                  # Create exception clause for ValueError

        # Create message for ValueError
        print('ERROR enter only numbers with no spaces.')

    except EOFError:                      # Create exception clause for EOFError
        # Create header + what program does.
        print ('\n\n\nWelcome to the Sum of the Digits Program \n\n'
    'This program will sum the digits of an input string.\n')

        # Call output and iterate its list.
        for x in output:
            print(x)

        # Create end message.
        print('\n\n*** Program has completed successfully***')


def stringTotal(user_input):         # Create strinTotal() recieving user_input.
    total = 0                    # Create accunulator variable.
    for num in user_input:              # Create for loop to iterate user_input.
        # Create variable that holds user_input string turned into int.
        numbers = int(num)
        total += numbers                           # Add int. in total variable.
    return total                                                 # Return total.

main()      # Call main
Output:
Enter a sequence of digits with nothing separating them (no input terminates): 11 Enter a sequence of digits with nothing separating them (no input terminates): 22 Enter a sequence of digits with nothing separating them (no input terminates): 33 Enter a sequence of digits with nothing separating them (no input terminates): 44 Enter a sequence of digits with nothing separating them (no input terminates): 55 Enter a sequence of digits with nothing separating them (no input terminates): Welcome to the Sum of the Digits Program This program will sum the digits of an input string. ('The sum of input string', '11', 'is:', 2) ('The sum of input string', '22', 'is:', 4) ('The sum of input string', '33', 'is:', 6) ('The sum of input string', '44', 'is:', 8) ('The sum of input string', '55', 'is:', 10) *** Program has completed successfully***
Reply
#9
Looks good. Is there still a problem?
Reply
#10
Yes, thank you for asking.

The output should look like this
Output:
Welcome to the Sum of the Digits Program This program will sum the digits of an input string. The sum of input string [2514] is: 12 The sum of input string [123456789] is: 45 *** Program has completed successfully***
But instead I'm getting the this:
Output:
Welcome to the Sum of the Digits Program This program will sum the digits of an input string. ('The sum of input string', '2514', 'is:', 12) ('The sum of input string', '123456789', 'is:', 45) *** Program has completed successfully***
I tried the str = ''.join(tuple) method and a variation that iterates over the tuple but I can't get it to work because of the different elements in it. Maybe I don't need to send my information into a list but I'm too new to this and PyScripter shows the output together with the user input in between lines and I don't know if that's how the real output would look.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,370 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Split string into 160-character chunks while adding text to each part iambobbiekings 9 9,491 Jan-27-2021, 08:15 AM
Last Post: iambobbiekings
  Convert list of numbers to string of numbers kam_uk 5 2,935 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  Convert multiple decimal numbers in string to floats Katy8 6 3,464 Aug-16-2020, 06:06 PM
Last Post: Katy8
  How to print the docstring(documentation string) of the input function ? Kishore_Bill 1 3,500 Feb-27-2020, 09:22 AM
Last Post: buran
  Question about running comparisons through loop from input value Sunioj 2 2,362 Oct-15-2019, 03:15 PM
Last Post: jefsummers
  In input, I want just numbers and not strings! aquerci 2 3,214 Oct-19-2018, 12:53 PM
Last Post: DeaD_EyE
  input vs string thdnkns 5 3,217 Oct-16-2018, 01:15 AM
Last Post: ichabod801
  Divide a number - Multiple levels - Sum of all numbers equal to input number pythoneer 17 8,651 Apr-20-2018, 04:07 AM
Last Post: pythoneer
  Trying to get the week number from a string of numbers fad3r 2 3,159 Apr-15-2018, 06:52 PM
Last Post: ljmetzger

Forum Jump:

User Panel Messages

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