[英]How do I get multiple inputs from the user with Python?
I would like to create a program that will input the enter size to the user and then enter type of individual triangle to select whether it is empty or no_empty, output 1 to 4 if empty and output 5 to 8 if no_empty.
我的代碼現在是這樣的。
tri = int(input("enter size : "))
empthy = input("type of rectangle triangle : " )
choice = int(input("Choose the triangle you want to draw.\n1. triangle1 \n2. triangle2 \n3. triangle3 \n4. triangle4 \n5. triangle5 \n6. triangle6 \n7. triangle7 \n8. triangle8\n== >"))
print_triangle(tri, empthy, choice)
但是我想要制作的代碼示例,
輸入尺寸:10
矩形三角形的類型:空的
選擇要繪制的三角形n1。 三角形1 \n2。 三角形2 \n3。 三角形3 \n4。 三角形4
或者
輸入尺寸:10
矩形三角形的類型:no_empthy
選擇要繪制的三角形 n5。 三角形5 \n6。 三角形6 \n7。 三角形7 \n8。 三角形8
我的問題是如果你 select no_empty in(“垂直三角形的類型”),它將 output 從 1 到 8。
歡迎來到 Stackoverflow 兄弟!!
triangle_size = int(input("Enter size : "))
filling = input("Do you want empty triangle or no_empty triangle: ")
if(filling=="empty"):
choice = int(input("Choose the triangle you want to draw.\n1. triangle1 \n2. triangle2 \n3. triangle3 \n4. triangle4\n== >"))
elif(filling=="no_empty"):
choice = int(input("Choose the triangle you want to draw.\n5. triangle5 \n6. triangle6 \n7. triangle7 \n8. triangle8\n== >"))
print_triangle(triangle_size, empty, choice)
您必須使用if - else
來決定要向用戶顯示的三角形,例如:
tri = int(input("enter size : "))
empty = input("type of rectangle triangle : " )
if empty=="empty":
choice = int(input("Choose the triangle you want to draw.\n1. triangle1 \n2. triangle2 \n3. triangle3 \n4. triangle4\n== >"))
elif empty=="no_empty":
choice = int(input("Choose the triangle you want to draw.\n5. triangle5 \n6. triangle6 \n7. triangle7 \n8. triangle8\n== >"))
print_triangle(tri, empty, choice)
沒有看到print_triangle
function 的代碼很難判斷為什么它是 output 從 1 到 8 的所有內容,但是如果您需要驗證您的輸入,您可以這樣做。
1) 聲明一個 function 來判斷輸入是否有效。 例如,如果我們想檢查輸入是否是正確的 integer 類型,我們這樣做:
def validate_integer_input(s):
return int(s)
def validate_exactly_2_int_input(s):
parts = s.split()
if len(parts) != 2:
raise ValueError
return list(map(int, parts))
如果數據有問題,驗證器會返回值或引發 ValueError。
2)然后您編寫修改后的輸入 function 如下:
def validated_input(validator):
while True:
try:
return validator(input())
except ValueError:
pass
這個 function 將繼續嘗試接收用戶的輸入,直到輸入正確的數據。
3)使用它:
a = validated_input(validate_integer_input)
pairs = validated_input(validate_exactly_2_int_input)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.