0

okay, i'm stuck on an assignment! (first post btw, so tell me if i'm doing anything wrong please :) )

okay, my assignment is as follows :

Write some efficient and commented python code to do the following:

Accept an input value between 33 and 126 and convert it to an integer
Output the number and its corresponding character; using the chr() function
Accept a word input
Output the length of the word using len()
Convert each character into its ASCII value
Add up all the character values and output the total

and so far i've only come up with

def check_input(low, high):

    prompt = "Enter an integer number between %d and %d: " % (low, high)
    while True:
        try:
            a = int(input(prompt))
            if low <= a <= high:
                return a
        except ValueError:
            print(prompt)

num_input = check_input(33, 126)
print(chr(num_input))

but this only accepts a number between 33 and 126, and displays the ascii character... any help would be much appreciated, especially on the accepting word input bit!!

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by kannibalkiwi
0

Here is one variation of input, not exactly according to your specification, so it is not direct answer:

try:
    input = raw_input
except:
    pass

def check_input(low, high):

    print("Enter an integer number between %d and %d: " % (low, high))
    while True:
        a = input()
        try:
            if low <= int(a) <= high:
                yield int(a)
            else:
                print('Value %s out of range. Enter again: ' % a)
        except ValueError:
            if not a:
                break
            print('Wrong input %s ignored. Enter again: ' % a)
            
print('To finish, give empty line')
the_numbers = list(check_input(33, 126))

print('\n'.join('%s %r' % (number, chr(number)) for number in the_numbers))
print('Sum %i' % sum(the_numbers))

print('Input as string is %r.' % ''.join(chr(number) for number in the_numbers))
0

Perhaps something along the lines of the following. Otherwise, you want to use 2 prompts, one for the number, and another for the word. Note that you can also use isdigit() to test for a number, but it doesn't really matter which one you use.

def check_input(low, high):

    prompt = "Enter an integer number between %d and %d: " % (low, high)
    while True:
        try:
            a = int(input(prompt))
            if low <= a <= high:
                return a
        except ValueError:
            print("A word was entered = %s" (a))

num_input = check_input(33, 126)
print(chr(num_input))

Edited by woooee: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.