I received an error message that I don't quite understand - python

I am working on a program and I received an error message that said:
print("I will set a timer for " + shortesttime + "minutes")
TypeError: can only concatenate str (not "int") to str
I assumed it meant that I had to change the variable from an int to a string but when I tried it it didn't work. Afterwards I just thought that maybe I wasn't understanding the error message correctly.
Here's some code for context:
shortesttime = hwt.index(min(hwt))
smallesthwitem = (uhw[hwt.index(min(hwt))]) #it's finding the position of the smallest item in homeworktime and then, for example if the place of that was 2 it would find what's at the second place in uhw
print("So let's start with something easy. First you're going to do " + smallesthwitem)
print("I will set a timer for " + shortesttime + "minutes")
Sorry about the weird variable names

The error says that concatenating (with +) a string to an integer is not allowed. Other languages (BASIC comes to mind) let you do that. The best thing to do is to use a formatter. If you want a simple formatting, then all you need is:
print(f"I will set a timer for {shortesttime} minutes")
There's options in formatters to add commas for thousands and other stuff, but this is easier than mucking with type conversions. This format was introduced in python 3.6 (called f-strings). If you are between 3.0 and 3.5 use
print("I will set a timer for {} minutes".format(shortesttime))
Which is equivalent, just a bit longer and not as clear.

Always Remember : To join multiple strings, You perhaps have to strings only. For example, You can't concatenate int with str .
So to print it you have to convert it to a string which is known as str in python world.
On the 4th line change it to : print("I will set a timer for " + str(shortesttime) + "minutes")
One more way would be formatted string :
Like this, print(f"I will set a timer for {shortesttime} minutes"). Formatted strings automatically converts any datatype to string.

As #ferdbugs mentioned earlier, you can cast any value to a string type.
Your code should look somewhat like this
shortesttime = hwt.index(min(hwt))
smallesthwitem = (uhw[hwt.index(min(hwt))]) #it's finding the position of the smallest item in homeworktime and then, for example if the place of that was 2 it would find what's at the second place in uhw
print("So let's start with something easy. First you're going to do " + smallesthwitem)
print("I will set a timer for " + str(shortesttime) + "minutes")
Hope this helps! Do let me know in the comments if you still get the same error or a different error.

Try:
print("I will set a timer for " + str(shortesttime) + "minutes")
You can cast it to a string.

Related

Two ways to use print function. Does it matter which is used? [duplicate]

This question already has answers here:
Format strings vs concatenation
(7 answers)
Closed 3 years ago.
This is a very simple question, but I am a new Python learner and this is bugging me.
I am using Python version 3.7.4. I want to know if it matters which way below I should use the print function or is one way more appropriate to use under some select circumstance.
print(f"Miles Per Gallon:\t\t {mpg}")
vs
print("Miles Per Gallon: \t\t " + str(mpg))
The first option (formatting) is much easier to read and write. For example instead of writing:
print('He had ' + str(cookies) + ' cookies and ' str(bananas) + ' bananas')
You can simply write
print(f'He had {cookies} cookies and {bananas} bananas.')
doing it that way you also avoid having to explicitly call str, as format does that for you. You can also use formatting like this:
print('I have {} cookies'.format(cookies))
Short answer: there's no difference between the two.
In the first example you provided (print(f"Miles Per Gallon:\t\t {mpg}")), you're doing something in Python called formatting. It's a pretty useful concept that can come in handy when you want to put lots of things in one string without having to concatenate all of them.
In your second example, print("Miles Per Gallon: \t\t " + str(mpg)), instead of using formatting, you're converting mpg to a string, and then telling python to "concatenate" (merge) the two (the string to the left and the string to the right) together. + in Python will both concatenate and add numbers, depending on the types of the variables surrounding it.
Formatting in Python becomes very useful when you need to put a lot of things in one string. For example, let's say I want to print the value of 3 variables, a, b, and c, and I want to label them. For the sake of example, we'll say that we don't know if the variables are type int or str; this is important, because it means we need to explicitly convert them to a string, otherwise we run the risk of Python throwing a TypeError (specifically, TypeError: can only concatenate str (not "int") to str). To do this with concatenation (as your second example does), this is what would be done:
"The value of a is " + str(a) + ", b is " + str(b) + ", c is " + str(c)
As you can see, that can be kind of messy, which is where formatting comes in to play. There are lots of ways to format strings in Python. I'll use yours in addition to another common one, but it's entirely personal preference which you would like to use.
f"The value of a is {a}, b is {b}, c is {c}"
"The value of a is {0}, b is {1}, c is {2}".format(str(a), str(b), str(c))
This is a lot cleaner, and makes for more easily readable code than concatenation, as well as making editing it less of a headache. More info on various ways of formatting string is available in the documentation here.
Hope this helps!
The second one has an explicit casting str(), but the first one has an implicit casting. It depends when you will need an explicit casting.
You can also take a look at this question: How to print like printf in Python3?

Basic Input/Output in Python

I am using notepad++ to write code for python and have a variable that I need to add 1 to for my next question. I am new to coding and would like to know how to achieve this. I would also like to phrase the question so that the answer (variable plus 1) is placed between text. Below, in my next line I would like it to read (for instance if the number is 3) How often do the 4 of you visit?
I have tried different ways of framing my variable +1 within parentheses and quotation marks but at best, when run, it shows exactly what I wrote not the answer to the equation.
famnumber = input ("How many of your family members still live there?")
I would like the answer to appear within text as noted above if possible.
Here is some code:
famadd = float(famnumber) + (1)
print ("Do all (famadd) of you get together often?")
There are several ways to do this. Note that when you you get something from input, it's a string. So using famnumber += 1 won't work, as you can't add a number to a string. So we have to turn the numeral string into an actual number. You can use int() to convert the input text into an integer. Then to include the value in a new string for your next question, use %d ('d' for 'digit'). This makes more sense than using a float, since people don't report family members in fractions of whole numbers (likewise, you don't want to say something like 'How often do the 4.0 of your meet?').
famnumber = input("How many of your family members still live there? ")
new_number = int(famnumber) + 1
next_question = input("How often do the %d of you meet? " % new_number)
Other ways to accomplish the same thing is converting 'famnumber' itself from a string to an integer, then back into a string to join in the sentence. Personally I'd go with the previous method, but this should give you an idea of some of the other things you can do in Python:
famnumber = input("How many of your family members still live there? ")
famnumber = int(famnumber)
famnumber += 1
next_question = input("How often do the " + str(famnumber) + " of you meet? ")
Also, while Notepad++ is a great text editor, if you're planning on doing a lot of Python scripting and writing, you may want to consider instead using an IDE, such as PyCharm, or IDLE which is included in the Python package. Tools like this make it easier for yourself to read and run your code.
I think you are looking for this kind of code:
famnumber = input("How many of your family members still live there?")
incremented_number = int(famnumber) + 1
next_number = input("How often do you " + str(incremented_number) + "visit")
print(next_number)
In the second line simply cast the input to int and increment it by one.
In the third line put the variable where you want it to be shown surrounded by + signs. You have to cast it to a string by using str() because the return type itself is a string. You can verify the type of the variable next_number simply by adding this line print(type(next_number))

TypeError: Cannot concatenate 'str' and 'int' [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 months ago.
I'm starting with some basic stuff to get a feeling for how to make a text based game. After creating the .py file in my IDE, I open terminal and use bash to open the .py file.
hpGanon = 10
damage = input("How much damage did you do with the Master Sword?")
hpGanon = hpGanon - damage
print("Ganon now has " + hpGanon + "hit points.")
At the end when I want it to print, bash tells me it cannot concatenate 'str' and 'int' objects.
I tried following what was said in the following post, Python: TypeError: cannot concatenate 'str' and 'int' objects
But I'm not getting the result I want.
I just want it to say: "Ganon now has x hit points."
Any ideas?
I'm not entirely sure (I have never coded with Python before) but it seems that the hpGanon variable is an integer and not a string, so it cannot put the two together. To convert an integer to a string in Python (I searched this up :P), you need to do str(integer).
So, to implement this in your example, try something like this:
print("Ganon now has " + str(hpGanon) + "hit points.")
You can do your mathematical calculation and convert it into string, for example
a = x*3
str(a)
and now if you call it in your print statement, it will work.
a = x*3
str(a)
print("3 x {} = {} ").format(x,a)

some simple coding in python, don't know what to do

I wanted to do something like this:
for i in range(999999999999999):
print ("sending messages no." + i)
but just don't know the proper way to do it since it doesn't work like this.
The problem is, that your value i is an integer and the print-function takes a string as parameter. Therefore you need to cast your variable using the str() function.
Your code should look like this:
for i in range(999999999999999):
print ("sending messages no." + str(i))
Now, I encourage people to learn Python and so I am glad to help you out but next time, if you get a "TypeError: cannot concatenate 'str' and 'int' objects" maybe you should first check with Google (or any other place) what this error means, since it actually tells you that i is an integer and it cannot convert that to a string.
Cheers

Having problems with python

I'm new to python and I'm trying to do a simple application (age calculator); I'm using Python 3.
This is my code:
date=2012
age=input("type in the date you born to calculate your age")
print ("your age is ") + (date-age)
It seems fine to me, but it gives me a TypeError: cannot concatente 'str' and 'int' objects.
Pass everything as a series of arguments to the print function:
print("your age is", date - int(age))
The print() function will convert the result of date - int(age) to a string for you. Note that you need to turn age (a string) into an integer first before you can subtract it from date though.
Python is strongly typed so you need to convert your data to the appropriate type.
age is a str (string), because it comes from an input. You should write:
date - int(age)
print ("your age is ") + (date-age) is not going to work for two reasons:
print in python 3 is a function so it only consider print ("your age is ") + (date-age) as its argument list;
Again, you're concatanating a str and an int, which is illegal in a strongly typed language.
The last conversion can be overridden since print does all the job for you:
print("your age is ", date - int(age))
input is going to give you a string. 2012, however is an int. They need to both be of arithmetic types to do mathematical operations on them. You want input to be a number, probably an int. Cast it as such with int(age).
So you would do print("Your age is ", date - int(age))
To nitpick your code, what if I was born in December 1992? Then your code would say I'm 20 even though I'd actually be 19. Also, what if I type in the actual date I was born, June 6, 1992?
These aren't relevant if you're just getting started and learning the syntax, but it's good to think about because you'll quickly find that those kinds of things are what will actually give you problems in programming, while the basic syntax and little technicalities tend to be things that you can look up on Google or use a cheat-sheet for (my preferred approach since I work with so many different languages with C-style syntax) after you gain familiarity with the language.
As you learn python, it's a good idea to take the error as it appears on the last line and feed that to a search engine.
TypeError: cannot concatenate 'str' and 'int' objects is by no means unique.
TypeError: cannot concatenate 'str' and 'int' objects
The issue here is that you're trying to concatenate a string and an int. That is not supported by Python (or most other languages), and that is what the error message is telling you. What you've done is wrong because you are mixing up two different concepts
Incorrectly called the function - you should call it this way.
print('Your age is: ', date-age)
You used the + operator. This is an alternate method for concatenating a string and number, however to do that you have to first make sure they're both of the same type. In this case - String. You can do this by using the string function.
print('Your age is: ' + str(date-age))
A better way to have done this would be by using string formatting, mainly because it supports various formats without the need to convert them into strings as well as making a long string of text with multiple values easier.
print('Your age is: %d' % date-age)
You can read more about string formatting here.
:)
First thing you want to do is keep everything you want to print within the print() function brackets.
print ("your age is ") + (date-age)
Will not work.
This may work better
print("your age is" + str(date-int(age)))
As you move on with python you will realize why you can not do what you did with the print function.
Anyway I hope this was helpful for you.
Also you may notice in the code I used some functions; str() and int(). These are type conversion function. You may have came across these before or you will do very soon.
Try:
print("Your age is ",date-int(age))
str will cast your integer result to a string so that it can properly be "added" to the rest of the string.

Categories

Resources