【问题标题】:if and else statement pythonif 和 else 语句 python
【发布时间】:2020-05-19 22:29:16
【问题描述】:
import re
social = '1234'
phone = '5678'

user = int(input("Please tell me your last four digit of your social: "))

user1 = int(input("your last digit of your phone number: "))

info_checker = re.search("^12.*34$", social)

info_checker1 = re.search("^56.*78$", phone)

if info_checker and info_checker1:
    print("Great you're all set")
else:
    print("Sorry we couldn't find this info")

每当我输入用户的数据时,无论是对是错,它都只打印出 if 语句?

【问题讨论】:

  • 首先使用print(info_checker, info_checker1) 看看你得到了什么。或者学习如何使用调试器。
  • 您必须在search() 中使用useruser1,但您使用socialphone 始终具有相同的值'1234''5678'
  • user, user1 分配给输入语句!当我这样做时,它会打印出 TypeError: expected string or bytes-like object –
  • 不要将input()转换成int()

标签: python if-statement search python-re


【解决方案1】:

您必须在 search() - user 中使用正确的变量而不是 socialuser1 而不是 phone

info_checker = re.search("^12.*34$", user)

info_checker1 = re.search("^56.*78$", user1)

编辑:并且不要将用户的字符串转换为整数。


import re

user  = input("Please tell me your last four digit of your social: ")
user1 = input("your last digit of your phone number: ")

info_checker  = re.search("^12.*34$", user)
info_checker1 = re.search("^56.*78$", user1)

if info_checker and info_checker1:
    print("Great you're all set")
else:
    print("Sorry we couldn't find this info")

【讨论】:

  • 当我这样做时,它会打印出 TypeError: expected string or bytes-like object
  • 不要在int(input(...)) 中使用int() 并将其保留为字符串。
  • 我明白了!非常感谢:)