#Python script not executing properly
1 messages · Page 1 of 1 (latest)
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()
Like this? Because its still not working
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.
This is a more complete and well written explanation https://python-course.eu/python-tutorial/structuring-indentation.php
Like this?
Like this? Its still not working
Its still not working
It says that there's an indentation issue?
Nope
What does it says?
And please send your code like shown bellow instead.
```python
your code here
```
It doesnt have an error, its just blank
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.
‘’Python’’
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()
Hello plntbasedmami
Python script not executing properly
Wait how would I do my code like how you did it?
```python
your code here
```
You send this in the chat
Of course, you need to change "your code here" by your actual code
‘’’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)’’’
I dont think that worked lol
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()
Killed - processing time exceeded
Now all you got to do is fix your function (btw, it says Killed - processing time exceeded because your loop never ends)
‘ ‘ ‘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()
’’’ are the wrong characters. It needs to be ```
They also need to be on their own line. Look at this message
‘ ‘ ‘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() ' ' '
How do i get the loop to end?
@bold coralWould i use break?
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()
None
None
No that's wouldn't be the solution
No, // in Python isn't a comment. It's a floor division.
ah ok
;compile
print(15 / 2)
print(15 // 2)
7.5
7
it's appending a bunch of zeros
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.
I think it's supposed to convert of base 10 to a number of another base?
Definitely not
// 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
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
Now my code is saying list index out of range
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 😄
I'm guessing they changed alpha to alpha = ["0123456789ABCDEFGHIJKLMNOPQ..."] instead of alpha = ["0", "1", "2", ...] because you said to make it [ ]
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()
10
A
1010
A
11111111
FF
7V
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
the results seems correct for base <= 16
But doesnt that code need a lookout table?
digs is lookup
Is the way i did it fine or should i “1”, “2”,
digs is the lookup table on the last line
The way it was at first was fine although making it a list might be better in this case.
This is the output for the code
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
*/
What does this mean?
it's just a comment
I am showing you the algorithm in Java, because I cannot find python3 😄 equivalent yet
Thanks
but basically you parse each byte into a lookup table and shift multiply by that base
until you read the entire thing
So this code answers all of my code assignment question?
"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
🙂
I tried the code but its saying invalid syntax on line 2 where it has digs= string.digits+
works in python3
maybe not in python2
but that's for encoding, not decoding
your initial code was more decoding also 🙂
i gtg
Well im not sure if im supposed to encode or decode
Thanks for your help and do you think this code answers the question
try it
Well it gave 10 8 2 and 16
As output
I am assuming that decimal to representation in base X
means you have to encode not to decode