0

For some reason the line "new1 = [chr(x) for x in new]" cannot take a float. I am converting all the ASCII integers in the 'new' list back to a list with characters, according to their respective ASCII number, this list would be saved as new1.

if de == "d":
   num = input("input ur number: ")
   key = int(input("Decryption key?"))
   num = [int(x) for x in num.split()]
   new = [x /key for x in num]
   new1 = [chr(x) for x in new]

This is the error:

--Traceback (most recent call last): File "C:\Python34\Encryptiontrue.py", line 23, in new1 = [chr(x) for x in new]

-- File "C:\Python34\Encryptiontrue.py", line 23, in new1 = [chr(x) for x in new]

-- TypeError: integer argument expected, got float

Full Code:

de = input("Decrypt or encrypt?: ")

if de == "e":
   word = input("input ur text: ")
   word = word.lower() 
   new = list(word)

   key = int(input("what number by?: "))

   new1 = [ord(x) * user for x in new]

   new2 = " ".join(str(x) for x in new1)
   print(new2)

if de == "d":
   num = input("input ur number: ")
   key = int(input("Decryption key?"))
   num = [int(x) for x in num.split()]
   new = [x /key for x in num]
   new1 = [chr(x) for x in new]
3
  • What are you inputs? Commented Dec 14, 2015 at 16:41
  • chr(x) shouldn't take a float because how would you convert something like 26.23 into a ascii character? do an explicit integer conversion in your list comprehension for new with x//key or int(x/key). Commented Dec 14, 2015 at 16:42
  • @RNar Thank you so much! It works :) Commented Dec 14, 2015 at 16:46

1 Answer 1

1

Change

new = [x / key for x in num]

To

new = [x // key for x in num]

In Python 3, / indicates "true division" which always returns a float. // indicates "floor division". Floor division will return an integer if both arguments are integers. For more details see PEP 238 -- Changing the Division Operator.

Sign up to request clarification or add additional context in comments.

6 Comments

I find that a lot of people are confused about the // operator. You might want to explain why changing it to // fixes the problem.
Working on that. Thinking about just linking to the PEP.
Actually, I'm not completely sure that will work as chr(10.//3.) is still a TypeError. (from the PEP: the result type will be the common type into which a and b are coerced before the operation)
@mgilson: Good point. But the OP's code is not using floats so it won't be an issue here.
Ahh, right. I didn't look at OP's code closely enough to infer the types of x and key. Sorry for the noise.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.