#Python script not executing properly

1 messages · Page 1 of 1 (latest)

leaden yew
#

Hello, im new to coding and have little knowledge and wondering if anyone can help me with this code im working on. I tried to run it but nothing is happening. Thanks!!

bold coral
#

It's because you're not calling the main properly. The call (main()) should be outside the function. In other words, you simply need to un-indent it.

def main():
  ...

main()
leaden yew
bold coral
#

Kinda. You also need to un-indent the whole main function. Right now, your main function is inside your decimalToRep. It's going to cause some issue and will make it impossible to call your main function.

#

It should look like this

def decimalToRep(num, base):
  ...

def main():
  ...

main()

PS. In the future, please send your code like shown bellow instead.
```python
your code here
```

#

You should fix your indentation in general. A lot of your code is badly indented and will not work properly or make your code crash.

#

It's important to understand that in Python code is structured through indentation. Thus, all statements that have the same indentation are considered to be in the same block (group of statements). It also means that if you want to add statements in a function, a while, a if-else, etc, they need to be in the same block to work properly. The last important thing to know about those block is that anything created in a block is only accessible to this block or it's children (block or statement inside it).

Ex.

while condition:
  statement 1
  statement 2
statement 3

In the example above, statement 1 and 2 are both in the while block and will thus both be executed when the while is executed. The statement 3 is outside the while block and will only be executed once the while is finished.

while loop_condition:
  statement 1
      
  if condition:
    statement 2

statement 3

In this example, all is the same as the previous example except that statement 2 is in an additional block and will be executed only if the condition of the if is met during looping.

https://docs.python.org/3/reference/executionmodel.html

leaden yew
#

Like this?

leaden yew
#

Its still not working

bold coral
#

It says that there's an indentation issue?

leaden yew
#

Nope

bold coral
#

What does it says?

#

And please send your code like shown bellow instead.
```python
your code here
```

leaden yew
#

It doesnt have an error, its just blank

bold coral
#

Show me

#

And if you send your code like I asked I can fix it for you

#

You have a lot of error that will flare up in any cases. You need to adjust your decimalToRep function.

leaden yew
#

‘’Python’’

bold coral
#

Have you read my explanation of how code-blocks work in Python?

#

And again, if you could send your while code like shown bellow I could try to fix it for you
```python
your code here
```

#

;compile

def greet(name):
  print(f"Hello {name}")

def main():
  greet("plntbasedmami")

main()
stable vineBOT
#
Program Output
Hello plntbasedmami
bold coral
#

Python script not executing properly

leaden yew
bold coral
#

You send this in the chat

#

Of course, you need to change "your code here" by your actual code

leaden yew
#

‘’’python def decimalToRep (num, base) :
result
while (num>0):
rem = num % base
if rem in range(10) :
result += str(rem)
else:
result += chr(65+(rem%10))
num
num //
das
result = result[::-1]
if(result
return '91
return result
def
main() :
""'"Tests the function.""
print (decimalToRep(10,10))
print (decimalToRep(10
81 )
print (decimalToRep(10,2)
print (decimalToRep(10,16))
main)’’’

leaden yew
bold coral
#

Yea you got the wrong characters at the beginning and end and it needs to be on their own lines

#

```python
def decimalToRep (num, base) :
result
while (num>0):
rem = num % base
if rem in range(10) :
result += str(rem)
else:
result += chr(65+(rem%10))
num
num //
das
result = result[::-1]
if(result
return '91
return result
def
main() :
""'"Tests the function.""
print (decimalToRep(10,10))
print (decimalToRep(10
81 )
print (decimalToRep(10,2)
print (decimalToRep(10,16))
main)
```

#
def decimalToRep (num, base) :
result
while (num>0):
rem = num % base
if rem in range(10) :
result += str(rem)
else:
result += chr(65+(rem%10))
num
num //
das
result = result[::-1]
if(result
return '91
return result
def
main() :
""'"Tests the function.""
print (decimalToRep(10,10))
print (decimalToRep(10
81 )
print (decimalToRep(10,2)
print (decimalToRep(10,16))
main)
#

Anyway, let's indent this properly

#

;compile

def decimalToRep(num, base):
    result = ""

    while num > 0:
        rem = num % base
        if rem in range(10):
            result += str(rem)
        else:
            result += chr(65 + (rem % 10))
            num = num // base
            result = result[::-1]

        if result == "":
          return result


def main():
    """Tests the function."""
    print(decimalToRep(10, 10))
    print(decimalToRep(10, 81))
    print(decimalToRep(10, 2))
    print(decimalToRep(10, 16))

main()
stable vineBOT
#
Compiler Output
Killed - processing time exceeded
bold coral
#

Now all you got to do is fix your function (btw, it says Killed - processing time exceeded because your loop never ends)

leaden yew
#

‘ ‘ ‘python
def decimalToRep (num, base) :
result
while (num>0):
rem = num % base
if rem in range(10) :
result += str(rem)
else: result += chr(65+(rem%10))
num=num // base
result = result[::-1]
if (result == “”):
return '0’
return result
def main() :
""'"Tests the function.""”
print (decimalToRep(10,10))
print (decimalToRep(10,8))
print (decimalToRep(10,2))
print (decimalToRep(10,16))
main()

bold coral
#

’’’ are the wrong characters. It needs to be ```

bold coral
leaden yew
#

‘ ‘ ‘python
def decimalToRep (num, base) :
result
while (num>0):
rem = num % base
if rem in range(10) :
result += str(rem)
else: result += chr(65+(rem%10))
num=num // base
result = result[::-1]
if (result == “”):
return '0’
return result
def main() :
""'"Tests the function.""”
print (decimalToRep(10,10))
print (decimalToRep(10,8))
print (decimalToRep(10,2))
print (decimalToRep(10,16))
main() ' ' '

leaden yew
#

@bold coralWould i use break?

foggy wind
#

num = num // base ?

not num = num / base ?

isn't // a comment ?

#

;compile python

def decimalToRep(num, base):
    result = ""
    i = 0
    while ( (num > 0) and (i < 1000) ):
        rem = num % base
        if rem in range(10):
            if (rem > 0):
               result += str(rem)
        else:
            result += chr(65 + (rem % 10))
            num = num // base
            result = result[::-1]

        i = i + 1
        #print(rem)
        #print(result)
        if result == "":
          return result

def main():
    """Tests the function."""
    print(decimalToRep(10, 10))
    print(decimalToRep(10, 81))
    print(decimalToRep(10, 2))
    print(decimalToRep(10, 16))

main()
stable vineBOT
#
Program Output
None

None
bold coral
bold coral
foggy wind
#

ah ok

bold coral
#

;compile

print(15 / 2)
print(15 // 2)
stable vineBOT
#
Program Output
7.5
7
foggy wind
#

it's appending a bunch of zeros

bold coral
#

I think it's the fault of the line above it

#

I would test it but I'm not on my computer and it's anoying to code on phone. I might check this out tomorrow.

foggy wind
#

I don't understand what he's trying to do 😄

#

ok but he's not using a lookup table 😄

bold coral
#

I think it's supposed to convert of base 10 to a number of another base?

bold coral
foggy wind
#

// Integer JDK7
    /**
     * All possible chars for representing a number as a String
     */
    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

     static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
        int charPos = len;
        int radix = 1 << shift;
        int mask = radix - 1;
        do {
            buf[offset + --charPos] = Integer.digits[val & mask];
            val >>>= shift;
        } while (val != 0 && charPos > 0);

        return charPos;
    }
#

that's with a lookup table 🙂

#

this one also

#
    public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        if (radix == 10) {
            return toString(i);
        }

        char buf[] = new char[33];
        boolean negative = (i < 0);
        int charPos = 32;

        if (!negative) {
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }
#

digits[] is a look up table

leaden yew
#

Would that be a lookout table that i did?

foggy wind
#

alpha needs to be a []

#
final static char[] alpha = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };
#

maybe capitalized 🤷‍♂️

#

but the jdk8 algo is valid for any number negative or positive

#

and any radix from 2 to 36

leaden yew
#

Now my code is saying list index out of range

foggy wind
#

are you indexed at 0 or 1

#
import string
digs = string.digits + string.ascii_letters


def int2base(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1

    x *= sign
    digits = []

    while x:
        digits.append(digs[x % base])
        x = x // base

    if sign < 0:
        digits.append('-')

    digits.reverse()

    return ''.join(digits)
#

where digs are digits then letters 😄

bold coral
foggy wind
#

from stack overflow, python 3 with // base

#

;compile python

import string
digs = string.digits + string.ascii_letters.upper() + string.ascii_letters

def decimalToRep(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1

    if base < 2:
       base = 2

    x *= sign
    digits = []

    while x:
        digits.append(digs[x % base])
        x = x // base

    if sign < 0:
        digits.append('-')

    digits.reverse()

    return ''.join(digits)

def main():
    """Tests the function."""
    print(decimalToRep(10, 10))
    print(decimalToRep(10, 81))
    print(decimalToRep(10, 2))
    print(decimalToRep(10, 16))
    print(decimalToRep(255, 2))
    print(decimalToRep(255, 16))
    print(decimalToRep(255, 32))
    print(digs)

main()
stable vineBOT
#
Program Output
10
A
1010
A
11111111
FF
7V
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
foggy wind
#

the results seems correct for base <= 16

leaden yew
foggy wind
#

digs is lookup

leaden yew
foggy wind
#

digs is the lookup table on the last line

bold coral
foggy wind
#

7v is correct for 255 in base 32 in java

#

so yeah, this algo works 🙂

foggy wind
#

oh so you are DECODING (parseInt) not ENCODING (toString)

#
public static int parseInt(String s, int radix)
throws NumberFormatException
    {
        int result = 0;
        boolean negative = false;
        int i = 0;
        int len = s.length();
        int limit = -2147483647; // -0x7fffffff; // Integer.MAX_VALUE;
        int multmin = 0;
        int digit = 0;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = -2147483648; //0x80000000; // Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }
#

test cases

/**
     * parseInt("0", 10) returns 0
     * parseInt("473", 10) returns 473
     * parseInt("+42", 10) returns 42
     * parseInt("-0", 10) returns 0
     * parseInt("-FF", 16) returns -255
     * parseInt("1100110", 2) returns 102
     * parseInt("2147483647", 10) returns 2147483647
     * parseInt("-2147483648", 10) returns -2147483648
     * parseInt("2147483648", 10) throws a NumberFormatException
     * parseInt("99", 8) throws a NumberFormatException
     * parseInt("Kona", 10) throws a NumberFormatException
     * parseInt("Kona", 27) returns 411787
*/
foggy wind
#

it's just a comment

#

I am showing you the algorithm in Java, because I cannot find python3 😄 equivalent yet

leaden yew
#

Thanks

foggy wind
#

but basically you parse each byte into a lookup table and shift multiply by that base

#

until you read the entire thing

leaden yew
foggy wind
#

"10" in base 10
is 1 x 10^1 + 0 x 10^0

#

"10" in base 16
is 1 x 16^1 + 0 x 16^0

#

anyway

#

🙂

leaden yew
foggy wind
#

works in python3

#

maybe not in python2

#

but that's for encoding, not decoding

#

your initial code was more decoding also 🙂

#

i gtg

leaden yew
#

Well im not sure if im supposed to encode or decode

leaden yew
foggy wind
#

try it

leaden yew
#

Well it gave 10 8 2 and 16

leaden yew
foggy wind
#

I am assuming that decimal to representation in base X
means you have to encode not to decode