我已经开发了一段代码用于学校,我已经到最后一个问题,为了完成游戏,我需要打印出结果总和的最终值,我正在问题包括用户输入的变量名,这里是代码;
import random
print('Welcome to the game')
char1=input('What is the fist characters name: ')
char2=input('What is the second characters name: ')
char1st=int(input('What is the strength of '+char1))
char1sk=int(input('What is the skill of '+char1))
char2st=int(input('What is the strength of '+char2))
char2sk=int(input('What is the skill of '+char2))
strmod = abs (char2st - char1st) // 5
sklmod = abs (char2sk - char1sk) //5
char1rl=random.randint(1,6)
char2rl=random.randint(1,6)
if char1rl>char2rl:
char1nst=(char1st+strmod)
char1nsk=(char1sk+sklmod)
char2nsk=(char2sk-sklmod)
char2nst=(char2st-strmod)
elif char2rl>char1rl:
char2nst=(char2st+strmod)
char2nsk=(char2sk+sklmod)
char1nsk=(char1sk-sklmod)
char1nst=(char1st-strmod)
else:
print('both rolls where the same, no damage was given or taken')
if char1nst <= 0:
print(str(+char1+' has died'))
elif char2nst <=0:
print(str(+char2+' has died'))
else:
print(+char1( ' now has a strength value of '+char1nst' and a skill value of '+char1nsk'.'))
print(+char2( ' now has a strenght value of '+char2nst' and a skill value of '+char2nsk'.'))
我在最后写了这个位,希望它会打印结束值但是我得到语法错误?!并且不知道为什么会这样。有人可以帮我编辑最后四行,以便以下列格式打印:
鲍勃现在的力量值为4,技能值为7
我之前使用过我的方法,但这次没有工作,所以如果有人能指出我哪里出错了,怎么修改这个问题就好了!!!!
答案 0 :(得分:2)
您正在尝试使用+
运算符而无需添加任何内容:
print(str(+char2+' has died'))
您不需要str
或+
运算符,只需对print()
函数使用多个参数:
if char1nst <= 0:
print(char1, 'has died'))
elif char2nst <=0:
print(char2, 'has died'))
else:
print(char1, 'now has a strength value of', char1nst, 'and a skill value of', str(char1nsk) + '.'))
print(char2, 'now has a strength value of', char2nst, 'and a skill value of', str(char2nsk) + '.'))
仅在最后两行中,我使用str()
和+
来避免值与.
句号之间的空格。
相反,您可以使用str.format()
method的字符串格式为最后两行提供更易读的字符串格式选项:
template = '{} now has a strength value of {} and a skill value of {}.'
print(template.format(char1, char1nst, char1nsk))
print(template.format(char2, char2nst, char2nsk))
因为两行的文本相同,所以可以在这里重复使用模板字符串。
答案 1 :(得分:2)
您在不需要它们的地方有连接操作符(+
)(在print()
的开头,并且您不需要在需要它们的地方使用它们它们(在of '+char1nsk'.'
中的变量之后)。这导致了语法错误。
您可能会考虑使用string formatting而不是字符串连接:
print "%s now has a strength value of %d and a skill value of %d" % (char1, char1nst, char1nsk)
答案 2 :(得分:0)
尝试删除print语句开头的+。将其更改为:
print char1 +' has died'
print char2 +' has died'
答案 3 :(得分:0)
否则: print(char1 +'现在的强度值为'+ char1nst +',技能值为'+ char1nsk +'。') print(char2 +'现在的实力值为'+ char2nst +',技能值为'+ char2nsk +'。')
答案 4 :(得分:0)
好了,因为你使用python3为什么不使用.format? 将{}插入到您想要一个值的字符串中,然后使用您想要的值以正确的顺序调用该字符串上的format()方法。
else:
temp = "{} now has a strength value of {} and a skill value of {}."
print(temp.format(char1, char1nst, char1nsk))
print(temp.format(char2, char2nst, char2nsk))
如果你问我,那就是最干净的解决方案。