如何在python中修复我的ValueError消息? [英] How do I fix my ValueError message in python?

查看:265
本文介绍了如何在python中修复我的ValueError消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

choice1=("yes")
choice=("no")

import sys

while True:
    try:
        user5=input("is your phone working")
    except ValueError:
        print("Sorry, I didn't understand that, make sure to reply with 'YES' or 'NO'")
        
    if user5==choice1:
        print("thats great")
        sys.exit(0)
        break
    elif user5==choice:
        print("you could contact seller")
        while True:
            try:
                user_response=input("is it fix?")
            except ValueError:
                print("sorry i didnt understand that, make sure to reply with 'YES' or 'NO'")
            if user_response==choice1:
                print("great")
                sys.exit(0)
                break
            elif user_response==choice:
                break
        break



当用户给出inv时alid响应,它假设打印错误消息但跳过它,并重复该问题。像这样:


When the user gives an invalid response, its suppose to print the error message but it skips it, and repeats the question. Like so:

is your phone workinglll
is your phone working;';'';
is your phone workinglll;l;l
is your phone working;ll;';';l;';'
is your phone working





当用户输入无效回复时,它会显示消息

:抱歉我不明白,请务必回复'是'或'否,然后再问问题,直到得到有效答复。



When the user enters an invalid response, its suppose to display the message
:sorry I didn't understand that, make sure to reply with 'YES' or 'NO and then ask the question again until it gets a valid response.

推荐答案

输入刚刚接受任何字符串,如果响应是yes或no,它不会抛出ValueError。



相反,你必须使用if-else语句检查您回答是或否,如果没有, continue 语句将返回到循环的开头,以便再次得到问题。

input just accepts any string, it won't throw a ValueError if the response is anything else than yes or no.

Instead, you have to use an if-else statement that checks that you responded yes or no, and if you didn't, the continue statement returns to the beginning of the loop so you get the question again.
user5 = input("Is your phone working?").lower()
if user5 != choice and user5 != choice1:
    print("Sorry, I didn't understand that, make sure to reply with 'YES' or 'NO'.")
    continue



并且:


And:

user_response = input("Is it fixed?").lower()
if user_response != choice and user_response != choice1:
    print("Sorry, I didn't understand that, make sure to reply with 'YES' or 'NO'.")
    continue


这篇关于如何在python中修复我的ValueError消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆