[英]How to ask for a boolean input from a user to qualify if statements and print a sentence using that information in Python
我在這里是我的第一個查詢(希望不是最后一個查詢)。
我正在嘗試從用戶那里獲取信息,特別是布爾值,以確定它們是男性/女性還是身材高/矮,然后打印正確的語句“您是男性/女性身高/矮”
is_tall = input("Are you tall?")
is_male = input("Are you male?")
if is_tall and is_male:
print("You are a tall male")
elif is_tall and not(is_male):
print("You are a tall female")
elif not(is_tall) and is_male:
print("You are a short male, sorry")
else:
print("You are a short female, sorry")
我的代碼運行並始終返回“您是個高個子男性”,搜索顯示這是因為用戶輸入的內容始終是真實的,因為它是字符串。
我已經看到了其他示例,它們可以獲取布爾值,但不能在if語句中同時獲取兩個值並同時使用它們。 我在附近任何地方嗎?我想念什么? 我知道我不能在輸入周圍使用bool()進行轉換。
當前,您正在檢查字符串是否為非零。 而是,檢查字符串的值。
if is_tall.upper() in ('YES', 'Y') and is_male.upper() in ('YES', 'Y'):
print("You are a tall male")
elif is_tall.upper() in ('YES', 'Y') and is_male.upper() in ('NO', 'N'):
print("You are a tall female")
等等
您可以在in后面的括號in
.upper()
任意.upper()
有效字符串(答案),並且將所有輸入都強制為.upper()
或.lower()
可以使您避免處理兩倍(或更多)可能的響應。
您可以嘗試這樣的事情:
tall_str = input("Are you tall? ")
while tall_str.lower() not in {'y', 'yes', 'n', 'no'}:
tall_str = input("Are you tall [y/n] ? ")
is_tall = True if tall_str.lower() in {'y', 'yes'} else False
這將接受'Yes'
和'nO'
(對於tall_str
)之類的東西,然后將它們轉換為True
或False
(對於is_tall
),然后再次詢問給定的答案是否可接受。
然后可以對is_male
執行相同的is_male
。
將字符串轉換為布爾值后, if
子句將起作用。
這種方法適合您嗎?
is_tall = True if input("Are you tall?").lower() == 'y' else False
is_male = True if input("Are you male?").lower() == 'y' else False
...
盡管可以自己進行轉換,但沒有簡單的方法來獲取布爾值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.