int() can't convert non-string with explicit base - Why? [duplicate] - python

This question already has answers here:
How to convert an integer to a string in any base?
(35 answers)
Closed 4 days ago.
Write a program that prompts the user for input of a positive integer n and
converts that integer into each base b between 2 and 16 (using a for loop). I'm halfway there (still have to convert the numbers to letters for bases 10+).
When I run the program, the error pops up. I thought int() took integers as parameters?
n = int(input("Enter a positive number: "))
while n < 0:
n = int(input("Please input a positive number: "))
for x in range(2, 17): #x being the iteration of base numbers
baseConvert = int(n, x)
textString = "{} = {} in base {}".format(n, baseConvert, x)
print(textString)
Traceback (most recent call last):
File "/tmp/sessions/fdb8f9ea1d4915eb/main.py", line 8, in <module>
baseConvert = int(n, base)
TypeError: int() can't convert non-string with explicit base

Credits to https://stackoverflow.com/a/53675480/4954993
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(number, base):
res = "" #Starts with empty string
while number and base>1: #While number is not zero, it means there are still digits to be calculed.
res+=BS[number%base] #Uses the remainder of number divided by base as the index for getting the respective char from constant BS. Attaches the char to the right of string res.
number//= base #Divides number by base and store result as int in var number.
return res[::-1] or "0" #Returns reversed string, or zero if empty.
n=-1
while n < 0:
n = int(input("Please input a positive number: "))
for i in range(2,17):
print("Base", i, "Number", to_base(n,i))

Related

How check if first digit of integer is zero in python

** i want to check if first digit of integer is zero.
If it is zero, i want to leave first digit which is zero and take the rest.
For example num = 0618861552
In this case first digit is zero. I want to get 618861552
If the first digit of num is not zero, i want to take the entire string.
For example num = 618861552
In this case first digit of num is not zero, i want to get 618861552
Below is the code i have tried.
Note that my code works if first digit is not zero but doesn't work if the first digit is zero
**
num = int(input("enter number: "))
#changing int to str to index.
position = str(num)
if int(position[0]) == 0:
len = len(position)
position1 = position[1:len]
print(position1)
else:
len = len(position)
position1 = position [0:len]
print(position1)
This should do:
number = input("enter number: ")
print(number.lstrip('0'))
This would work :
def remove_zero (a) :
a = str(a)
if ord(a[0]) == 48 :
a = a[1:]
return (str(a))
p = int(input("Enter a number :"))
q = remove_zero(p)
print(q)
Actually converting to int remove all leading zero.
num = "0020"
num2 = "070"
num3 = "000000070"
print(int(num))
print(int(num2))
print(int(num3))
Output is
20
70
70
And this way works too:
num = int(input())
print(num)
That is why
Note that my code works if first digit is not zero but doesn't work if
the first digit is zero **
It is always without leading zero after convertion to int

Include a variable into the input function prompt [duplicate]

This question already has answers here:
Python Error - TypeError: input expected at most 1 arguments, got 3 [duplicate]
(3 answers)
Closed 1 year ago.
This is the question I was working on. I have created a function to convert binary number to decimal but what I couldn't figure out was how to get values while the number after Enter change
Enter 4 position value
Enter 3 position value
Enter 2 position value
Enter 1 position value
This is the code which I tried but apparently prompt inside input does not work like it does in print function. The numbers after Enter change depending on how much the user wants to enter.
a=int(input("Enter Number of digits : "))
while a<0:
x=int(input("Enter ",a, " position value : "))
input() only expects a single argument; use string formatting to pass it a single string with your position value in it
One of these is likely what you're after (functionally identical, but you may have some preference)
int(input(f"Enter {a} position value: "))
int(input("Enter {} position value: ".format(a)))
Multiple arguments to input() will raise TypeError!
>>> input("foo", "bar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: input expected at most 1 argument, got 2
You could print before the input
b = 0
a = int(input("Enter Number of digits: "))
# digits = [0 for _ in range(a)]
b |= int(input("Enter MSB Value")) # or digits[a-1] = int(input())
a -= 1
while a > 0:
print("Enter " , a, " position value : ")
x = int(input()) # or digits[a] = int(input())
b |= (x << a) # just an example
a -= 1
But if you want to put the input on the same line, then you need to format or concatenate the string to the input function, which is not what commas do
Regarding the storing of binary numbers, you should ideally be using bit-shift logic (as shown above) for that since you aren't actually entering decimal values, only individual bits. (Logic above not tested for your problem, btw)
And you don't need to write your own function to convert
Python: Binary To Decimal Conversion

Can't convert string to integer under while loop in python [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed 2 years ago.
I'm new to python. In this code, I'm trying to ask for numbers repeatedly. When the user enters 0, the program print the average of the numbers exclude 0. I can get the average from this code. However, there's a ValueError,
y = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't understand why this error happens. Is it because of convert variable type under while loop? Can anyone help? Thanks!!
nums=0
i=0
x = int(input())
while x>0:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
This error occurs when you try to input a string of characters, instead of numbers.
E.g:
if you input '', 'string' - These won't work
but if you input '9', '239412' - This will work
It is likely the line y = int(input()) is receiving a string from the user input .
See this example.
>>> while True:
... y = int(input())
... print "Y=",y
...
12
Y= 12
0
Y= 0
"this"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'this'
Like #Blade said you should give numbers as input. You can do this:
nums=0
i=0
try:
x = int(input())
while x>0:
try:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
except:
print("Input is not a number")
except:
print("Input is not a number")
You got the Value Error because you entered a space( "") which considered as a string but the input should be an integer int
For calculating the average of two numbers you can use this simple code instead : -
def average(x, y):
" Returns the average of two numbers "
return (x+y)/2
x = int(input("Enter a number:\n"))
y = int(input("Enter another number :\n"))
print(average(x, y))

ISBN final digit finder

I am working in python 3 and I am making a program that will take in a 10 digit ISBN Number and applying a method to it to find the 11th number.
Here is my current code
ISBN=input('Please enter the 10 digit number: ')
while len(ISBN)!= 10:
print('Please make sure you have entered a number which is exactly 10 characters long.')
ISBN=int(input('Please enter the 10 digit number: '))
continue
else:
Digit1=int(ISBN[0])*11
Digit2=int(ISBN[1])*10
Digit3=int(ISBN[2])*9
Digit4=int(ISBN[3])*8
Digit5=int(ISBN[4])*7
Digit6=int(ISBN[5])*6
Digit7=int(ISBN[6])*5
Digit8=int(ISBN[7])*4
Digit9=int(ISBN[8])*3
Digit10=int(ISBN[9])*2
Sum=(Digit1+Digit2+Digit3+Digit4+Digit5+Digit6+Digit7+Digit8+Digit9+Digit10)
Mod=Sum%11
Digit11=11-Mod
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('Your 11 digit ISBN Number is ' + ISBNNumber)
I want to create some kind of loop so that the number after "Digit" for the variable name increases starting from 1 (or zero if it makes life easier), the number in the square brackets increases starting from 0 and the multiplication number to decrease from 11 to 2.
Is there any way of doing this code in a more efficient way?
I think this should do what you want.
def get_isbn_number(isbn):
digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
digit_11 = 11 - (sum(digits) % 11)
if digit_11 == 10:
digit_11 = 'X'
digits.append(digit_11)
isbn_number = "".join(map(str, digits))
return isbn_number
EXAMPLE
>>> print(get_isbn_number('2345432681'))
22303640281810242428
>>> print(get_isbn_number('2345432680'))
2230364028181024240X
Explanation of second line:
digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
Could be written out like:
isbn_letters = list(isbn) # turn a string into a list of characters
isbn_numbers = map(int, isbn_letters) # run the function int() on each of the items in the list
digits = [] # empty list to hold the digits
for i, num in enumerate(isbn_numbers): # loop over the numbers - i is a 0 based counter you get for free when using enumerate
digits.append((11 - i) * num) # If you notice the pattern, if you subtract the counter value (starting at 0) from 11 then you get your desired multiplier
Terms you should look up to understand the one line version of the code:
map,
enumerate,
list conprehension
ISBN=int(input('Please enter the 10 digit number: ')) # Ensuring ISBN is an integer
while len(ISBN)!= 10:
print('Please make sure you have entered a number which is exactly 10 characters long.')
ISBN=int(input('Please enter the 10 digit number: '))
continue
else:
Sum = 0
for i in range(len(ISBN)):
Sum += ISBN[i]
Mod=Sum%11
Digit11=11-Mod
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('Your 11 digit ISBN Number is ' + ISBNNumber)

I dont understand this syntax error

I think I'm calculating the conversion from an integer to a binary number wrong. I entered the integer 6 and got back the binary number 0, which is definitely wrong. Can you guys help out? Here's the new code.
def ConvertNtoBinary(n):
binaryStr = ''
if n < 0:
print('Value is a negative integer')
if n == 0:
print('Binary value of 0 is 0')
else:
if n > 0:
binaryStr = str(n % 2) + binaryStr
n = n > 1
return binaryStr
def main():
n = int(input('Enter a positive integer please: '))
binaryNumber = ConvertNtoBinary(n)
print('n converted to a binary number is: ',binaryNumber)
main()
You forgot to call raw_input(). Right now you try to convert your prompt message to an integer which cannot work.
n = int(raw_input('Enter a positive integer please: '))
Of course a try..except around that line would be a good idea:
try:
n = int(raw_input('Enter a positive integer please: '))
except ValueError:
n = 0 # you could also exit instead of using a default value
In n = int('Enter a positive integer please: '), you are trying to make an int out of the string 'Enter a positive...'. I would assume you forgot your raw_input(). You could either do
n = int(raw_input('Enter a positive integer please: '))
or
n = raw_input('Enter a positive integer please: ')
n = int(n)
You can't cast a arbitratry string literal to an int. I think what you mean to do is call a prompt method of some sort that takes input from the user.

Categories

Resources