Hướng dẫn restrict input python - hạn chế python đầu vào

10

Nội dung chính

  • Làm thế nào để bạn giới hạn đầu vào cho các số nguyên trong Python?
  • Làm thế nào để bạn hạn chế giá trị đầu vào trong Python?
  • Làm thế nào để bạn chỉ cho phép một số đầu vào nhất định trong Python?
  • Làm thế nào để bạn kiểm soát đầu vào trong Python?

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.Learn more.
Learn more.

Tôi đang cố gắng thực hiện một cuộc khảo sát trắc nghiệm cho phép người dùng chọn từ Tùy chọn 1-X. Làm thế nào tôi có thể làm cho nó để nếu người dùng nhập bất kỳ ký tự nào ngoài các số, hãy trả lại một cái gì đó như "đó là một câu trả lời không hợp lệ"

def Survey():
    print('1) Blue')
    print('2) Red')
    print('3) Yellow')
    question = int(input('Out of these options\(1,2,3), which is your favourite?'))
    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

Gino Mempin

21.2K25 Huy hiệu vàng87 Huy hiệu bạc115 Huy hiệu đồng25 gold badges87 silver badges115 bronze badges25 gold badges87 silver badges115 bronze badges

Hỏi ngày 27 tháng 4 năm 2014 lúc 16:43Apr 27, 2014 at 16:43Apr 27, 2014 at 16:43

1

Mã của bạn sẽ trở thành:

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

Cách thức hoạt động này là nó tạo ra một vòng lặp sẽ lặp lại vô hạn cho đến khi chỉ có số được đưa vào. Vì vậy, tôi nói rằng tôi đặt '1', nó sẽ phá vỡ vòng lặp. Nhưng nếu tôi đặt 'Fooey!' Lỗi đã được nêu ra bị bắt bởi tuyên bố

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
4 và nó lặp lại vì nó chưa bị phá vỡ.

Đã trả lời ngày 27 tháng 4 năm 2014 lúc 16:54Apr 27, 2014 at 16:54Apr 27, 2014 at 16:54

HarrycburnharrycburnHarryCBurnHarryCBurn

7451 Huy hiệu vàng7 Huy hiệu bạc17 Huy hiệu đồng1 gold badge7 silver badges17 bronze badges1 gold badge7 silver badges17 bronze badges

0

Cách tốt nhất sẽ là sử dụng hàm trợ giúp có thể chấp nhận một loại biến cùng với thông báo để thực hiện đầu vào.

def _input(message, input_type=str):
    while True:
      try:
        return input_type (input(message))
    except:pass

if __name__ == '__main__':
    _input("Only accepting integer : ", int)
    _input("Only accepting float : ", float)
    _input("Accepting anything as string : ")

Vì vậy, khi bạn muốn một số nguyên, bạn có thể vượt qua nó mà tôi chỉ muốn số nguyên, chỉ trong trường hợp bạn có thể chấp nhận số nổi, bạn vượt qua phao làm tham số. Nó sẽ làm cho mã của bạn thực sự mỏng vì vậy nếu bạn phải nhập 10 lần, bạn không muốn viết thử Catch Blocks mười lần.

Đã trả lời ngày 26 tháng 9 năm 2019 lúc 7:49Sep 26, 2019 at 7:49Sep 26, 2019 at 7:49

Ahsan Royahsan RoyAhsan RoyAhsan Roy

6305 Huy hiệu bạc13 Huy hiệu Đồng5 silver badges13 bronze badges5 silver badges13 bronze badges

1

def func():
    choice = "Wrong"
    
    while choice.isdigit()==False :
        choice = input("Enter a number: ")
        
        if choice.isdigit()==False:
            print("Wrongly entered: ")
        else:
            return int(choice)

OCRDU

2.0966 Huy hiệu vàng13 Huy hiệu bạc21 Huy hiệu đồng6 gold badges13 silver badges21 bronze badges6 gold badges13 silver badges21 bronze badges

Đã trả lời ngày 2 tháng 1 năm 2021 lúc 12:15Jan 2, 2021 at 12:15Jan 2, 2021 at 12:15

VarunvarunVarunVarun

Phù hiệu đồng 4144 bronze badges4 bronze badges

Một giải pháp trong số những người khác: Sử dụng hàm

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
0 hoặc hàm
def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
1 để kiểm tra xem bạn có ̀ ________ 12 hoặc
def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
3 hoặc một số loại khác
>>> type(1)


>>> type(1.5)


>>> isinstance(1.5, int)
False

>>> isinstance(1.5, (int, float))
True   

Đã trả lời ngày 27 tháng 4 năm 2014 lúc 16:50Apr 27, 2014 at 16:50Apr 27, 2014 at 16:50

CyrillecyrilleCyrilleCyrille

13.4K2 Huy hiệu vàng18 Huy hiệu bạc38 Huy hiệu đồng2 gold badges18 silver badges38 bronze badges2 gold badges18 silver badges38 bronze badges

2

Tôi sẽ bắt đầu tiên là ngoại lệ

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
4 (không phải số nguyên) và kiểm tra xem câu trả lời có được chấp nhận không (trong vòng 1, 2, 3) hoặc tăng ngoại lệ
def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
4 khác
def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
0

Lipis

21K19 Huy hiệu vàng93 Huy hiệu bạc118 Huy hiệu đồng19 gold badges93 silver badges118 bronze badges19 gold badges93 silver badges118 bronze badges

Đã trả lời ngày 27 tháng 4 năm 2014 lúc 17:31Apr 27, 2014 at 17:31Apr 27, 2014 at 17:31

Georsfegeorstefgeorstefgeorstef

1.3683 huy hiệu vàng12 Huy hiệu bạc18 Huy hiệu đồng3 gold badges12 silver badges18 bronze badges3 gold badges12 silver badges18 bronze badges

1

Tôi đã thực hiện một mô -đun cho các trường hợp như thế này được gọi là hạn chế_input kiểm tra đầu vào trong thời gian thực. Ở đây, vì bạn chỉ cần đầu vào từ 1-3, điều này sẽ làm

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
1

Nó sử dụng msvcrt.getch/termios để nhận đầu vào không chặn, do đó, nó kiểm tra nó trong thời gian thực và chỉ cho phép các ký tự được chỉ định. Lưu ý: Điều này sẽ không hoạt động trong Idles như Spyder, Jupyter, v.v. Note: This will not work in IDLEs like Spyder, Jupyter etc.
Note: This will not work in IDLEs like Spyder, Jupyter etc.

Đã trả lời ngày 2 tháng 2 năm 2021 lúc 12:13Feb 2, 2021 at 12:13Feb 2, 2021 at 12:13

FgoofgooFGooFGoo

812 Huy hiệu bạc3 Huy hiệu đồng2 silver badges3 bronze badges2 silver badges3 bronze badges

0

Bạn có thể sử dụng một mô -đun có tên PyInputPlus.

Installation:

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')
2

Bạn có thể sử dụng cái này như

def Survey():
    print('1) Blue')
    print('2) Red')
    print('3) Yellow')
    question = int(input('Out of these options\(1,2,3), which is your favourite?'))
    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

mkrieger1

15.9k4 Huy hiệu vàng47 Huy hiệu bạc57 Huy hiệu Đồng4 gold badges47 silver badges57 bronze badges4 gold badges47 silver badges57 bronze badges

Đã trả lời ngày 12 tháng 2 năm 2021 lúc 6:47Feb 12, 2021 at 6:47Feb 12, 2021 at 6:47

Làm thế nào để bạn giới hạn đầu vào cho các số nguyên trong Python?

Cách tốt nhất sẽ là sử dụng hàm trợ giúp có thể chấp nhận một loại biến cùng với thông báo để thực hiện đầu vào. Vì vậy, khi bạn muốn một số nguyên, bạn có thể vượt qua nó mà tôi chỉ muốn số nguyên, chỉ trong trường hợp bạn có thể chấp nhận số nổi, bạn vượt qua phao làm tham số.use a helper function which can accept a variable type along with the message to take input. So when you want an integer , you can pass it that i only want integer, just in case you can accept floating number you pass the float as a parameter.use a helper function which can accept a variable type along with the message to take input. So when you want an integer , you can pass it that i only want integer, just in case you can accept floating number you pass the float as a parameter.

Làm thế nào để bạn hạn chế giá trị đầu vào trong Python?

Để giới hạn đầu vào của người dùng vào một phạm vi: Sử dụng vòng lặp trong thời gian để lặp lại cho đến khi giá trị đầu vào được cung cấp nằm trong phạm vi.Trên mỗi lần lặp, kiểm tra xem giá trị có nằm trong phạm vi được chỉ định không.Nếu điều kiện được đáp ứng, hãy sử dụng một câu lệnh ngắt để thoát ra khỏi vòng lặp.Use a while loop to iterate until the provided input value is in range. On each iteration, check if the value is in the specified range. If the condition is met, use a break statement to break out of the loop.Use a while loop to iterate until the provided input value is in range. On each iteration, check if the value is in the specified range. If the condition is met, use a break statement to break out of the loop.

Làm thế nào để bạn chỉ cho phép một số đầu vào nhất định trong Python?

Để chỉ chấp nhận số làm đầu vào người dùng: Sử dụng vòng lặp thực sự để lặp cho đến khi người dùng nhập một số.Sử dụng lớp float () để cố gắng chuyển đổi giá trị thành số điểm nổi.Nếu người dùng nhập một số, hãy sử dụng câu lệnh break để thoát ra khỏi vòng lặp.Use a while True loop to loop until the user enters a number. Use the float() class to attempt to convert the value to a floating-point number. If the user entered a number, use the break statement to break out of the loop.Use a while True loop to loop until the user enters a number. Use the float() class to attempt to convert the value to a floating-point number. If the user entered a number, use the break statement to break out of the loop.

Làm thế nào để bạn kiểm soát đầu vào trong Python?

Cú pháp của hàm đầu vào ()...

Sử dụng hàm input () để lấy đầu vào của người dùng Python từ bàn phím ..

Nhấn phím Enter sau khi nhập giá trị ..

Chương trình chờ đợi đầu vào của người dùng một cách vô định, không có thời gian chờ ..

Hàm đầu vào trả về một chuỗi, mà bạn có thể lưu trữ trong một biến ..