Python Code Questions

Asked 2 years ago, Updated 2 years ago, 84 views

6. Physical strength decreases due to damage input by text, save remaining physical strength

Text when outputting coding

Please let me know the appropriate code below!

7.When you run a program, read the file to start with your previously saved physical strength However, if the file does not exist, print "File not found." (Correction of previously written program) Related to what I asked earlier!

Please let me know the appropriate code below!

Loading saved files

My current physical strength is 120.

How much damage did you wear? : : 10

I have 110 left.

How much damage did you wear? : : 110

You have zero stamina left.

Question 6

f = open('score.txt', 'w')

hp = 280

while(1):

    print("Your current strength is %d."%hp)

    sub = input ("How many damage did you wear?")

    if(sub == "save"):

        print("Saved".")
        break

    else:
        hp -= int(sub)

f.write(hp)

f.close()

If you enter save, 120 points should be saved in the notepad, so which part should I modify?

Question 7

print ('Loading saved pie...')

f = open('score.txt', 'w+')

hp = 120
while(1):
    print("Your current strength is %d."%hp)
    sub = input ("How many damage did you wear?")

    if(hp == 'sub'):
        print("Physical strength left 0".")
        break

    else:
        hp -= int(sub)

f.write()
f.close()

How can I save 0 in my notepad when the sub value is 0?

f.Please tell me what value to write

coding python

2022-09-21 10:05

2 Answers

Check for file presence

https://docs.python.org/ko/3/library/os.path.html#os.path.exists

If you don't want to use a separate module, you can make an exception after opening it in a read format.

Exception handling

https://docs.python.org/ko/3/tutorial/errors.html

For the rest, I think we just need to adjust the location of the code you wrote.


2022-09-21 10:05

f = open('score.txt', 'w')
hp = 280
while 1:
    print("Your current strength is %d."%hp)
    sub = input ("How many damage did you wear?")
    if sub == "save":
        print("Saved".")
        break
    else:
        hp -= int(sub)
f.write('%s' % hp)
f.close()

is at the end of the six , f write ('% s' % hp) change with the rest of the hp is stored.
string million can be stored in files.

import os.path
path = 'score.txt'
if os.path.isfile(path):
    with open(path, 'r') as f:
        hp = int(f.read())
    print('Saved file read.')
else:
    print('File not found.')

Number 7 uses os.path.isfile to verify that the file exists in that location.
Returns True if any, or False if not.


2022-09-21 10:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.