【问题标题】:Python - Performing different tasks based input() data-typePython - 基于输入()数据类型执行不同的任务
【发布时间】:2021-05-24 11:13:53
【问题描述】:

编辑: 这篇文章与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

我试图用“继续”让它回到开头,但它对我很生气。您可能会说我是一个完整的新手,这是我的第一篇文章。请不要太用力地撕扯我。 :(

【问题讨论】:

标签: python input types while-loop continue


【解决方案1】:

这应该可行:

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

【讨论】:

  • 这完美!非常感谢。
【解决方案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 将输入视为strings,因此即使给输入一个数字,它也将是string 类型。您可以通过多种方式解决此问题,其中之一是您例如尝试将输入转换为数字。在这种情况下,floatint 效果更好,否则你将无法很好地处理小数。示例:

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

这样做是您尝试将默认输入的字符串转换为浮点数,如果这不起作用,则它将保留为字符串。

【讨论】:

  • 感谢您的贡献!不幸的是,这告诉我一切都匹配。我使用print(type(answer1))print(type(answer2)) 来确定,即使我在 input() 中输入一个整数,它也会将其视为一个字符串。
  • 我已编辑我的答案以帮助您解决此类问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
相关资源
最近更新 更多