2015-02-05 39 views
-1

如何在python中編寫以下while循環?python中的測試用例如C語言編程

int v,t; 
while (scanf("%d %d",&v,&t)==2) 
{ 
    //body 
} 
+1

你能告訴我們你有什麼到目前爲止已經試過? – 2015-02-05 19:17:55

+0

其實我想用這個循環來解決uva問題10071(http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1012) – Neo 2015-02-05 19:22:24

+0

如果你查找while循環的語法 - 它幾乎是一樣的。 – neil 2015-02-05 19:26:17

回答

2

Python是比C更高級別的語言,通常會針對這種情況使用不同的模式。有一個被刪除的問題實際上與你的C代碼段具有完全相同的行爲 - 因此會是「正確的」,但它變得如此醜陋一段Python中的代碼,它的速度很低。

因此,首先要做的事情是2015年,人們不能簡單地在提示符處查看C的「scanf」,並且應該輸入兩個以空格分隔的整數 - 你最好給出一條消息。另一大區別在於,在Python中,變量賦值被視爲語句,並且不能在表達式中完成(在這種情況下爲while表達式)。所以你必須有一個始終爲真的while表達式,並決定是否稍後中斷。

因此,你可以像這樣的模式。

while True: 
    values = input("Type your values separated by space, any other thing to exit:").split() 
    try: 
     v = int(values[0]) 
     t = int(values[1]) 
    except IndexError, ValueError: 
     break 
    <body> 
+0

的確,除非常罕見的例外情況,Python中的while循環不是慣用的,除非它以'while true:'開頭。 – 2015-02-05 19:34:42

0

這取代你的代碼的行爲:

import re 

while True: 
    m = re.match("(\d) (\d)", input()): 
    if m is None: #The input did not match 
     break #replace it with an error message and continue to let the user try again 
    u, v = [int(e) for e in m.groups()] 
    pass #body