Nhờ giải thích về code python

Mình lần đầu học code và đang xem video trên chanel Dạy nhau học đến đoạn này mình có code theo và thấy phần biến khai báo dưới cùng lại đổi màu thành màu xanh và chương trình không chạy được hình như python hiểu nó thành một hàm gì đó không biết mình sai ở đâu mong mọi người chỉ giúp. Cảm ơn mọi người!

Bạn chạy file này như thế nào?

P/s: Post code và bỏ trong dấu ``` để format code

code

2 Likes
# this one is like your scripts with argv
def print_two(*args):
	arg1, arg2 = args
	print "arg1: %r, arg2: %r" % (arg1, arg2)

# ok,that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
	print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just take one argument
def print_one(arg1):
	print "arg1: %r" % arg1

# this one takes no arguments
def print_none():
	print "I got nothin'."


print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()

Mình không hiểu sao lúc trưa mình chạy không được nhưng giờ lại chạy được mà trong khi mình không sửa 1 chút code nào. Lúc lỗi nó báo dòng 18 not defined

Chạy được la tốt rồi, mình đọc qua cũng không thấy lỗi. Có thể là các lỗi bên ngoài như không lưu đủ file trước khi chạy chẩng hạn. Nếu không gặp lỗi này lại thì bạn cho qua mình nghĩ cũng không sao.

2 Likes

Lỗi của mình đây bác
PS C:\Users\Admin\workspace\NewFolder\ex20> python.exe ex20.py test.txt
First let’s print the whole file:

This is line 1
This is line 2
This is line 3
Now let’s rewind, kind of like a tape.
Let’s print three line:
Traceback (most recent call last):
File “ex20.py”, line 27, in
print_a_line(current_line, current_file)
File “ex20.py”, line 12, in print_a_line
print line_count, f.readline()
NameError: global name ‘line_count’ is not defined

Code của mình đây

from sys import argv

script, input_file = argv

def print_all(f):
	print f.read()

def rewind(f):
	f.seek(0)

def print_a_line(lie_count, f):
	print line_count, f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three line:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

:smile: Xem kỹ lại 2 dòng trên.

1 Like

:sweat_smile: Trời Sao mù thế không biết?? Tại mấy code gần đây cứ gặp cái vđề kia nên không để ý. Cảm ơn bác em sẽ rút kinh nghiệm

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?