英文:
In Python, how do I get this variable assignment to work?
问题
这部分代码有效直到第7行
sex = input("你是男性(m)还是女性(f)?")
me = 75 * 52
fe = 80 * 52
ca = input("你当前年龄是多少岁?") * 52
print(sex) # 这里返回了第一行的输入。
if sex == 'm':
print(f"你大约还有{me - ca}周可活。")
else:
print(f"你大约还有{fe - ca}周可活。")
该变量被赋予了一个字符串,但在 if 语句中它不起作用作为布尔值。
英文:
# This works until line 7
sex = input("Are you male(m) or female(f)? ")
me = 75 * 52
fe = 80 * 52
ca = input("What is your current age in years? ") * 52
print(sex) # This is returning the input from the first line.
if sex == m:
print(f"You have approximately {me - ca} weeks to live. ")
else:
print(f"You have approximately {fe - ca} weeks to live. ")
The variable is assigned a string, but it's not working as a Boolean in the if statement.
答案1
得分: 0
这段代码有两个问题。
-
sex == m
比较的是变量sex
和变量m
,但并没有定义m
。你需要将sex
与字符串'm'
进行比较。 -
input()
返回一个字符串。在将其乘以 52 之前,你需要将这个字符串转换为整数。
以下是 OP 代码的正确版本:
sex = input("Are you male(m) or female(f)? ")
me = 75 * 52
fe = 80 * 52
ca = int(input("What is your current age in years? ")) * 52
print(sex) # 这会返回第一行输入的内容。
if sex == 'm':
print(f"You have approximately {me - ca} weeks to live. ")
else:
print(f"You have approximately {fe - ca} weeks to live. ")
英文:
There are two problems with this code.
-
sex == m
is comparingsex
, a variable tom
, another variable that was not defined. you need to comparesex
to'm'
, a string. -
input()
returns a string. you need to convert that string into an integer before multiplying by 52
Here is a correct version for OP's code:
sex = input("Are you male(m) or female(f)? ")
me = 75 * 52
fe = 80 * 52
ca = int(input("What is your current age in years? ")) * 52
print(sex) # this is returning the input from the first line.
if sex == 'm':
print(f"You have approximately {me - ca} weeks to live. ")
else:
print(f"You have approximately {fe - ca} weeks to live. ")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论