我正在努力处理一些 if 语句 - Python 2.7.9(大菜鸟)

I'm struggling with some if statements - Python 2.7.9 (big noob)

我想制作一个游戏的一部分,其中你有一把只有一颗子弹的枪。但是你有两次机会使用它。所以如果你第一次使用它,你不能第二次使用它,反之亦然。

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:

if ammo_amount == 0:

你也从未改变过ammo_amount;以下表达式产生一个新数字:

ammo_amount-1

但是您忽略了那个新号码。将其存储回 ammo_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'>

看看 5'5'5.0 有何不同的类型?我们可以用这些不同的文字做不同的事情。比如我们可以获取到'5'的长度,因为它是一个字符串,是一个序列,但是我们获取不到5的长度。

len( '5' )    # 1
len( 5 )      # TypeError: object of type 'int' has no len()

当您比较两个类型不兼容的对象时,解释器不会总是按照您的期望进行操作。考虑以下代码:

num = 5
num == 5      # True
num == '5'    # False, comparing int to str

为什么第二次比较是假的?那么口译员不知道我们想做什么。 == 对字符串和整数进行比较的方式不会比较字符串的整数值,因为字符串可能包含非整数数据。据解释器所知,我们可能会尝试做这样的事情:

num == 'clearly not a number'

正如 Martijn 所说,您的问题是您正在尝试将整数 (ammo_amount) 与字符串 ('1''0') 进行比较。

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