Print function input into int [duplicate] - python

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

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.

Grok Learning: Halve this TypeError [duplicate]

This question already has answers here:
How can I concatenate str and int objects?
(1 answer)
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 7 months ago.
I have to write a program that reads in a whole number and prints out that number divided by two. This is my code:
a= int(input("Number: "))
h= a/2
print("Half number: " + h)
But I keep getting this
Number: 6
Traceback (most recent call last):
File "program.py", line 3, in <module>
print("Half number: " + h)
TypeError: Can't convert 'float' object to str implicitly
I don't see anything wrong with my code and I have no idea what the error is. Any idea what's wrong?
The expression:
"Half number: " + h
is trying to add a string to a float. You can add strings to strings:
"This string" + ", then this string"
and floats to floats:
100.0 + 16.8
but Python isn't willing to let you add strings and floats. (In the error message above, Python has processed the first string and the addition, and it now expects a string -- that's why you get the error that it can't -- or at least won't -- convert a 'float' number to a string.)
You can tell Python this is what you really want it to do in a few ways. One is to use the built-in str() function which converts any object to some reasonable string representation, ready to be added to another string:
h = 100
"You can add a string to this: " + str(h)
a= int(input("Number: "))
h= a/2
print('Half number:', h)
Without the spaces in between though
Here is a very simple way to do it.
Here's a sample solution from Grok Learning:
n = int(input('Number: '))
print('Half number:', n/2)
Here's my explanation below:
As you might've already guessed, n here is a variable. And in this code, we will be assigning some information to n. int(input('Number ')) is the statement that Python will then read, and follow. int() tells Python that the input will be an integer, and input() allows the user to input whatever they would like to input. n/2 is simply another way of saying "n divided by two". print() tells Python to print a statement, and so print('Half number:', n/2) will print out that "Half number" is simply just half of the number entered above.
Here's an example of what the output should look like:
Number: 6
Half number: 3
(In that example, the input was 6.)
So, yes, I know that you may already know this stuff but I am leaving this information for people who may visit this website in the future. The error that you had was that you used a +, when you should've used a ,. Python is pretty strict when it comes to processing what you're saying, so it didn't allow you to put a str and an int together using a +. So next time, remember to use a ,.
I hope this helps you.

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

How can I convert and integer into a string? [duplicate]

This question already has answers here:
How to print list item + integer/string using logging in Python
(2 answers)
Closed 7 years ago.
I am coding in Python, and have reached an error that I cannot seem to solve. Here's the part of the code that it affects.
import random
a = raw_input("Enter text")
b = random.randrange(1,101)
print (a+b)
When I try to run the code, I get the error "TypeError: cannot concatenate 'str' and 'int' objects"
I want to know how to print the result of a+b.
To answer to the question in the title, you can convert an integer into a string with str. But the print function already applies str to its argument, in order to be able to print it.
Here, your problem comes from the fact that a is a string while b is an integer. The + operator works on two strings, or two ints, but not a combination of this two types. If you have two strings, the + will mean concatenate. If you have two ints, the + will mean add. It then depends on the result you want to get.
You can convert a string to an integer by using int.
Try this code:
import random
a = int (raw_input ("Enter int "))
b = random.randrange (1, 101)
print a + b

Concatenate string and int in Python 3 .4 [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 1 year ago.
I'm new to Python, so I've been running through my own set of exercises to simply start memorizing basic functions and syntax.
I'm using the PyCharm IDE and Python 3.4. I've run into an issue when running through some basic string and integer concatenation exercises. Each instance below is throwing an unsupported operand type. There are several threads on Stack Overflow that clearly states proper concatenation syntax, but the above error message continues to plague me.
print ("Type string: ") + str(123)
print ("Concatenate strings and ints "), 10
In Python 3+, print is a function, so it must be called with its arguments between parentheses. So looking at your example:
print ("Type string: ") + str(123)
It's actually the same as:
var = print("Type string: ")
var + str(123)
Since print returns nothing (in Python, this means None), this is the equivalent of:
None + str(123)
which evidently will give an error.
That being said about what you tried to do, what you want do to is very easy: pass the print function what you mean to print, which can be done in various ways:
print ("Type string: " + str(123))
# Using format method to generate a string with the desired contents
print ("Type string: {}".format(123))
# Using Python3's implicit concatenation of its arguments, does not work the same in Python2:
print ("Type string:", str(123)) # Notice this will insert a space between the parameters
Note that print is a function in Python 3. In Python 2, your first line would concatenate "Type string: " and "123" and then print them. In Python 3, you are calling the print function with one argument, which returns None, and then add "123" to it. That doesn't make any sense.
The second line doesn't generate an error in Python 2 or 3 (I've tested it with 2.7.7 and 3.2.3). In Python 2, you get
Concatenate strings and ints 10
while in Python 3, your script should only print
Concatenate strings and ints
This is because again, print is a function, and therefore you call it with the argument "Concatenate strings and ints". The , 10 makes your line a tuple of the return value of print, which is None, and 10. Since you don't use that tuple for anything, there is no visible effect.
Try format():
print("Type string: {}".format(123))
print("Concatenate strings and ints {}".format(10))
There is nothing wrong with this:
print ("Type string: ") + str(123)
print is just a function like anything else. And you're calling that function with one argument, "Type string: ", and then trying to add the result (which will be None) to the string '123'. That isn't going to work. If you wanted to add the two strings together, you have to put them into the same expression, inside the parentheses:
print("Type string: " + str(123))
Similarly:
print ("Concatenate strings and ints "), 10
This calls print with one argument, and then makes a tuple of the None returned by print and the number 10. If you want to pass 10 to the print call, it has to go inside the parentheses:
print("Concatenate strings and ints ", 10)
As gitaarik's answer points out, using str.format is more flexible, and avoids the possibility of problems like this. It also gives you code that works exactly the same way in both Python 2.6-2.7 and Python 3.x, which is pretty nice even if you aren't trying to write dual-platform/single-codebase code, because it'll be understandable even to people who only know one or the other.
I think this is a pretty cool way to concatenate a string and an int in Python:
print (f"Type string: {123}")
print (f"Concatenate strings and ints {10}")
You can do it like this:
c = 'Emerson'
d = 32
print("My name is %s and I am %d years old." %(c,d))
Result:
My name is Emerson and I am 32 years old.

Categories

Resources