Unsupported Operand Error generated from custom factorial function - python

f = input("Enter the number to be squared : ")
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(f))
I am trying to get the factorial of the input number
When running the code I receive the following error:
TypeError: unsupported operand type(s) for -: 'str' and 'int'

You have to typecast your input into float or integer for it to be accepted on your mathematical equation. You can even place that in a while loop together with the try: and except ValueError: to cover the error in entry or give messages when your user does not satisfy the type you want your f variable. You can read the documentation for more info.
f = int(input("Enter the number to be squared : "))
OR
f = float(input("Enter the number to be squared : "))
On your original code f would take any a string value even if the user inputs the number 2 for example. So when you call the function that solves your factorial, it will return an error, because of course, you cannot do factorial notation on a string.

You forgot closing parenthesis ')' at the parenthesis end.
The data type of variable 'f' must be an integer and you are passing a string. As 'input' assigns string data type by default to the variable.
Make the following changes:
f = int(input("Enter the number to be squared : "))
print(factorial(f))
to lines 1 and the last line respectively.

The first problem that I see is with your data types. You will need to convert f to either an integer or a float so that it can be used in the mathematical operations in your function. You may also want to include some exception handling in case the user enters something other than a number.
You can convert the type by using int(f) or float(f)
As another commenter mentioned, you are also missing a parenthesis at the end of print(factorial(f).
If you make these changes your code should run.

Related

Keep getting error when using += operation between two variables - Python

I currently have a bit of code that adds a certain amount of points to a plyers score:
points = 5
player1 = 0
float(points)
float(player1)
player1 += points
points = 0
The problem is when I run this I get this error:
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
At first, I thought it had to do with the data types of the variables, points and player1 but I have a float function right before it. Also just for debugging purposes I wrote a bool statement print(bool(float(var))) to check if it was floating correct and it wasn't. The points variable floated correctly but it was saying that player1 was not a float. Any ideas on why this is happening?
If you are reading user input, you need to assign the result of float to the variable.
points = float(points) # convert existing string, or use float(input())
player1 = float(player1)
First of all, I was not able to reproduce the error, meaning I executed your code and did not get the error.
Second: When you cast a variable as: float(points) you must save the casting in a variable (or update the previous one).
points = float(points)
Note: in your case, you don't need to cast the variable to float because you are using only int values.

"totalarray=sum(array) TypeError: unsupported operand type(s) for +: 'int' and 'str'"?

array = []
for i in range(6):
array.append(input("Enter a number: "))
decision=input("Do you want the total or the average? ")
totalarray=sum(array)
if decision=="total":
print(totalarray)
elif decision=="average":
print(totalarray/6)
else:
print("Invaild option")
For this program i am supposed to ask the user to enter 6 numbers which are then stored in an arry. The user should be able to pick to see either the total or the average of these numbers. How do I prevent the TypeError?
cast input values into integer since sum function of python refers to integers not to strings.
array.append(int(input("Enter a number: ")))
How do I prevent the TypeError?
In Python 3, input returns the user's input as a string (always). If you want to use it as something other than a string you need to perform that conversion yourself based on what "number" you expect (e.g. integer, float, decimal, ...)

Converting decimal numbers to binary with functions in python

I have to create a program to convert decimal numbers to binary for my class but im lost. These are the directions.
3 Files must be used
user_input.py
Obtain an integer from the user between 0-255.
No conversion or print statements allowed in the user_input.py
Obtaining the integer must be done in a function
No import statements allowed
conversion.py
Convert the number provided to a binary number (e.g., 254 provided and converted to 11111110)
No print statements, input statements, or built in functions to convert a number to binary. Conversion must be done manually.
Small hint, concatenating the 1s and 0s is going to be tough b/c python will want to add the numbers (e.g., 1+1 = 2 vs 1+1 = 11). So, how are you going to handle this issue?
The conversion must be done in a function
No import statements allowed
main.py
Print the eight bit binary representation (00000000 - 11111111) of the number provided and converted. To do so, you will have to access the necessary functions in conversion.py and user_input.py
Note - the program is only allowed to access functions. No direct access to variables allowed.
No input or conversions allowed in main.py
Note - the binary print must only be the eight binary numbers. No commas, brackets etc. - ['1', '0', '0', ...] or [1,1,0,0,1..] are not allowed.
to make the function to get the inputted number I use
def number ():
num =int(input('Pick a number from 0 - 255'))
return num
number()
After that when I do not know how I would access it without importing it.
This is the code I'm using to convert
def conversion(num):
cnv_bin = ''
num = ''
while num // 2 > 0:
if num % 2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
num = num // 2
return cnv_bin
In the last file I tried
import conversion
import user_input
print(conversion.conversion(user_input.number()))
and that gave me this error
Traceback (most recent call last):
File "C:/Users/adkir/PycharmProjects/lab_23/main.py", line 4, in <module>
print(conversion.conversion(user_input.number()))
File "C:\Users\adkir\PycharmProjects\lab_23\conversion.py", line 5, in
conversion
while num // 2 > 0:
TypeError: unsupported operand type(s) for //: 'str' and 'int'
So basically im lost. Can anyone point me in the right direction so I can figure this out?
Your conversion function takes num as a parameter and yet it overwrites num's value by assigning an empty string to it.
Remove the line:
num = ''
and it should work.

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.

Adding numbers in a list gives TypeError: unsupported operand type(s) for +: 'int' and 'str'

I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:
Traceback (most recent call last):
File "Calculator.py", line 17, in <module>
addition = sum(inputs)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
My code is:
#declare variables
inputs = []
done = False
#while loop for inputting numbers
while done == False:
value = raw_input()
#escape loop if user enters done
if value == "Done":
print inputs
done = True
else:
inputs.append(value)
addition = sum(inputs)
print addition
raw_input returns strings, not numbers. sum operates only on numbers.
You can convert each item to an int as you add it to the list: inputs.append(int(value)). If you use float rather than int then non-integer numbers will work too. In either case, this will produce an error if the user enters something that is neither Done nor an integer. You can use try/except to deal with that, but that's probably out of the scope of this question.
When using raw_input() you're storing a string in value. Convert it to an int before appending it to your list, e.g.
inputs.append( int( value ) )

Categories

Resources