[英]How can i save a new result from a variable using Python?
it's my first post here.这是我在这里的第一篇文章。 I'm new to programming and started recently using the Python language to learn programming logic and algorithms.
我是编程新手,最近开始使用 Python 语言来学习编程逻辑和算法。 I have a problem that I am unable to solve in an basic exercise.
我有一个在基本练习中无法解决的问题。 How can I save a new variable's value?
如何保存新变量的值? My problem is after the IF, because he is miscalculating the time in PM
我的问题是在 IF 之后,因为他在 PM 中计算错误时间
# Exercise 3.9 - Calculating seconds in the current month
day = int(input("Type the current day: "))
hours = int(input("Type the current hour (in 12-hour format): "))
am_pm = str(input("It's AM or PM?: "))
if (am_pm) == "PM":
hours += 12
if (am_pm) == "AM":
hours *= 1
minutes = int(input("Type the current minute: "))
seconds = int(input("Type the current second: "))
conversion_day = (day-1) * 86400
conversion_hours = hours * 3600
conversion_minutes = minutes * 60
conversion_seconds = seconds * 1
total = conversion_day+conversion_hours+conversion_minutes+conversion_seconds
print(f"The conversion of {day} days, {hours} hours, {minutes} minutes and {seconds} seconds resulted in {total} seconds this month! ")
You do it by assignment, that is hours = hours + 12 or hours += 12您通过分配来完成,即小时 = 小时 + 12 或小时 += 12
If you just write variable_name + value, the variable itself does not change.如果只写variable_name + value,变量本身不会改变。
To assign a value to a variable you need to use the =
operator.要将值分配给变量,您需要使用
=
运算符。 In your case, you must do hours = hours + 12
.在您的情况下,您必须执行
hours = hours + 12
。 You can also use the +=
operator for the same result, in that case it would be hours += 12
.您还可以使用
+=
运算符来获得相同的结果,在这种情况下,它将是hours += 12
。
The same is true for the line just above, where you have hours * 1
.上面的行也是如此,您有
hours * 1
。 That is not actually doing anything.那实际上并没有做任何事情。 You should have done
hours = hours * 1
or hours *= 1
.您应该已经完成
hours = hours * 1
或hours *= 1
。
Both if statements will be as following,两个 if 语句将如下所示,
if (am_pm) == "AM":
hours *= 1
if (am_pm) == "PM":
hours += 12
or you can also write them as,或者你也可以把它们写成,
if (am_pm) == "AM":
hours *= 1
else:
hours += 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.