I';我正在努力处理一些if语句——Python 2.7.9(big noob)

I';我正在努力处理一些if语句——Python 2.7.9(big noob),python,if-statement,Python,If Statement,我想做一个游戏的一部分,你有一把只有一颗子弹的枪。但你有两次机会使用它。因此,如果你第一次使用它,你就不能第二次使用它,反之亦然 ammo_amount = 1 ammo = raw_input ("Shoot?") if ammo == 'y': print ("you shot") ammo_amount-1 else: print("You didn't shoot") ammo_2 = raw_input ("do you want to shoot aga

我想做一个游戏的一部分,你有一把只有一颗子弹的枪。但你有两次机会使用它。因此,如果你第一次使用它,你就不能第二次使用它,反之亦然

ammo_amount = 1

ammo = raw_input ("Shoot?")
if ammo == 'y':
    print ("you shot")
    ammo_amount-1

else:
    print("You didn't shoot")

ammo_2 = raw_input ("do you want to shoot again?")

if ammo_2 == 'y':
    if ammo_amount == '1':
        print ("you can shoot again")

    if ammo_amount == '0':
        print ("you can't shoot again")
if ammo_2 == 'n':
    print ("You didn't shoot") 

您正在将字符串与整数进行比较:

ammo_amount = 1

# ...

if ammo_amount == '1':

# 

if ammo_amount == '0':
这些测试永远不会为真,字符串永远不会等于整数,即使它们包含的字符在读取文本时可以解释为相同的数字;与另一个数字进行比较:

if ammo_amount == 1:

你也从未改变过弹药数量;以下表达式将生成一个新数字:

ammo_amount-1
但你忽略了那个新号码。将其存储回
ammo\u amount
变量:

ammo_amount = ammo_amount - 1

为了解释Martijn在回答中关于比较字符串和整数的内容

我们在计算中处理数据的方式因变量的类型而异。此类型确定可以和不能对变量执行的操作。通过调用
type()
函数,可以找到变量的类型:

type( 5 )     # <type 'int'>
type( '5' )   # <type 'str'>
type( 5.0 )   # <type 'float'>
num = 5
type( num )   # <type 'int'>
当您比较两个不兼容类型的对象时,解释器并不总是按照您的预期执行。考虑下面的代码:

num = 5
num == 5      # True
num == '5'    # False, comparing int to str
为什么第二个比较是错误的?翻译不知道我们想做什么。对字符串和整数执行比较的方式不会比较字符串的整数值,因为字符串可能包含非整数数据。据译员所知,我们可以尝试这样做:

num == 'clearly not a number'
正如Martijn所说,您的问题是您试图将一个整数(
弹药量
)与一个字符串(
'1'
'0'
)进行比较


希望这能进一步说明你的错误

所以不要用第一个?(我对python XP真的很陌生)@BhargavRao:两个不同但相关的问题。@MoJoe:我在哪里说这个?我给了你更好的选择;与实际数字相比。我很困惑,它基本上跳过了代码的第二部分…??@MoJoe:我给了你3行特定代码的替换代码。我不知道你为什么认为这会跳过代码的任何部分?小建议:如果你正在学习python,最好从官方开始。您可能最多需要5天来完成它,但它将真正帮助您了解导致此类错误的原因。祝你一切顺利。愿巨蟒之神与你同在。
num = 5
num == 5      # True
num == '5'    # False, comparing int to str
num == 'clearly not a number'