简介:我正在尝试编写一个简单的程序来检查给定的代码是否有效。如果输入的所有三个字符都是0到9之间的数字,则代码有效。如果代码有效,您的程序会显示一条消息谢谢。我们将处理您的订单!程序的输出应该是错误消息验证码无效。请再次检查您的信用卡代码。如果输入无效。
ATTEMPT:
lol = raw_input("what's your code?")
rofl=lol.split()
for int in rofl:
if 9>int(rofl)>0:
print "Thank you. We will process your order!"
else:
print 'The verification code was not valid. Please check your credit card code again.'
目的:
要学习 - 我发现了另一种方法,只需检查整个事物是否在1000以及0以下,并且它工作得很好。但我只是想了解更多。
REQUEST:
您明确指示如何修复我的代码并提供任何其他相关建议。
CLOSE:
提前谢谢。
答案 0 :(得分:4)
你要做的是检查给定的输入是否与给定的模式匹配(在你的情况下是三位数),这基本上是为正则表达式做的。
使用正则表达式,您的代码将如下所示:
import re
code = raw_input("what's your code? ")
if re.match(r'^\d{3}$', code):
print "Code OK"
else:
print "Wrong Code!"
在正则表达式中,^
表示“字符串的开头”,\d
表示“数字”(也可能是[0-9]
),{3}
表示“重复3次“,$
表示”字符串的结尾“。
有关正则表达式的更多信息,请查看re module documentation。
答案 1 :(得分:3)
a = raw_input()
if a.isdigit() and 0<int(a)<1000 and len(a)==3:
print "yeah!"
else:
print "Nope."
isdigit()是一个很酷的内置函数,它检查字符串是否完全由数字组成!你不必在try /中包装int(a),因为'和'作为一个短路运算符,如果isdigit()返回false,它将阻止对int(a)进行求值。
编辑:添加len(a)== 3。
答案 2 :(得分:2)
你的第一个问题是.split()
没有将字符串拆分成字符,它将字符串拆分为空格。
"12 34 56".split() == ["12", "34", "56"]
.split()
,只需使用for character in string
。lol
和rofl
等变量名称的代码,所以我改变了这一点。9 > int(digit) > 0
的检查不包括9
和0
。我认为这是一个意外,因此我使用0 <= int(digit) <= 9
并将其包括在内。int(digit)
无法将digit
转换为int
,则会引发异常。相反,我只是比较角色本身,看它是否在"0"
和"9"
之间,而不是转换它。code = raw_input("what's your code?")
for digit in code:
if not ("0" <= digit <= "9"):
print "The verification code was not valid. Please check your credit card code again."
break
else:
print "Thank you. We will process your order!"
使用循环的紧凑替代方法是使用带有any
函数的生成器表达式:
code = raw_input("what's your code?")
if all("0" <= digit <= "9" for digit in code):
print "Thank you. We will process your order!"
else:
print "The verification code was not valid. Please check your credit card code again."
答案 3 :(得分:2)
lol = raw_input("what's your code?")
rofl=lol.split()
# split() doesn't perform as you think.
# it separates parts of string according to space, tab and line ends.
for int in rofl:
# this is a loop using 'int' as variable name, not a good idea at all
# as int is a standard type
if 9>int(rofl)>0:
# rofl is a list.
# if you don't redefine int, and use "for d in lol" instead to loop the digits
# then int(d) witll throw an exception if it's not a digit
print "Thank you. We will process your order!"
else:
print 'The verification code was not valid. Please check your credit card code again.'
# You don't test there is exactly 3 digits.
# And you reply to your test in the loop, so once per item in the loop