Reputation: 81
So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error.
TypeError: 'int' object is not iterable
Heres the code, i hope you guys can help me, much appreciated
plainNum = input("enter a number to encode ")
codedNum = ' '
Key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Upvotes: 0
Views: 409
Reputation: 21
This is working but not if I use a decimal and it doesn't behave if I enter words or spaces. Consider checking first that the entry is a number with something like:
try:
float(element)
except ValueError:
print "Not a float"
after stripping any whitespace with something like:
plainNum = plainNum.strip()
But this outputs the encoded digits of your entered integer:
plainNum = raw_input("enter a number to encode ")
codedNum = ' '
key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Ask the user for the number with raw_input. This makes the input a string which you can iterate over with:
for char in plainNum:
Yes, this is a now a char in a string and so you've used the int(i) function.
Upvotes: 1
Reputation: 3217
you maybe also wanna change key to Key to reflect what variable is declared and also make codeNum initially equal to '' instead of ' ' (no space vs space) just book keeping stuff
Upvotes: 0
Reputation: 2722
Most dirty fix of all, simply change
for i in plainNum:
with
for i in str(plainNum):
Upvotes: 2
Reputation: 1124348
Use raw_input
if you expect a string:
plainNum = raw_input("enter a number to encode ")
input()
interprets the input as if it is Python code; enter 5
and it'll return an integer, enter 'some text'
(with quotes) and it'll return a string. raw_input()
on the other hand returns the entered input uninterpreted.
Upvotes: 5