简体   繁体   中英

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

# 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

If you just write variable_name + value, the variable itself does not change.

To assign a value to a variable you need to use the = operator. In your case, you must do hours = hours + 12 . You can also use the += operator for the same result, in that case it would be hours += 12 .

The same is true for the line just above, where you have hours * 1 . That is not actually doing anything. You should have done hours = hours * 1 or hours *= 1 .

Both if statements will be as following,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM