在Python中,如何使这个变量赋值生效?

huangapple go评论70阅读模式
英文:

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

这段代码有两个问题。

  1. sex == m 比较的是变量 sex 和变量 m,但并没有定义 m。你需要将 sex 与字符串 'm' 进行比较。

  2. 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.

  1. sex == m is comparing sex, a variable to m, another variable that was not defined. you need to compare sex to 'm', a string.

  2. 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. ")

huangapple
  • 本文由 发表于 2023年6月5日 03:18:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定