CloudFace - 1 year ago 89
Python Question

# Python user-input

I'm trying to come up with a simple calculator that takes a user's input and does a calculation but it keeps throwing out errors.

``````raw = input("Raw Formatting:")
disk = input("On-disk formatting:")
slack = input("Slack space:")
quest = input("Select protection; 1=FTT, 2=EC-1, 3=EC-2:")

if quest == 1:
answer = raw * (1-disk) * (1-slack) * 0.5
elif quest == 2:
answer = raw * (1-disk) * (1-slack) * 0.75
elif quest == 3:
answer = raw * (1-disk) * (1-slack) * 0.67
else:
print ("You didn't provide a valid protection level")
``````

Output:

``````Raw Formatting:24
On-disk formatting:0.1
Slack space:0.3
Select protection; 1=FTT, 2=EC-1, 3=EC-2:1
Traceback (most recent call last):
File "C:\Users\Ed\Desktop\hello.py", line 7, in <module>
answer = raw * (1-disk) * (1-slack) * 0.5
TypeError: unsupported operand type(s) for -: 'int' and 'str'
``````

Any help would be appreciated.

Thanks

You are taking an input, which is a string, no matter what is entered as input, then you are trying to perform a math operation with a string and an integer.

you need to convert your strings to ints or call them as ints when you are performing your math functions.

example one:

``````raw = input("Raw Formatting:")
disk = input("On-disk formatting:")
slack = input("Slack space:")
quest = input("Select protection; 1=FTT, 2=EC-1, 3=EC-2:")
raw = float(raw)
disk = float(disk)
slack = float(slack)
quest= float(quest)
if quest == 1:
answer = raw * (1-disk) * (1-slack) * 0.5
elif quest == 2:
answer = raw * (1-disk) * (1-slack) * 0.75
elif quest == 3:
answer = raw * (1-disk) * (1-slack) * 0.67
else:
print ("You didn't provide a valid protection level")
``````

Example 2

``````raw = input("Raw Formatting:")
disk = input("On-disk formatting:")
slack = input("Slack space:")
quest = input("Select protection; 1=FTT, 2=EC-1, 3=EC-2:")

if quest == '1':
answer = float(raw) * (1-float(disk)) * (1-float(slack)) * 0.5
elif quest == '2':
answer = float(raw) * (1-float(disk)) * (1-float(slack)) * 0.75
elif quest == '3':
answer = float(raw) * (1-float(disk)) * (1-float(slack)) * 0.67
else:
print ("You didn't provide a valid protection level")
``````

You will also need to check to make sure that what you are getting back will evaluate to integer, less you want more errors.. first thing you should do is strip spaces from you input

``````x = input('type a number: ').strip(' ')
``````

then you should ensure that your input(string values) are numbers.

``````if not x.isdigit():
print("you didn't enter a number")
``````

Alternatively, there are more pythonic ways to perform the answer I have given, but I think the answer is appropriate for you currently you should be able to work with that.. read the docs https://docs.python.org/3/library/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download