繁体   English   中英

如何使用python验证输入中的数字?

[英]How to verify numbers in input with python?

我正在努力学习如何编程,我遇到了一个问题....

我试图弄清楚如何确保有人输入数字而不是字符串。 我发现的一些相关答案令人困惑,有些代码对我不起作用。 我觉得有人发布了try:function,但它没有用,所以也许我需要导入一个库?

这就是我现在正在尝试的:

码:

print "Hi there! Please enter a number :)"
numb = raw_input("> ")

if numb != str()
    not_a_string = int(next)
else:
    print "i said a number, not a string!!!"

if not_a_string > 1000:
    print "You typed in a large number!"

else:
    print "You typed in a smaller number!"

我问的时候还有另外一个问题。 我该怎么做才能接受大写和小写拼写? 在下面的代码中,如果我输入“Go to the mall”但是使用小写G,它将不会运行if语句,因为它只接受大写G.

print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")

if answer == "Go to the mall":
    print "Awesome! Let's go!"
elif answer == "Get lunch":
    print "Great, let's eat!"
elif answer == "Go to sleep":
    print "Time to nap!"
else:
    print "Not what I had in mind...."

谢谢。 ^^

编辑:我也使用python 2.7而不是3.0

你可以这样做:

while True: #infinite loop
   ipt = raw_input(' Enter a number: ')
   try:
      ipt = int(ipt)
      break  #got an integer -- break from this infinite loop.
   except ValueError:  #uh-oh, didn't get an integer, better try again.
      print ("integers are numbers ... didn't you know? Try again ...")

要回答第二个问题,请使用.lower()字符串方法:

if answer.lower() == "this is a lower case string":
   #do something

如果您想要,您可以使字符串比较非常强大:

if answer.lower().split() == "this is a lower case string".split():

在这种情况下,您甚至可以匹配“ThIs IS A lower Case \\ tString”等字符串。 为了使你接受的内容更加自由,你需要使用正则表达式。

(并且所有这些代码在python2.x或3.x上都可以正常工作 - 我通常将我的print语句括在括号中以使其适用于任一版本)。

编辑

这段代码在python3.x上不太适用 - 在python3中,你需要将raw_input更改为input以使其工作。 (对不起,忘了那个)。

首先,你应该每个帖子只问一个问题。

Q1:使用内置的.isdigit()

if(numb.isdigit()):
    #do the digit staff

Q2:您可以使用string.lower来解决资金问题。

你可以试试


    numb = numb.strip()
    if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
        # process numb

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM