簡體   English   中英

設置“if”以確保變量是數字而不是字母/符號

[英]setting “if” to make sure variable is a number and not a letter/symbol

如何創建“if”語句以確保輸入變量是數字而不是字母?

radius = input ('What is the radius of the circle? ') 

#need if statement here following the input above in case user
#presses a wrong key    

謝謝你的幫助。

假設您正在使用python2.x:我認為更好的方法是將輸入作為raw_input 然后你知道它是一個字符串:

r = raw_input("enter radius:")  #raw_input always returns a string

上面語句的python3.x等效於:

r = input("enter radius:")      #input on python3.x always returns a string

現在,從那里構建一個浮點(或嘗試):

try:
    radius = float(r)
except ValueError:
    print "bad input"

關於python版本兼容性的一些進一步說明

在python2.x中, input(...)等效於eval(raw_input(...)) ,這意味着你永遠不知道從它返回什么 - 你甚至可以在input引發一個SyntaxError

關於 在python2.x上 使用 input 警告

作為旁注,我建議的程序使您的程序免受各種攻擊。 考慮一下用戶投入的日子有多糟糕:

__import__('os').remove('some/important/file')

提示時代替數字! 如果你eval ING,通過使用以前聲明中input上python2.x,或使用eval明確,你只是有some/important/file刪除。 哎呀。

嘗試這個:

if isinstance(radius, (int, float)):
    #do stuff
else:
    raise TypeError  #or whatever you wanna do

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM