Why do I keep getting an error that the chr() value is out of range?

290 Views Asked by At

CODE:

from tkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename
ews = 3
xds = True
while xds:
    password = input("ENTER A 7 DIGIT PASSWORD: ")
    if password == "encrypt":
        xds = False
        def open_file():
            """Open a file for editing."""
            filepath = askopenfilename(
                filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
            )
            if not filepath:
                return
            txt_edit.delete("1.0", END)
            with open(filepath, mode="r", encoding="utf-8") as input_file:
                text = input_file.read()
                txt_edit.insert(END, text)
            window.title(f"Decoder - {filepath}")

        def save_file():
            """Save the current file as a new file."""
            filepath = asksaveasfilename(
                defaultextension=".txt",
                filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
            )
            if not filepath:
                return
            with open(filepath, mode="w", encoding="utf-8") as output_file:
                text = txt_edit.get("1.0", END)
                output_file.write(text)
            window.title(f"Decoder - {filepath}")


        def decode(strt, num):
            y = ""
            for i in strt:
                print(i)
                print(ord(i))
                print(ord(i)-num)
                y += chr(ord(i)-num)
            return (y)
        def encode(str, num):
            y = ""
            for i in str:
                y+=chr(ord(i)+num)
            return(y)

        def decode_file(r):
            s = txt_edit.get("1.0", END)
            print(s)
            x = decode(s, r)
            txt_edit.delete("1.0", END)
            txt_edit.insert(END, x)

        def encode_file(r):
            s = txt_edit.get("1.0", END)
            x = encode(s, r)
            txt_edit.delete("1.0", END)
            txt_edit.insert(END, x)
        def clear():
            txt_edit.delete("1.0", END)
        window = Tk()
        window.title("Decoder")
        def enter():
            global ews
            z = e.get()
            if z.isnumeric():
                z = int(z)
                if z<=50000 and z >=1:
                    ews = z
        def test():
            global ews
            encode_file(ews)
        def test2():
            global ews
            decode_file(ews)
        window.rowconfigure(0, minsize=1300, weight=1)
        window.columnconfigure(1, minsize=800, weight=1)

        txt_edit = Text(window)
        frm_buttons = Frame(window, relief=RAISED, bd=2)
        btn_open = Button(frm_buttons, text="Open", command=open_file)
        btn_save = Button(frm_buttons, text="Save As...", command=save_file)
        btn_encode = Button(frm_buttons, text = "Encrypt", command = test)
        btn_decode = Button(frm_buttons, text = "Decrypt", command = test2)
        btn_clear = Button(frm_buttons, text = "Clear", command = clear)
        btn_enter = Button(frm_buttons, text = "ENTER", command = enter)
        l = Label(frm_buttons,text = "ENCRYPTION CODE:", fg = "black")
        e = Entry(frm_buttons)

        btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
        btn_save.grid(row=1, column=0, sticky="ew", padx=5, pady = 5)
        btn_encode.grid(row=2, column=0, sticky="ew", padx=5, pady=5)
        btn_decode.grid(row=3, column=0, sticky="ew", padx=5, pady=5)
        btn_clear.grid(row=4, column=0, sticky="ew", padx=5, pady=5)
        l.grid(row = 5, column = 0, sticky = "ew", padx = 5, pady = 5)
        e.grid(row=6, column=0, sticky="ew", padx=5, pady=5)
        btn_enter.grid(row=7, column=0, sticky="ew", padx=5, pady=5)
        frm_buttons.grid(row=0, column=0, sticky="ns")
        txt_edit.grid(row=0, column=1, sticky="nsew")

        window.mainloop()
    else:
        print("INVALID")

Error code: line 42, in decode y += chr(ord(i)-num) ValueError: chr() arg not in range(0x110000)

What is happening is that the chr() value is going negative (I tested it with some print statements) but I would like to know how to solve it. I need to add details so the code is basically trying to make a decryption and encryption software.

EDIT: after modifying this:

def enter():
    global ews
    z = e.get()
    if z.isnumeric():
        z = int(z)
        if z<=31 and z >=1:
            ews = z

it still has the same error code.

3

There are 3 best solutions below

0
hc_dev On BEST ANSWER

Did you research? Found plenty of answers for [python] chr() arg not in range(0x110000).

See the docs for function chr(i) which requires a postive number as argument:

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

Debug the failing statement

To debug your failing statement just add some print outs before to see the inputs:

print(f"i: '{i}', ord(i): {ord(i)}, num: {num}")  # debug-print the inputs
print(f"given as arg to chr(): {ord(i)-num}")   # debug-print the expression passed as argument to chr 

y += chr(ord(i)-num)  # will raise a ValueError if ord(i) < num

Post such debug print-outputs with your question, because we need such debugging details to reproduce and help you.

Further call-stack

Since above failing decode and encode functions are called with a string s and a subtrahend given by number r

def decode_file(r):
    x = decode(s, r)

# or
def encode_file(r):
    x = encode(s, r)

Let's figure out what values r can be.

Found it in your test-functions:

def test():
    global ews
    encode_file(ews)

def test2():
    global ews
    decode_file(ews)

Now, either make sure that global variable ews is always lower or equal to any char's ASCII code (derived by ord(i)), or adjust your expression given to chr so that it always results in a positive number.

0
Xavion Mirchandani On

I just modified this:

def enter():
    global ews
    z = e.get()
    if z.isnumeric():
        z = int(z)
        if z<=31 and z >=1:
            ews = z

So that the max was 10 (which was what I found after some testing) and it had no error code.

1
Hack On

Just add an if statement so that if whatever is delivered by ord(i) is less than 0 then don't do it.