- Joined
- Dec 10, 2018
- Posts
- 86
- Reaction
- 33
- Points
- 103
Gandang araw sainyo. Dahil tinamas ako pumasok, at wala akong ginagawa, continue nalang natin yung tutorial natin.
Kung nabasa nyo yung [0] at [1], madadalian nalang kayo dito.
So reading and writing a file. Hindi sya mahirap. May mga bagay lang na kelangan tandaan.
'a' = append
'r' = read
'w' = write
Para maopen ang file natin. For example, file.txt, Gagamitan natin sya ng open func.
open(file_as_string, method)
code:
Define mo sya as variable para kontrolado mo ang input and output nito.
f = open('file.txt')
Walang method since open lang natin sya. Ang default na opening method ay readonly.
Example, mag write tayo ng data na string kay file.txt.
Andali lang diba? Write sya. Hindi sya append so automatic overwritten yung file mo if existing. Ngayon, ituloy natin yung laro. Mag sesave sya dapat ng scores sa scores.txt
Mag sesave sya ng scores sa scores.txt same directory ng script nyo.
Next topic: reading a line out of text file
Kung nabasa nyo yung [0] at [1], madadalian nalang kayo dito.
So reading and writing a file. Hindi sya mahirap. May mga bagay lang na kelangan tandaan.
'a' = append
'r' = read
'w' = write
Para maopen ang file natin. For example, file.txt, Gagamitan natin sya ng open func.
open(file_as_string, method)
code:
Code:
file = 'file.txt'
open(file, 'a')
#'a' is method as string.
Or
open('file.txt', 'a')
f = open('file.txt')
Walang method since open lang natin sya. Ang default na opening method ay readonly.
Example, mag write tayo ng data na string kay file.txt.
Code:
p1 = 'Hello'
p2 = ' World'
data = pi + p2
#para masanay kayo sa defining ng vars.
f = open('file.txt', 'w')
f.write(data)
output: Hello World
Code:
import random
#import natin yung module na random for access ng random functions
import time
#for time modules.
rand_this = [1, 2, 3, 4, 5, 6]
#integers in a list
t = input('Number of tries: ')
#number of trials based on uset input.
counter = 0
score_file = 'scores.txt'
score = 0
while counter != int(t):
#!= is not equal which is true/false based on user input.
guess = input('Guess a number from 1-6 \n')
#tatanungin kung anong hula mo.
#ang \n ay new line
result = random.choice(rand_this)
#pipili ang script ng choice dun sa list natin sa taas. RANDOMLY
if int(guess) == result:
print('You win!', guess, 'is', result)
score += 1
else:
print('Sorry.', guess, 'is not', result)
counter += 1
#instead of counter = counter + 1
#if and else statement. Yung nasa baba ay ang conclusions ang 'if' ay condition. Uri sya ng function.
#ang int() naman ay conversation from string. To integer.
#ang nasalabas ng while ay mag eexecute lamang kapag tapos na ang loop or false na.
f = open(score_file, 'a') #naka append
f.write('You won ' + str(score) + ' time/s out of ' + str(counter) + '.\n')
f.close()
print('Thankyou for playing.')
time.sleep(5)
#sleep for 5seconds.
Next topic: reading a line out of text file