Hướng dẫn calling a function with user input python - gọi một chức năng với đầu vào của người dùng python

Bạn có thể gọi các chức năng từ đầu vào của người dùng không? Một cái gì đó như thế này:

def testfunction(function):
    function()

a = raw_input("fill in function name: "
testfunction(a)

Vì vậy, nếu bạn điền vào một chức năng hiện có, nó sẽ thực hiện nó.

hỏi ngày 27 tháng 2 năm 2011 lúc 16:52Feb 27, 2011 at 16:52

Hướng dẫn calling a function with user input python - gọi một chức năng với đầu vào của người dùng python

Những gì bạn đang làm là xấu xấu: P Tuy nhiên, nó hoàn toàn có thể.

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
5 trả về một từ điển của tất cả các đối tượng hiện có sẵn và tên của chúng. Vì vậy, khi chúng tôi nói
a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
6, chúng tôi đang nói, "có bất kỳ đối tượng nào được gọi là". Nếu có, chúng tôi sẽ nhận được nó bằng cách thực hiện
a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
7 và sau đó kiểm tra xem đó là một chức năng sử dụng
a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
8. Nếu đó là
a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
9, thì chúng ta gọi hàm. Nếu không, chúng tôi chỉ cần in
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
0.

Đã trả lời ngày 27 tháng 2 năm 2011 lúc 16:59Feb 27, 2011 at 16:59

Ớt ớt xanhBlue Peppers

3.5882 Huy hiệu vàng21 Huy hiệu bạc23 Huy hiệu đồng2 gold badges21 silver badges23 bronze badges

Tôi có lẽ sẽ gói gọn loại hành vi này trong một lớp:

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()

Như những người khác đã nói, đây là một rủi ro bảo mật, nhưng bạn càng có nhiều quyền kiểm soát đối với đầu vào, thì càng ít rủi ro; Đặt nó vào một lớp bao gồm giúp kiểm tra đầu vào cẩn thận.

Đã trả lời ngày 27 tháng 2 năm 2011 lúc 17:01Feb 27, 2011 at 17:01

Hướng dẫn calling a function with user input python - gọi một chức năng với đầu vào của người dùng python

người gửisenderle

Phù vàng 141K35 Huy hiệu vàng207 Huy hiệu đồng35 gold badges207 silver badges231 bronze badges

2

Có bạn có thể, mặc dù đây nói chung là một ý tưởng tồi và rủi ro bảo mật lớn.

def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])

Đã trả lời ngày 27 tháng 2 năm 2011 lúc 16:57Feb 27, 2011 at 16:57

Chinmay Kanchichinmay KanchiChinmay Kanchi

60.6K22 Huy hiệu vàng86 Huy hiệu bạc113 Huy hiệu đồng22 gold badges86 silver badges113 bronze badges

Giới thiệu

Cách thức mà thông tin được lấy và xử lý là một trong những khía cạnh quan trọng nhất của ethos của bất kỳ ngôn ngữ lập trình nào, nhiều hơn đối với thông tin được cung cấp và lấy từ người dùng.

Python, trong khi tương đối chậm về vấn đề này khi so sánh với các ngôn ngữ lập trình khác như C hoặc Java, chứa các công cụ mạnh mẽ để thu thập, phân tích và xử lý dữ liệu thu được trực tiếp từ người dùng cuối.

Trong bài viết này, chúng tôi sẽ xem xét ngắn gọn về cách lấy thông tin từ người dùng thông qua chức năng

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 trong Python với sự trợ giúp của một số đoạn mã để làm ví dụ.

Đầu vào trong Python

Để nhận thông tin thông qua bàn phím, Python sử dụng chức năng

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1. Hàm này có một tham số tùy chọn, thường được gọi là dấu nhắc, là một chuỗi sẽ được in trên màn hình bất cứ khi nào hàm được gọi.

Lưu ý: Trước khi Python 3 giới thiệu chức năng

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1, cách đi khi đọc đầu vào của người dùng là hàm
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
4. Tuy nhiên, bạn luôn khuyên bạn nên sử dụng chức năng Python 3 và
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 của nó bất cứ khi nào bạn có thể! Trong Python 3, hàm
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
4 đã được không dùng nữa và thay thế bằng hàm
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 và được sử dụng để có được chuỗi của người dùng thông qua bàn phím. Và hàm
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 của Python 2 đã bị ngừng trong phiên bản 3. Để có được chức năng tương tự được cung cấp bởi hàm
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 của Python 2, câu lệnh
def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
0 phải được sử dụng trong Python 3.
Before Python 3 introduced the
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 function, the way to go when reading the user input was the
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
4 function. Still, it's always advised to use Python 3 and its
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 function whenever you can!
In Python 3, the
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
4 function has been deprecated and replaced by the
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 function and is used to obtain a user's string through the keyboard. And the
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 function of Python 2 is discontinued in version 3. To obtain the same functionality that was provided by Python 2's
class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 function, the statement
def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
0 must be used in Python 3.

Khi

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1Function được gọi, luồng chương trình dừng lại cho đến khi người dùng nhập vào đầu vào thông qua dòng lệnh. Để thực sự nhập dữ liệu, người dùng cần nhấn phím Enter sau khi nhập chuỗi của họ. Trong khi nhấn phím Enter thường chèn một ký tự mới (
def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
2), nhưng trong trường hợp này không có trong trường hợp này. Chuỗi đã nhập chỉ đơn giản sẽ được gửi đến ứng dụng.

Bây giờ chúng ta đã hiểu lý thuyết cơ bản đằng sau hàm

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1, chúng ta hãy xem cách nó thực sự hoạt động trong Python:

# Python 3

txt = input("Type something to test this out: ")

print(f"Is this what you just said? {txt}")

Chạy mã trước sẽ nhắc chúng tôi với "Nhập một cái gì đó để kiểm tra thông báo:" Tin nhắn. Sau khi chúng tôi gõ một cái gì đó, nó sẽ in ra những gì chúng tôi vừa gõ:

Type something to test this out: Let the Code be with you!

Is this what you just said? Let the Code be with you!

Chuỗi và đầu vào số

Theo mặc định, chức năng

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 sẽ chuyển đổi tất cả thông tin mà nó nhận được thành một chuỗi. Ví dụ trước chúng tôi cho thấy chứng minh hành vi này.

Mặt khác, các con số cần được xử lý rõ ràng như vậy vì chúng đến như các chuỗi ban đầu. Ví dụ sau đây cho thấy cách nhận thông tin loại số:

# An input is requested and stored in a variable
test_text = input ("Enter a number: ")

# Converts the string into an integer. If you need
# to convert the user input into the decimal format,
# the float() function is used instead of int()
test_number = int(test_text)

# Prints in the console the variable as requested
print ("The number you entered is: ", test_number)

Chạy mã trước sẽ cung cấp cho chúng tôi:

Enter a number: 13
The number you entered is: 13

Cách tiếp cận phổ biến hơn là thực hiện cả đầu vào đọc và chuyển đổi nó thành một số nguyên trong một dòng:

test_number = int(input("Enter a number: "))

Hãy nhớ rằng nếu người dùng không thực sự nhập một số nguyên thì mã này sẽ ném một ngoại lệ, ngay cả khi chuỗi đã nhập là số điểm nổi.

Cách xử lý các ngoại lệ khi đọc đầu vào

Có một số cách để đảm bảo rằng người dùng nhập thông tin hợp lệ. Một trong những cách là xử lý tất cả các lỗi có thể xảy ra trong khi người dùng nhập dữ liệu. Trong phần này, chúng tôi sẽ chứng minh một số phương thức xử lý lỗi tốt cho các lỗi có thể phát sinh khi đọc đầu vào.

Nhưng trước tiên, chúng ta hãy xem một ví dụ về một số mã không an toàn (có khả năng):

test2word = input("Tell me your age: ")
test2num = int(test2word)
print("Wow! Your age is ", test2num)

Sau khi chạy mã này, giả sử bạn nhập chuỗi "ba" thay vì số 3:

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
0

Ở đây, khi hàm

def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
5 được gọi với chuỗi "ba", ngoại lệ
def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
6 được ném và chương trình sẽ dừng và/hoặc sự cố.

Bây giờ chúng ta hãy xem cách chúng ta sẽ làm cho mã này an toàn hơn để xử lý đầu vào của người dùng:

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
1

Khối mã này sẽ đánh giá đầu vào mới. Nếu đầu vào là một số nguyên được biểu diễn dưới dạng chuỗi thì hàm

def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
5 sẽ chuyển đổi nó thành một số nguyên thích hợp. Nếu không, một ngoại lệ sẽ được nêu ra, nhưng thay vì làm hỏng ứng dụng, nó sẽ bị bắt và câu lệnh
def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
8 thứ hai được chạy. Dưới đây là một ví dụ về mã này đang chạy khi một ngoại lệ được nêu ra:

Kiểm tra hướng dẫn thực hành của chúng tôi, thực tế để học Git, với các thực hành tốt nhất, các tiêu chuẩn được công nghiệp chấp nhận và bao gồm bảng gian lận. Ngừng các lệnh git googling và thực sự tìm hiểu nó!

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
2

Và đây là cách xử lý các lỗi liên quan đến đầu vào trong Python.

Lưu ý: Bạn có thể kết hợp mã này với một cấu trúc khác, giống như một vòng lặp trong thời gian để đảm bảo rằng mã được chạy nhiều lần cho đến khi bạn nhận được đầu vào số nguyên hợp lệ mà chương trình của bạn yêu cầu. You can combine this code with another construct, like a while loop to ensure that the code is repeatedly run until you receive the valid integer input that your program requires.

Một ví dụ hoàn chỉnh

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
3

Đầu ra sẽ là:

a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
    locals()['a']()
else:
    print 'Function not found'
4

Sự kết luận

Trong bài viết này, chúng tôi đã thấy hàm Python

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()
1 tích hợp có thể được sử dụng để có được đầu vào của người dùng trong nhiều định dạng khác nhau. Chúng tôi cũng thấy cách chúng tôi có thể xử lý các ngoại lệ và lỗi có thể xảy ra trong khi có được đầu vào của người dùng.

Bạn có thể đặt đầu vào người dùng vào một chức năng python không?

Trong Python, sử dụng hàm input (), chúng tôi lấy đầu vào từ người dùng và sử dụng hàm in (), chúng tôi hiển thị đầu ra trên màn hình.Sử dụng hàm input (), người dùng có thể cung cấp bất kỳ thông tin nào cho ứng dụng trong định dạng chuỗi hoặc số.Using the input() function, we take input from a user, and using the print() function, we display output on the screen. Using the input() function, users can give any information to the application in the strings or numbers format.

Một chức năng có thể lấy đầu vào người dùng không?

Bạn có thể lấy đầu vào của người dùng với hàm input ().Điều này chờ đợi đầu vào bàn phím vô định.Nếu bạn thêm một tham số, nó sẽ in văn bản đó trước khi người dùng nhập.. This waits for keyboard input indefinetly. If you add a parameter, it will print that text before the user input.