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!!

Recommended Answers

All 2 Replies

while True :
	# Accept an input from the user
	reply = raw_input( "Enter an integer between 33 and 126: " )

	# Check if it is indeed a number
	if not reply.isdigit() :
		continue

	# Convert it to number
	number = int( reply )

	# Check if the number is in the specifeid range
	if 33 <= number <= 126 :
		break

# Output the number and its corresponding character:
print "Number entered: %d" % number
print "Corresponding character: '%s'" % chr( number )

# Accept a word as input
word = raw_input( "Enter a word: " )

# Convert each letter to ascii value
print "Characters and their ascii values: "
for letter in word :
	print letter + ": %d" % ord( letter )

chrValSum = 0
for letter in word :
	chrValSum += ord( letter )

print "Sum of the charater values of the word, '%s': %d" % ( word, chrValSum )

This is called "non-sense code" (not my word). It is more straight forward to use

if not reply.isdigit() :
        continue
    # Convert it to number
    number = int( reply )
#
#
    if reply.isdigit() :
        # rest of instructions
        # Convert it to number
        number = int( reply )

Also you have redundant loops that can be combined:

chr_val_sum = 0
for letter in word :
    print letter + ": %d" % ord( letter )
    chr_val_sum += ord( letter )
print "Sum of the charater values of the word, '%s': %d" % ( word, chr_val_sum )

Python naming conventions when you get some extra time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.