Python:如何在 if 语句中使用类型函数?

标签 python if-statement types

我正在编写一个从文件加载数据列表的程序,我需要该程序区分行中的数据是字符串还是整数。但是,在我完成的代码中,程序无法区分数字和字符串。

我拥有的数据列表的示例:

HAJOS
ALFRED
1896
1

我的代码:

def medalsYear():
  times = 1
  totalGold = 0
  totalSilver = 0
  totalBronze = 0
  while times <= 5:
    alpha = fob.readline() #reads file line by line#
    print(alpha)
    times = times + 1
    if type(alpha) == int:
        if alpha == 1:
            totalGold = totalGold + 1
            print("gold medal won")
        elif alpha == 2:
            totalSilver = totalSilver + 1
            print("silver medal won")
        elif alpha == 3:
            totalBronze = totalBronze + 1
            print("bronze medal won")
        else:
            pass
    else:
        print('is a string')
  print(totalGold, "Gold medals won")
  print(totalSilver, "Silver medals won")
  print(totalBronze, "Bronze medals won")

我的问题是,当程序读取包含整数的行时,它无法正确确定该行是否包含整数,并从那里运行相应的 if 语句。目前我的输出如下所示。

HAJOS
is a string
ALFRED
is a string
1896
is a string
1
is a string

is a string
0 Gold medals won
0 Silver medals won
0 Bronze medals won
done

最佳答案

从文件中读取的数据总是是一个字符串。您需要尝试转换这些行,而不是测试它们的类型:

try:
    alpha = int(alpha)
    if alpha == 1:
        totalGold = totalGold + 1
        print("gold medal won")
    elif alpha == 2:
        totalSilver = totalSilver + 1
        print("silver medal won")
    elif alpha == 3:
        totalBronze = totalBronze + 1
        print("bronze medal won")
except ValueError:
    print('is a string')
alpha 无法解释为整数时,

int() 将引发 ValueError。如果引发异常,则会导致 Python 跳转到 except ValueError: block ,而不是执行 try: 套件的其余部分。

关于Python:如何在 if 语句中使用类型函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25940695/

相关文章:

Javascript if this OR this statement - 忽略第二个条件

Python:venn3_circles:如何获取 Venn 3 圆图中的交点值

python - 在 python 中是否有等效于 emacs 的 rx 宏?

python - 在 Python Pandas DataFrame 中删除重复项而不删除重复项

C++ 为输入类型选择模板输出类型

java - 为什么我无法访问泛型类型类元素?

types - 为什么在有区别的联合中使用选项类型是错误的?

python - 值错误 : No module named 'notmigrations' during unit tests

python - 嵌套 if ... else(Python 练习)

php - 检查sql数据库中是否存在email,然后输出(关于running if inside if)