Having problems with python - 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.

Related

Why does this error happen? TypeError: can only concatenate str (not "int") to str

This is my Python code and I would like to know why the error
TypeError: can only concatenate str (not "int") to str
is happening, and how to fix it:
import random
print("Welcome to the Text adventures Game\nIn this Game you will go on an amazing adventure.")
print("Following are the rules:\n1.You can type the directions you want to go in.\n2. There will be certain items that you will encounter. You can type grab to take it or leave to leave it\n3.In the starting, we will randomly give you 3 values. It is your choice to assign them to your qualites.\nYour Qualities are:\n1.Intelligence\n3.Attack\n4.Defence\n These Qualities will help you further in the game")
print("With these, You are all set to play the game.")
Name=input(str("Please Enter Your Name: "))
a=input("Hi "+Name+", Ready To Play The Game?: ")
Intelligence=0
Attack=0
Defence=0
if a=="yes"or a=="y":
value1=random.randint(0,100)
choice1=input("Your Value is: \n"+value1+ "\nYou would like to make it your Intelligence,Attack Or Defence level? ")
You are trying to add int to string
try this
if a=="yes"or a=="y":
value1=random.randint(0,100)
choice1=input("Your Value is: \n"+str(value1)+ "\nYou would like to make it your Intelligence,Attack Or Defence level? ")
This happens because the value stored in the variable is an integer and you are concatenating it in between string.
to do so:----
use str() method :
The str() function returns the string version of the given object.
It internally calls the __str__() method of an object.
If it cannot find the __str__() method, it instead calls repr(obj).
Return value from repr()
The repr() function returns a printable representational string of the given object.
so typecasting value1 integer variable with str().
str(value1)
Happy coding :)
You want to concatenate a string with an integer and it is not possible. You should cast your integer to string, like this: str(value1).
BUT, more efficient to use the .format() method of the string. This method automatically cast the integer type to str.
In your case:
choice1=input("Your Value is: \n{}\nYou would like to make it your Intelligence,Attack Or Defence level? ".format(value1))
Or if you use Python 3.6+, the formatted string is also available. The starting f character indicates the formatted strings.
In your case:
choice1=input(f"Your Value is: \n{value1}\nYou would like to make it your Intelligence,Attack Or Defence level? ")
You can find several Python string formatting on this page: https://realpython.com/python-string-formatting/

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

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.

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

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

Is it ever useful to use Python's input over raw_input?

I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous input function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to eval behind it.
So my question is, why does the input function call eval, and what would this ever be useful for that it wouldn't be safer to do with raw_input? I understand that this has been changed in Python 3, but it seems like an unusual design decision in the first place.
Python 2.x input function documentation
Is it ever useful to use Python 2's input over raw_input?
No.
input() evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, __import__, and the if/else operators, literally anything Python can do can be achieved with a single expression. Malicious users can use input() to remove files (__import__('os').remove('precious_file')), monkeypatch the rest of the program (setattr(__import__('__main__'), 'function', lambda:42)), ... anything.
A normal user won't need to use all the advanced functionality. If you don't need expressions, use ast.literal_eval(raw_input()) – the literal_eval function is safe.
If you're writing for advanced users, give them a better way to input code. Plugins, user modules, etc. – something with the full Python syntax, not just the functionality.
If you're absolutely sure you know what you're doing, say eval(raw_input()). The eval screams "I'm dangerous!" to the trained eye. But, odds are you won't ever need this.
input() was one of the old design mistakes that Python 3 is solving.
Python Input function returns an object that's the result
of evaluating the expression.
raw_input function returns a string
name = "Arthur"
age = 45
first = raw_input("Please enter your age ")
second = input("Please enter your age again ")
# first will always contain a string
# second could contain any object and you can even
# type in a calculation and use "name" and "age" as
# you enter it at run time ...
print "You said you are",first
print "Then you said you are",second
examples of that running:
Example: 1
Prompt$ python yraw
Please enter your age 45
Please enter your age again 45
You said you are 45 Then you said you are 45
Example: 2
Prompt$ python yraw
Please enter your age 45 + 7
Please enter your age again 45 + 7
You said you are 45 + 7 Then you said you are 52
Prompt$
Q. why does the input function call eval?
A. Consider the scenario where user inputs an expression '45 + 7' in input, input will give correct result as compared to raw_input in python 2.x
input is pretty much only useful as a building block for an interactive python shell. You're certainly right that it's surprising it works the way it does, and is rather too purpose-specific to be a builtin - which I presume is why it got removed from Python 3.
raw_input is better, It always returns the input of the user without changes.
Conversely The input() function will try to convert things you enter as if they were Python code, and it has security problems so you should avoid it.
In real program don't use input(), Parse your input with something that handles the specific input format you're expecting, not by evaluating the input as Python code.

Categories

Resources