Python 100 天 - 第 37 课 - 问题

问题描述 投票:0回答:2

几天前我开始在 Udemy 上参加 Angela Yu 博士的 Python 课程,我有一个关于她的“爱情计算器”代码的问题:

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")

combined_names = name1 + name2
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e

l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.count("e")
second_digit = l + o + v + e

score = int(str(first_digit) + str(second_digit))

print(score)

控制台打印出以下结果:

Welcome to the Love Calculator!
What is your name? 
True Love
What is their name? 
True Love
1010

我想知道为什么

print(score)
的结果是
1010
而不是
88
,因为每个单词只有4个字符。

非常感谢您的帮助:)

python
2个回答
3
投票

这是因为字母

e
对于每个“真爱”输入都会被计算两次,因为在真爱和爱情中都有一个
e

因此,不是每个字符都计数一次,而是其中 3 个字符计数一次,1 个字符计数两次,这为每个单词提供 5

count
。由于该短语被重复,因此每个单词变成 10
counts
,字符串“10”添加到“10”就是“1010”,将其转换为整数我们得到 1010

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")  # True Love
name2 = input("What is their name? \n") # True Love

combined_names = name1 + name2  # True LoveTrue Love
lower_names = combined_names.lower() #true lovetrue love
t = lower_names.count("t")  # 2
r = lower_names.count("r")  # 2
u = lower_names.count("u")  # 2
e = lower_names.count("e")  # 4
first_digit = t + r + u + e  # 10

l = lower_names.count("l")  # 2
o = lower_names.count("o")  # 2 
v = lower_names.count("v")  # 2
e = lower_names.count("e")  # 4
second_digit = l + o + v + e  # 10

score = int(str(first_digit) + str(second_digit)) # "10" + "10"

print(score)   # 1010

0
投票

我采用了您的代码并添加了一些附加的打印语句来说明为什么该值显示为“1010”。

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")

combined_names = name1 + name2

print("Combined Names:", combined_names)

lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e

print("First Digit:", first_digit)

l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.count("e")
second_digit = l + o + v + e

print("Second Digit:", second_digit)

score = int(str(first_digit) + str(second_digit))

print(score)

当我运行该程序并为两个名字输入“True Love”时,这就是终端上的结果输出。

@Una:~/Python_Programs/Love$ python3 Love.py 
Welcome to the Love Calculator!
What is your name? 
True Love
What is their name? 
True Love
Combined Names: True LoveTrue Love
First Digit: 10
Second Digit: 10
1010

首先,输入的名字被连接成一个字符串,“True LoveTrue Love”。 对该字符串进行采样,并为第一个数字和第二个数字构建计数。 对于第一个数字,在该连接字符串中找到两个“t”、两个“r”、两个“u”和四个“e”。 因此,第一个数字字段将包含值“10”(2 + 2 + 2 + 4)。 同样,对于第二位数字计算,在连接的字符串中找到两个“l”、两个“o”、两个“v”和四个“e”。 同样,这些计数的总和是“10”。 最后,将两个数字转换为字符串,然后连接起来。 这会产生字符串值“1010”。

因此,如果这个计算器程序应该得出不同的答案,您需要返回并重新评估您的代码。

© www.soinside.com 2019 - 2024. All rights reserved.