import easygui as eg
import sys
version = 'Percentage Calculator'
Options = [ 'Percantage Increase', 'Percentage Decrease' ]
button = eg.buttonbox ('What would you like to calculate', title = version, choices = Options)
if button == Options [0]:
enter = eg.enterbox ('Please enter a number between 0 and 999.', title = version, strip=False)
if enter < '0' or enter > '999':
eg.msgbox ('please choose a number between 0 and 999.', title = version, ok_button='OK')
sys.exit()
enter2 = eg.enterbox ('please enter a number between 0 and 999, that is bigger than the first number.', title = version, strip=False)
if enter2 < '0' or enter2 > '999':
eg.msgbox ('please choose a number between 0 and 999.', title = version, ok_button='OK')
sys.exit()
elif enter2 < var enter:
eg.msgbox ('please choose a number bigger than the first number.', title = version, ok_button='OK')
sys.exit()
Subtract = enter2 - enter
print (Subtract)
这是我的代码...正如你所看到的,在底部附近,它表示'enter2 - enter'我希望这减去用户从第一个数字输入的第二个数字,但它只是说......
Traceback (most recent call last):
File "C:\Users\olitr_000\Desktop\PYTHON\Percentage Calculator\Percentage Calculator.py", line 22, in <module>
Subtract = enter2 - enter
TypeError: unsupported operand type(s) for -: 'str' and 'str'
我该怎么做才能说输入1等于55而输入2 = 198我怎么能得到它以便它确实198-55?
请帮忙,如果您需要更多信息,请通知我。
答案 0 :(得分:2)
你不能减去两个字符串,把第一个字符串转换成整数。
Subtract = int(enter2) - int(enter)
答案 1 :(得分:1)
你的问题是,通过使用eg.enterbox函数,用户输入的数字将被视为字符串。为了解决这个问题,我们将enterbox返回的'string'发送到int()函数。这会将数字字符串转换为可用于减去其他整数的实际整数。
例如
enter = "3"
enter = int(enter)
enter2 = "4" #This is an example of what the variable looks like coming from the enterbox
enter2 = int(enter2) #enter2 now looks like 4 instead of "4"
output = enter2 - enter #this will return 1 to the variable output
希望这会有所帮助;)
哦,你不需要这一行中的引号:
if enter < '0' or enter > '999':
正如你所说'0'是一个字符串,不应被视为数字;)
答案 2 :(得分:0)
这会对你有帮助。
import easygui as eg
import sys
version = 'Percentage Calculator'
Options = [ 'Percantage Increase', 'Percentage Decrease' ]
button = eg.buttonbox ('What would you like to calculate', title = version, choices = Options)
if button == Options [0]:
enter = eg.enterbox ('Please enter a number between 0 and 999.', title = version, strip=False)
if enter < '0' or enter > '999':
eg.msgbox ('please choose a number between 0 and 999.', title = version, ok_button='OK')
sys.exit()
enter2 = eg.enterbox ('please enter a number between 0 and 999, that is bigger than the first number.', title = version, strip=False)
if enter2 < '0' or enter2 > '999':
eg.msgbox ('please choose a number between 0 and 999.', title = version, ok_button='OK')
sys.exit()
elif enter2 < var enter:
eg.msgbox ('please choose a number bigger than the first number.', title = version, ok_button='OK')
sys.exit()
Subtract = int(enter2) - int(enter)
print (Subtract)
答案 3 :(得分:0)
我认为你在这里遇到的问题只是parsing
,因为我们知道Python不接受键盘中的string
值,因为代码中没有变量类型定义,即为什么我们总是需要将输入转换或解析为适当的类型。
>>> a = "3.14"
>>> float(a)
3.14
>>> int(float(a))
3