2017-08-22 120 views
0

简单地说,我输入一个值,我想确定这个值是否为alpha。如果它不是alpha,我想检查它是否是数字。如果这是一个数字,我想检查它是正面还是负面。Python:如何检查签名的数字是正数还是负数还是无?

我读了很多关于检查签名的数字,如-50。有两种方法,我们可以用这样的:

>>> try: 
    val = int(x) 
except ValueError: 
    print("That's not an int!") 

哪我想我不需要在这里,我不知道在哪里把它放在我的代码。

另一种方法是使用.lstrip("-+"),但它不工作!

amount = 0 
while True: 
    amount = input("Enter your amount ===> ") 
    if amount.isalpha() or amount.isspace() or amount == "": 
     print("Please enter only a number without spaces") 
    elif amount.lstrip("-+").isdigit(): 
     if int(amount) < 0: 
      print("You entered a negative number") 
     elif int(amount) > 6: 
      print("You entered a very large number") 
     else: 
      print(" Why I am always being printed ?? ") 
    else: 
     print("Do not enter alnum data") 

我在做什么错?

+1

考虑,因为您使用的版本3 – JacobIRR

+0

这是为我工作,因为它是BTW消除蟒蛇2.7标签小于0或。 – JacobIRR

+0

也适用于我的魅力。 –

回答

2

这是你将如何整合try/except块:

amount = 0 
while True: 
    amount = input("Hit me with your best num!") 
    try: 
     amount = int(amount) 
     if amount < 0: 
      print("That number is too tiny!") 
     elif amount > 6: 
      print("That number is yuge!") 
     else: 
      print("what a boring number, but I'll take it") 
      break # How you exit this loop 
    except ValueError: 
     print("Wow dude, that's like not even a number") 

它所有繁重的你,因为int()可以自动+/-进程号。

+0

非常感谢!加快速度 – iCoder

2
>>> amount = '-6' 
>>> '-' in amount 
True 
>>> amount = amount.strip('-') 
>>> amount.isdigit() 
True 
0

检查数量大于0与< >

相关问题