编24点程序时遇到的问题
大佬好呀,Python小白又来求助啦!
这次的问题是在编24点时遇到的一个问题:如何将用户输入的数字运算出结果?
源代码:
import random
shuzi_str_one=str(random.randint(1,10))
shuzi_str_two=str(random.randint(1,10))
shuzi_str_three=str(random.randint(1,10))
shuzi_str_four=str(random.randint(1,10))
def twntyfour():
shuzi_str=shuzi_str_one+’ ‘+shuzi_str_two+’ ‘+shuzi_str_three+’ ‘+shuzi_str_four
global shuzi_str
tuntyfour()
print(‘24点游戏,用随机的四个数字算出24!如果发现无解,可回答“无解”。(一个一个回答,如:输入一,计算机回答收到,输入×,计算机回答收到,再输入一,计算机回答1×1=2)’)
print(‘数字是%s.’%(shuzi_str))
shuzi=int(input(‘请输入数字:’))
print(‘收到%d’%(shuzi))
fuhao=input(‘请输入运算符号:’)
print(‘收到%s’%(fuhao))
编到这里我就发现,变量shuzi和fuhao无法加起来,成为完整的算式并得出结果。并且,试运行时发现程序报错:
runfile(’/home/jiangyizheng/桌面/程序/24点.py’, wdir=’/home/jiangyizheng/桌面/程序’)
Traceback (most recent call last):
File “/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py”, line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File “”, line 1, in
runfile(’/home/jiangyizheng/桌面/程序/24点.py’, wdir=’/home/jiangyizheng/桌面/程序’)
File “/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py”, line 827, in runfile
execfile(filename, namespace)
File “/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py”, line 110, in execfile
exec(compile(f.read(), filename, ‘exec’), namespace)
File “/home/jiangyizheng/桌面/程序/24点.py”, line 8
global shuzi_str
^
SyntaxError: name ‘shuzi_str’ is assigned to before global declaration
求大佬帮助!