基于input()数据类型执行不同任务的Python

2024-09-30 02:30:16 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑: 这篇文章与Asking the user for input until they give a valid response不同,因为我不会根据响应的数据类型结束循环。字符串和整数都是有效的。只有当两个条目是不同的数据类型时,循环才会回退

我试图通过input()收集两个单词或两个整数如果两个值都是整数我想计算answer1**answer2.如果两个值都是非整数,我想连接字符串。最后,如果数据类型不匹配,我希望将用户发送到开头以输入两个新值

这是我的尝试。我为你将要看到的事提前道歉

## collect first value
print("Please type a word or an integer:")
answer1 = input()

## check for blanks
if answer1 == "":
    print("Blank space detected. Please retry.")
    answer1 = input()

## collect second value
print("Please type another word or integer:")
answer2 = input()

## check for blanks
if answer2 == "":
    print("Blank space detected. Please retry.")
    answer2 = input()

## define test for integer status
def containsInt(intTest):
    try: 
        int(intTest)
        return True
    except ValueError:
        pass

## check for matching data types and produce final value
if containsInt(answer1) == True:
    containsInt(answer2)
    if containsInt(answer2) == True:
        finalInt = (int(answer1))**(int(answer2))
        print("\n")
        print(finalInt)
    else:
        print("Sorry, the data types must match - both words or integers.")
        continue
else:
    containsInt(answer2)
    if containsInt(answer2) !=True:
        print("\n")
        print(answer1 + answer2)
    else:
        print("Sorry, the data types must match - both words or integers.")
        continue

我试图用“continue”让它回到开头,但它对我很生气。你可能知道我是个十足的新手,这是我的第一篇帖子。请不要对我太苛刻(


Tags: orthetrueforinputifvalue整数
2条回答

continue仅适用于循环,即forwhile。您试图在循环之外使用continue,这就是Python不喜欢它的原因

您可以做的一件事是检查数据类型是否匹配,然后基于此执行操作:

if type(answer1) == type(answer2):
    if isinstance(answer1, str):
        # do string stuff
    elif isinstance(answer1, int) or isinstance(answer1, float):
        # do calculations
    else:
        # types match but are not strings or numbers
else:
    # types don't match, react accordingly

默认情况下,Python将输入视为string,因此即使为输入指定一个数字,它也将是string类型。您可以通过多种方式解决此问题,其中之一是尝试将输入转换为数字^在本例中,{}比int工作得更好,因为否则您无法很好地处理小数。例如:

answer1 = input()
try:
    answer1 = float(answer)
except:
    pass

这样做的目的是尝试将默认输入的字符串转换为浮点数,如果这不起作用,那么它将保持为字符串

这应该起作用:

while True:
    answer1 = input("Please type a word or an integer:")

    # check for blanks
    while answer1 == "":
        answer1 = input("Blank space detected. Please retry.")

    try:
        answer1 = int(answer1)
    except ValueError:
        pass

    answer2 = input("Please type another word or integer:")

    # check for blanks
    while answer2 == "":
        answer2 = input("Blank space detected. Please retry.")

    try:
        answer2 = int(answer2)
    except ValueError:
        pass

    if type(answer1) == type(answer2):
        if type(answer1) == str:
            print(answer1 + answer2)
            break
        elif type(answer1) == int:
            print(answer1**answer2)
            break
    else:
        print(f"Sorry, the data types of '{answer1}' and '{answer2}' do not match.")
        continue

请注意,如果您输入像1.5这样的数字,它将被视为字符串。 因此输入1.5a将导致1.5a

相关问题 更多 >

    热门问题