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.
Related
print(*range(1, int(input())+1), sep='')
This was the code I found in a discussion on hacker rank. But I did not understand it.
Can anyone please explain this?
So, from what I can tell, this is how it works:
int(input())
This takes input from the user.
Next;
range(1,...+1)
This creates a range from 1 to our number we inputted earlier. The +1 means that it will include the max number.
And then:
print(*...,sep='')
The * sign, from what I can tell, just effectively returns each value in our range one to be printed.
The sep='' just means each value is separated by '' or nothing.
Hope this is useful to you.
[EDIT]
More on star and double star expressions in this post:
What does the star and doublestar operator mean in a function call?
Ok so we have print function. Inside we have this strange *range(1, int(input())+1) this is range function which return value from 1 to n (n is typed in input) in a form of a range object. * unpack this object to form like: 1 2 3 4 ... with spaces, so we have this sep='', keyword argument that makes separation from space to '' (no separate between).
Also you can do it like that:
n = input("Type integer value: ")
try:
[print(x+1,end="") for x in range(int(n))]
except ValueError:
exit("Typed string not number")
Hi so the question I completed involves while loops and although I finished it and got the expected outcome, I added a random line of code for "fun" to see what it would do, you could call it guessing and checking.
x = int(input())
increase = 0
while x != 0:
increase += x
**x = int(input())**
print(increase)
the line that I guessed has asterisks beside it, can someone please let me know what this simple line does.
If it helps:
My question is to input as many numbers as I please, but when I input the value 0, my code should return the sum of the number I inputted before the zero
x = int(input()) #takes user input string and try to convert to integer data type
increase = 0 # set value to variable increase
while x != 0: # condition
increase += x # it add/sum the value of the variable x to the value of the variable increase
x = int(input()) #takes user input string and try to convert to integer data type inside the while loop
print(increase) # print the value
watch this code in action on pythontutor
The function call input() takes user input from the console and makes it available to your code as a string. int(input()) converts the string input from the user, and tries to cast that value to an integer. That integer is then added to running count you have specified as increase.
Just to point out, you will get an error if a user specifies input that cannot be converted to an int, like typing in 'meow'. It will throw a ValueError.
The while loop waits for you to enter a value. This is done with input(). Because you need an integer (input always returns a string) int() is called on the input, which returns an integer (if possible). Everytime an input is made and converted to an integer the while loop starts the next iteration and checks if the previous input was equal to 0. If so, the while loop stops and (in this case) your print statement is executed.
This is exactly what you wanted to do.
So... I have this primitive calculator that runs fine on my cellphone, but when I try to run it on Windows 10 I get...
ValueError: could not convert string to float
I don't know what the problem is, I've tried using raw_input but it doesn't work ether. Please keep in mind I'm green and am not aware of most methods for getting around a problem like this
num1 = float(input ()) #take a float and store it
chars = input () #take a string and store it
num2 = float(input ())
your code only convert string that are integers like in below statement
num1 = float(input ()) #take a float and store it ex 13
print num1 # output 13.0
if you provide 13 as a input it will give the output as 13.0
but if you provide SOMEONEE as input it will give ValueError
And it is same with the case of raw_input() but the difference is that by default raw_input() takes input as a string and input() takes input as what is provided to the function
I think this is happening because in some cases 'input' contains non-numerical characters. Python is smart and when a string only contains numbers, it can be converted from string to float. When the string contains non-numerical characters, it is not possible for Python to convert it to a float.
You could fix this a few ways:
Find out why and when there are non-numerical characters in your input and then fix it.
Check if input contains numbers only with: isdecimal()
Use a try/except
isdecimal() example:
my_input = raw_input()
if my_input.isdecimal():
print("Ok, go ahead its all numbers")
UPDATE:
Two-Bit-Alchemist had some great advice in the comments, so I put it in my answer.
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(',')]
I'm making a game where the "Computer" tries to guess a number you think of.
Here's a couple snippets of code:
askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.
Any suggestions?
It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.
However here is what you want to do:
askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))
You save it as a number and not as a string.
As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str(); instead, you can convert it to an integer using int(). Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:
def int_raw_input(prompt):
while True:
try:
# if the call to int() raises an
# exception, this won't return here
return int(raw_input(prompt))
except ValueError:
# simply ignore the error and retry
# the loop body (i.e. prompt again)
pass
You can then substitute this for your calls to raw_input.
The range numbers were stored as strings. Try this:
askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'