Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

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!')

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

Gino Mempin

21.8K26 Huy hiệu vàng90 Huy hiệu bạc117 Huy hiệu đồng26 gold badges90 silver badges117 bronze badges

Hỏi ngày 27 tháng 4 năm 2014 lúc 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ố except 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:54

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

HarrycburnharrycburnHarryCBurn

7451 Huy hiệu vàng7 Huy hiệu bạc17 Huy hiệu đồng1 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:49

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

Ahsan Royahsan RoyAhsan Roy

6405 Huy hiệu bạc13 Huy hiệu Đồng5 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)

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

OCRDU

2.0976 Huy hiệu vàng14 Huy hiệu bạc22 Huy hiệu đồng6 gold badges14 silver badges22 bronze badges

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

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

VarunvarunVarun

Phù hiệu đồng 4144 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:50

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

CyrillecyrilleCyrille

Huy hiệu vàng 13,5K22 gold badges18 silver badges40 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')

    ans = 0
    while not ans:
        try:
            ans = int(input('Out of these options\(1, 2, 3), which is your favourite?'))
            if ans not in (1, 2, 3):
                raise ValueError
        except ValueError:
            ans = 0
            print("That's not an option!")

    if ans == 1:
        print('Nice!')
    elif ans == 2:
        print('Cool')
    elif ans == 3:
        print('Awesome!')
    return None

Lipis

21K19 Huy hiệu vàng93 Huy hiệu bạc118 Huy hiệu đồng19 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:31

Georsfegeorstefgeorstef

1.3683 huy hiệu vàng12 Huy hiệu bạc18 Huy hiệu đồng3 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

from restricted_input import r_input
num = int(r_input("Out of these options\(1,2,3), which is your favourite? ", input_type="nothing", allow="123", maxlength=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.

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

FgoofgooFGoo

832 Huy hiệu bạc4 Huy hiệu đồng2 silver badges4 bronze badges

0

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

Installation:

pip install PyInputPlus

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!')

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số

mkrieger1

16.2k4 Huy hiệu vàng50 Huy hiệu bạc58 Huy hiệu Đồng4 gold badges50 silver badges58 bronze badges

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

Hướng dẫn python user input only numbers - người dùng python chỉ nhập số