简单来说,我正在输入一个值,我想确定该值是否为 alpha。如果它不是 alpha,我想检查它是否是数字。如果它是一个数字,我想检查它是正数还是负数。
我读了很多关于检查签名号码的内容,例如-50. 有两种方法,我们可以使用这样的东西:
try:
val = int(x)
except ValueError:
print("That's not an int!")
Run Code Online (Sandbox Code Playgroud)
我认为我在这里不需要它,而且我不知道将它放在我的代码中的哪里。
另一种方法是使用.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")
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ?
这是集成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")
Run Code Online (Sandbox Code Playgroud)
它会为您完成所有繁重的工作,因为可以使用/自动int()处理数字。+-
| 归档时间: |
|
| 查看次数: |
9852 次 |
| 最近记录: |