multiple inputs using int instead of eval - python

Small question: Why doesn't this piece of code work when I use int but does when I use eval?
int can only take one input? Is there a way to make it take multiple inputs as concise as using eval? Int is a stronger condition so that's why I am curious about how it would work.
a,b,c = int(input("enter numbers: "))
print(no_teen_sum(a,b,c))
This gives ValueError: invalid literal for int() with base 10, but the following code does work.
a,b,c = eval(input("enter numbers: "))
print(no_teen_sum(a,b,c))

int takes one input and possibly a base:
>>> int('46',7) # 46 is 34 in base 7
34
But you can use int along with map:
>>> map(int,['1','2','3'])
[1, 2, 3]

Use list comprehension:
def main():
numbers = input("enter numbers: ").split()
print(no_teen_sum(*[int(n) for n in numbers)])
main()

Python is trying to parse the whole string as one integer rather than three.
What you could do is:
a, b, c = map(int, input("enter numbers: ").split())
This way you are splitting the list into three strings, and then converting (mapping) each string to an int.

int can only take one input?
Yes, and that is technically true for eval, too. It's just that eval might return something other than an int. In your case, I'm assuming you enter something like 1, 2, 3 on the input prompt. eval simply parses that as a tuple, which it returns, and unpacks into your three variables.
You can, however, easily achieve something similar to what you want using list comprehension:
a, b, c = [int(x.strip()) for x in input("Enter numbers: ").split(",")]
This has the added benefit that you don't risk having some completely unexpected type returned from eval.
One caveat with using eval that should perhaps be worth noting is that it accepts any valid Python syntax and executes the parsed result, which may include arbitrary function calls, including code to erase your hard drive. Not much of a problem when you're just writing a program for yourself to use, but just so that you know.

Related

Using input() as parameter for range() in Python

How does input() work as a parameter to range() in Python?
For example:
Say the user inputs multiple numbers 10 and 2 or more literally type "10 2"
for i in range(int(input())):
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
What range does the for loop use then? Is it (0,10), (0,2) or something else? Or, said differently, which number does the range use for the upper limit if the user inputs multiple numbers? More generally, I am trying to understand the purpose of the for loop here and why the code can't just be:
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
input() values will be stored as str.
It all comes down to what the user inputs. The piece of code you provided is very bad, because the user has to guess what to input and when. But the logic works as follows:
If you type in a single value, then int(input()) will convert that value to integer. For example, if you input 2, then input() will hold the string "2" and int("2") will yield integer 2.
If you have multiple values, then you cannot convert to int right away, because what the hell does int("2 10") mean? That is why you have to use .split(), to separate these multiple values in many singular values. For example, if you run x = input() and type in 2 10, then x will hold the string "2 10". Now, "2 10".split() yields the list of strings ["2", "10"].
The piece of code map(int,input().split()) comes in to convert this list of strings to a list of integers. It maps each value to a new value using the function int to transform it.
Now that this is established, it becomes easier to understand how this works in a for loop using range.
The range type, as per docs, may have one parameter stop or three arguments (start, stop [, step]) in its constructor. These arguments are all integers.
Thus, the values from input() have to fit this structure. If you type in 2 10 in input, and try to do range("2 10"), you'll receive an error. Because you are passing one argument of type str. That is why you have to convert to integer first. But you cannot convert "2 10" to integer right away, as we just discussed. That is why you have to split first, and then convert each value to int, and just then pass these as arguments to range().
So, to summarize, given x = input() and you type in 2 10, here is what does not work:
>>> int(x)
>>> range(x)
what does work:
>>> a,b=map(int,input().split())
>>> range(a, b)
The first input() will determine the stop condition of the for loop
Which means the first input() determines the number of time your for loop will be executed
Other input() will assign the values to a and b as string
The above is equivalent to:
stop = input()
stop = int(stop)
for i in range(stop):
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
But if the first input() is given as "10 10" then the code will throw you an error something like the string can not be converted to int
The a,b=map(int,input().split()) means you are expecting an input of two numbers separated by spaces and these inputs will be given exactly stop number of times
This pattern is used when you want to read n lines from the input, for example the input is:
3
1 2
3 4
5 6
The first input will determine how many times the for loop needs to be run to read all the lines.
For a single line of input like "10 2" you don't need to use a loop.

How to make random numbers with variables in python?

I encountered a problem while programming in Python, and here's a bite of my program:
import random
p = raw_input('Percent Probability Program\nWhat percent?\n ')
r1 = random.randint(p, 100)
It gave me an error that the first value in the random command wasn't an integer. Please help!
Python 2
raw_input returns a str object, which is basically a string - no math operations can be performed on strings, and it's not the correct type for randint.
You can either convert your input to int using int(raw_input()) or just use the method input(), which returns an evaluated value (in your case, it should return an int)
Python 3
In python 3, the input function returns an str object, so converting it to int will be int(input())

Print function input into int [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
My goal is very simple, which makes it all the more irritating that I'm repeatedly failing:
I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is 3, the code would be:
print(*range(1, 3+1), sep="")
which obviously works, however when using an n = input() , no matter where I put the str(), I get the same error:
"Can't convert 'int' object to str implicitly"
I feel sorry to waste your collective time on such an annoyingly trivial task..
My code:
n= input()
print(*range(1, n+1), sep="")
I've also tried list comprehensions (my ultimate goal is to have this all on one line):
[print(*range(1,n+1),sep="") | n = input() ]
I know this is not proper syntax, how on earth am I supposed to word this properly?
This didn't help, ditto this, ditto this, I give up --> ask S.O.
I see no reason why you would use str here, you should use int; the value returned from input is of type str and you need to transform it.
A one-liner could look like this:
print(*range(1, int(input()) + 1), sep=' ')
Where input is wrapped in int to transform the str returned to an int and supply it as an argument to range.
As an addendum, your error here is caused by n + 1 in your range call where n is still an str; Python won't implicitly transform the value held by n to an int and perform the operation; it'll complain:
n = '1'
n + 1
TypeErrorTraceback (most recent call last)
<ipython-input-117-a5b1a168a772> in <module>()
----> 1 n + 1
TypeError: Can't convert 'int' object to str implicitly
That's why you need to be explicit and wrap it in int(). Additionally, take note that the one liner will fail with input that can't be transformed to an int, you need to wrap it in a try-except statement to handle that if needed.
In your code, you should just be able to do:
n = int(input())
print(*range(1,n+1),sep="")
But you would also want to have some error checking to ensure that a number is actually entered into the prompt.
A one-liner that works:
print(*range(1, int(input()) + 1), sep="")

Differentiating Python variables as str or int

I have a file that has 3 values on each line. It is a fairly random file, and any of these values can be str or int.
George, 34s, Nikon
42, absent, Alan
apple, 111, 41
marked, 15, never
...
So, I read in the line, and using split I get the first value:
theFile = r"C:\... "
tDC = open(theFile, "r")
for theLine in tDC:
a, b, c = theLine.split(',')
So far so good.
Where I'm stuck is when I try to deal with variable a. I need to deal with it differently if it is a str or if it is an int. I tried setting a = int(a), but if it is a string (e.g., 'George') then I get an error. I tried if type(a) = int or if isinstance(a,int), but neither work because all the values come in as a string!
So, how do I evaluate the value NOT looking at its assigned 'type'? Specifically, I want to read all the a's and find the maximum value of all the numbers (they'll be integers, but could be large -- six digits, perhaps).
Is there a way to read in the line so that numbers come in as numbers and strings come in as strings, or perhaps there is a way to evaluate the value itself without looking at the type?
The first point is that you need some rule that tells you which values are integers and which ones aren't. In a data set that includes things like 32s, I'm not sure it makes sense to just treat anything that could be an integer as if it were.
But, for simplicity, let's assume that is the rule you want: anything that could be an integer is. So, int(a) is already pretty close; the only issue is that it can fail. What do you do with that?
Python is designed around EAFP: it's Easier to Ask Forgiveness than Permission. Try something, and then deal with the fact that it might fail. As Cyber suggests, with a try statement:
try:
intvalue = int(a)
except ValueError:
# Oops, it wasn't an int, and that's fine
pass
else:
# It was an int, and now we have the int value
maxvalue = max(maxvalue, intvalue)
isalpha() Returns "True" if all characters in the string are in the alphabet
isnumeric() Returns "True" if all characters in the string are numeric
so;
data="Hello World"
print(data.isnumeric()) #it will retuns with False
print(data.isalpha()) # True
Sorry for my soulles answer, I just came here for same issue, I found a different way and wanted to share with you
values = theLine.split(',')
for value in values:
try:
number = int(value)
# process as number
except ValueError:
# process value as string
this :
def ret_var(my_var: int) -> int:
try:
intvalue = int(my_var)
return my_var
except ValueError:
print("my_var not int!")

How do I get Python 2.7 to accept multiple variable inputs on a single line

Im trying to get the user to input the length and width of a rectangle at the same time.
length,width = float (raw_input("What is the length and width? ")).split(',')
When I run the program, however, and enter two variables such as 3,5 I get an error saying that I have an invalid literal for type float().
Well, that's because you're entering two numbers separated by a comma, but splitting that value on a period. Split it on a comma and it should work much better.
First, why does this fail:
float (raw_input("What is the length and width? ")).split(',')
The split(',') splits a string into a sequence of strings. You can't call float on a sequence of strings, only on a single string. That's why the error says it's "an invalid literal for type float".
If you want to call the same function on every value in a sequence, there are two ways to do it:
Use a list comprehension (or a generator expression):
[float(x) for x in raw_input("What is the length and width? ")).split(',')]
Or the map function:
map(float, raw_input("What is the length and width? ")).split(','))
I would use the list comprehension, because that's what the BDFL prefers, and because it's simpler for other things you may want to do like x[2], but it really doesn't matter that much in this case; it's simple enough either way, and you should learn what both of them mean.
You also will probably want to cast to integers:
prompt = "what is the length and width? "
inpt = raw_input(prompt)
length, width = [int(i) for i in inpt.split(',')]

Categories

Resources