简体   繁体   中英

what type should i use instead of int or str?

At the first let me explain the code: my code is an encrypting code. at the first it gives two numbers then it have two encryption stages. First stage, will reverse the text till the char that its index is equel with first number. Second stage, will shift the chars of previous stage output in amount of their new location multiple by second number. and finally print what is encrypted. in this code i have problem with the 7th line of code. don't know what type should i use for variables that are in 7th line. i receive error whether i use str or int.

first_num=int(input("Fnum: "))
second_num=input("Snum: ")
encrypt_stage1="".join(name[first_num-1::-1])+"".join(name[first_num::])

for place,char in enumerate(encrypt_stage1):
    ascii_code=ord(char)
    encryption_stage2=""
    encryption_stage2 += chr(str(int(ascii_code)+place*second_num))

print(encryption_stage2)
>>>TypeError: unsupported operand type(s) for +: 'int' and 'str'


----------
example of input: name=vahid, first_num=1, second_num=3
output will be: ygqus

There are at least three problems:

  • you forget to convert second_num to int
  • you can't apply chr() to str() , I removed chr() call
  • I have to move encryption_stage2="" outside the loop to not reassign it on every iteration

After dealing with these problems, the code looks like:

name = 'name'
first_num=int(input("Fnum: "))
second_num=int(input("Snum: "))
encrypt_stage1="".join(name[first_num-1::-1])+"".join(name[first_num::])

encryption_stage2=""
for place,char in enumerate(encrypt_stage1):
    ascii_code=ord(char)
    encryption_stage2 += str(int(ascii_code)+place*second_num)

print(encryption_stage2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM