Include a variable into the input function prompt [duplicate] - python

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

Related

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

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))

looping not exiting and not printing the results at the end [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping to create a code to output if a next number entered is Up, Down or Same as the first one. I wanted it to exit when '0' is entered. I also wanted it to print the 'Up', 'Down', or 'Same' result at the end when exited with '0' instead of each time a number is entered.(if user enters: 4, 6, 1, 1, then 0 to exit, the final output will be Up, Down, Same printed.) Please tell me what I am missing, here is what i have so far:
firstNumber = input('Please enter your first number:')
nextNumber=input('Enter the next number(0 to finish)')
while nextNumber !=0:
if firstNumber<nextNumber:
print ('Up')
elif firstNumber>nextNumber:
print ('Down')
elif firstNumber==nextNumber:
print ('Same')
firstNumber = nextNumber
nextNumber=input('Enter the next number(0 to finish)')
You are comparing string, not numbers.
You should cast your input to integers with int().
here:
try:
firstNumber = int(input('Please enter your first number:'))
nextNumber = int(input('Enter the next number(0 to finish)'))
except ValueError:
# Handle cast error here
pass
while nextNumber !=0:
...
Note
As blubberdiblub explained:
< > compare pointer code of strings, that means "8" < "10" returns False while 8 < 10 returns True
input
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So use
int(input(...))

python - inputting numbers that start with 0

I'm making a program in python. It is suppose to take in a GTIN number and put in a list and then check if it's valid. The program works, but as soon as I enter a GTIN number that starts with a 0, I get a "invalid token (, line 1)" error. I really need a solution because some products have their GTIN numbers starting with a 0.
when I input a number for example:
96080832
The program works great.
When i put in a number like:
00256986
I get an error:
invalid token (<string>, line 1)
pointing to this line:
inputtedInt = int(input("Enter the gtin number: "))
Whole def:
def chooseOption(inputInt):
while(inputInt > 0 and inputInt < 4):
if(inputInt == 1):
print("you picked option number 1")
showOptions()
break
elif(inputInt == 2):
print(" ")
inputtedInt = int(input("Enter the gtin number: "))
gtin = map(int,str(inputtedInt))
checkValidity(gtin, 2)
print(" ")
showOptions()
break
elif(inputInt == 3):
print("you picked option number 3")
showOptions()
break
else:
option = int(input("Error - enter a number from 1 to 3. : "))
chooseOption(option)
Thanks in advance.
You seem to be using Python 2. In Python 2, input tries to evaluate the input string as a Python expression, and a leading 0 on a numeric literal in Python 2 syntax means that the number is in octal, or base 8. Since 8 and 9 are not valid digits in base 8, this input constitutes a syntax error.
If you were supposed to be using Python 3, get on Python 3. If you're supposed to be on Python 2, use raw_input instead of input.
Additionally, if you care about preserving things like leading zeros, you should keep the input as a string and only call int on it when you want to do math on it as an integer.
Error is raised because you are mapping str ant/to int in line:
gtin = map(int,str(inputtedInt))
for example if you ty to run:
a = 005
You will get following error:
File "<stdin>", line 1
a = 005
^
SyntaxError: invalid token
Sollution -> you should use stringsfor GTIN number :)

How to find a specific number from a user inputed list in python [duplicate]

This question already has answers here:
Python - Count elements in list [duplicate]
(7 answers)
Closed 7 years ago.
I want the program to find the number of times a particular number occurs within a list. What am I doing wrong here?
def list1():
numInput = input("Enter numbers separated by commas: ")
numList = numInput.split(",")
numFind = int(input("Enter a number to look for: "))
count = 0
for num in numList:
if num == numFind:
count += 1
length = len(numList)
# dividing how many times the input number was entered
# by the length of the list to find the %
fraction = count / length
print("Apeared",count,"times")
print("Constitutes",fraction,"% of this data set")
list1()
numList isn't a list of numbers, it's a list of strings. Try converting to integer before comparing to numFind.
if int(num) == numFind:
Alternatively, leave numFind as a string:
numFind = input("Enter a number to look for: ")
... Although this may introduce some complications, e.g. if the user enters 1, 2, 3, 4 as their list (note the spaces) and 2 as their number, It will say "Appeared 0 time" because " 2" and "2" won't compare equal.
There are 2 issues with the code, First you are comparing int with str and the second is count / length. In Python when you divide int with int you get an int returned not a float (as expected.) so fraction = flost(count) / length would work for you , also you need to convert all the elements in the list to integers which can be done as :
numList = map(int, numInput.split(","))

Python - sum of two numbers program error [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
I was just getting into Python programming. I wrote a simple program to calculate sum of two user-input numbers:
a,b = input("enter first number"), input("enter second number")
print("sum of given numbers is ", (a+b))
Now if I enter the numbers as 23 and 52, what showed in the output is:
sum of given numbers is 23 52
What is wrong with my code?
input() in Python 3 returns a string; you need to convert the input values to integers with int() before you can add them:
a,b = int(input("enter first number")), int(input("enter second number"))
(You may want to wrap this in a try:/except ValueError: for nicer response when the user doesn't enter an integer.
instead of (a+b), use (int(a) + int(b))
I think it will be better if you use a try/except block, since you're trying to convert strings to integers
try:
a,b = int(input("enter first number")), int(input("enter second number"))
print("sum of given numbers is ", (a+b))
except ValueError as err:
print("You did not enter numbers")
By default python takes the input as string. So instead of adding both the numbers string concatenation is occurring in your code. So you should explicitly convert it into integer using the int() method.
Here is a sample code
a,b=int(input("Enter the first number: ")),int(input("Enter the second number: "))
print("Sum of the numbers is ", a + b)
For more information check this link
https://codingwithwakil.blogspot.com/2021/05/python-program-to-add-two-numbers-by.html

Categories

Resources