[英]Python: How to use type function in if statements?
I'm writing a program that loads a list of data from a file and I need the program to differentiate if the data in the line is either a string or an integer. 我正在编写一个从文件加载数据列表的程序,我需要该程序区分行中的数据是字符串还是整数。 However in the code I have done the program doesn't differentiate numbers from strings.
但是,在我完成的代码中,程序无法区分数字和字符串。
An example of the list of data I have: 我拥有的数据列表示例:
HAJOS
ALFRED
1896
1
My code: 我的代码:
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")
My problem is that when the program reads a line that has an integer, it doesn't determine correctly if the line contains an integer and from there run through the corresponding if statement. 我的问题是,当程序读取包含整数的行时,它无法正确确定该行是否包含整数,并从那里开始执行相应的if语句。 Currently my output looks like this.
目前,我的输出如下所示。
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
Data read from a file is always going to be a string. 从文件读取的数据将始终是字符串。 You'll need to try and convert those lines, not test their type:
您需要尝试转换这些行,而不是测试它们的类型:
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')
int()
will raise a ValueError
when alpha
cannot be interpreted as an integer number. 当
alpha
无法解释为整数时, int()
将引发ValueError
。 The exception, if raised, causes Python to jump to the except ValueError:
block instead of executing the rest of the try:
suite. 如果引发此异常,则会导致Python跳至
except ValueError:
块except ValueError:
块,而不是执行try:
套件的其余部分。
You can make a dict where the keys are "1","2" and "3"
to correspond to gold, silver, bronze and use dict.get. 您可以创建一个dict,其中键为
"1","2" and "3"
以对应于金,银,青铜,然后使用dict.get。
with open(infile) as f:
times = 1
medal_dict = {"1": 0, "2": 0, "3": 0}
while times <= 5:
alpha = f.readline().rstrip() #reads file line by line#
times += 1
if medal_dict.get(alpha) is not None:
medal_dict[alpha] += 1
else:
print("is a string")
print(medal_dict["1"], "Gold medals won")
print(medal_dict["2"], "Silver medals won")
print(medal_dict["3"], "Bronze medals won")
Which outputs: 哪个输出:
(1, 'Gold medals won')
(0, 'Silver medals won')
(0, 'Bronze medals won')
If you want to print when a medal is won through the loop: 如果要在循环中赢得奖牌时打印:
with open(infile) as f:
times = 1
medal_dict = {"1": [0,"gold"], "2": [0,"silver"], "3": [0,"bronze"]}
while times <= 5:
alpha = f.readline().rstrip() #reads file line by line#
print(alpha)
times += 1#
check = medal_dict.get(alpha)
if check is not None:
medal_dict[alpha][0] += 1
print("{} medal won".format(check[1]))
else:
print("is a string")
print(medal_dict["1"][0], "Gold medals won")
print(medal_dict["2"][0], "Silver medals won")
print(medal_dict["3"][0], "Bronze medals won")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.