[英]How to take user input and use the if else function to give outputs
我試圖接受用戶輸入,並使用if else函數將結果作為基礎。
此輸入是一個名稱,如果是字符串,則輸出應該是文本'What a beautiful name you have'
,如果是int或float,則輸出應該是'Sorry , please enter a name'
。 但是,如果我輸入int或str,則兩個輸出都是'What a beautiful name you have'
。 我該怎么辦? 這是我的代碼:
name = input("What is your name?")
if type(input) is str:
print("What a beautiful name you have!")
elif type(input) is int or float:
print("Sorry, enter a proper name")
有幾個問題。
1)您使用input
作為type
參數-> elif type(input)...
您應該使用name
。
2) input()
總是返回一個str
。 您必須將其強制轉換為所需的類型。
3) elif type(input) is int or float
並沒有執行您認為的操作。 這等效於elif (type(input) is int) or float
因此它將始終為True
因為float
是Truthy。 您需要做elif type(name) is int or type(name) is float
。
4)您不應使用type(...)
進行比較,而應使用isinstance(name, str)
。
嘗試這個 :
name = input("What is your name?")
if all(x.isalpha() or x.isspace() for x in name):
print("What a beautiful name you have!")
else:
print("Sorry, enter a proper name")
注意: name
始終為字符串格式。 如果要檢查是否有任意數量的name
,那么你可以這樣做: any(i.isnumeric() for i in name)
輸入函數將返回一個字符串,而不管該字符串的內容如何。 字符串"1"
仍然是字符串。
您可能想做的是檢查字符串是否可以無誤轉換為數字:
s = input("what is your name?")
try:
float(s)
print("Sorry, enter a proper name")
except ValueError:
print("What a beautiful name you have!")
問題是機器的輸入將始終是字符串。 因此,即使您輸入數字或浮點數,也將其視為字符串。 考慮以下使用正則表達式的代碼,以識別您的字符串是否包含int / float:
import re
name = input("What is your name?")
if re.match('[0-9]', name):
print("Sorry enter a proper name")
else:
print("What a beautiful name")
希望這可以幫助!
這部分工作,但您需要在引號下鍵入名稱,否則您將收到錯誤消息,因為python正在尋找變量名稱。 如果將整數寫在引號內,則它們將被視為str,但如果不是,則代碼將完成其工作。 TBH如果不給我個竅門,我看不到可行的解決方案。
x = eval(input("What is your name? "))
if isinstance(x, str):
print ("What a beautiful name you have!")
else:
print ("Sorry, enter a proper name")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.