2012-04-17 80 views
0

新手來蟒蛇,並在我最新的程序中遇到困難。簡單地說,我試圖編寫一個用戶輸入變量的遞減循環,如果可能的話。基本上,我有一個全局常量設置爲例如如圖13所示,每當程序循環時,它提示用戶輸入一個值,然後該用戶值被剃掉13,直到它達到0.問題在於它確實刮掉了它,但是當它重申它將值重置爲13並且僅移除當前迭代值輸入。所以如果每次迭代輸入2次,它就會將其減少到11次......但我以2次爲例再次以11,8,5等等爲例或以3爲例10,7, 4名....任何幫助球員將非常感激,乾杯:)基本遞減循環 - PYTHON

a = 13 

def main(): 
    runLoop() 

def runLoop(): 
    while other_input_var > 0: # guys this is my main score accumulator 
           # variable and works fine just the one below 
     b=int(input('Please enter a number to remove from 13: ')) 
     if b != 0: 
      shave(a, b) 

def shave(a, b): 
    a -= b 
    print 'score is %d ' % a 
    if a == 0: 
     print "Win" 

main() 
+0

查看'global'關鍵字,然後閱讀所有可能的關於爲什麼使用它是一個很好的跡象表明你正在做一些可怕的錯誤。 – geoffspear 2012-04-17 13:34:37

+0

我明白了,所以變量應該在函數shave()中進行本地化?是的,這是我一直堅持的作業的一部分。 – user1291271 2012-04-17 14:03:03

回答

-1

不回答你的問題,而是字符串格式化的演示。這是舊式,使用%「字符串插值運算符」。

a = 100 
while a: 
    shave = int(raw_input("Input a number to subtract from %i:" % a)) 
    if (shave > 0) and (shave <= a): 
     a -= shave 
    else: 
     print ("Number needs to be positive and less than %i." % a) 

有該程序的會話:

Input a number to subtract from 100:50 
Input a number to subtract from 50:100 
Number needs to be positive and less than 50. 
Input a number to subtract from 50:30 
Input a number to subtract from 20:20 

在原始字符串的%i是其由%操作者在琴絃之後填充在一個整數(i爲整數)的佔位符。

還有%f用於浮點數字,%s用於字符串等等。你可以做很多漂亮的事情,例如指定打印的小數點位數 - %.3f保留三位小數 - 等等。

又如:

>>> "My name is %s and I'm %.2f metres tall." % ('Li-aung',1.83211) 
"My name is Li-aung and I'm 1.83 metres tall." 

這是一個比一個更容易閱讀:

"My name is " + name + " and I'm " + str(round(age,2)) + " metres tall" 

瞭解了更多關於字符串格式化old waynew way

2

在我的愚見有這樣一個小片段的addtional功能最終在複雜的事情。不過很高興看到你正在理解這個概念。我沒有測試過這個,但是這個應該做同樣的事情,你正在尋找。注意行5我保證輸入的數字不會超過a的當前值。如果他們/你意外地輸入了更高的值,這應該會有所幫助。下一步將是如果你還沒有嘗試過,請參閱Python Error Handling。希望這可以幫助!

def main(): 
    a = 13 
    while a: 
     b = int(input("Please enter a number to remove from " + str(a) + " : ")) 
     if b > 0 and b <= a: 
      a -= b 
      print "Score is ", str(a) 
    print "Win"  

main() 
+0

感謝dc,虐待嘗試並執行它 – user1291271 2012-04-17 13:48:49

+0

我在這裏測試了一個盒子,並且必須修復一件東西或2件,它現在可以工作。讓我知道! – dc5553 2012-04-17 14:01:59

+0

使用字符串格式化運算符'%':''請輸入一個數字以從%i中刪除:「%a',而不是將'a'轉換爲字符串('str(a)')並使用字符串連接。閱讀關於字符串格式化[舊方式](http://docs.python.org/library/stdtypes.html#string-formatting-operations)或[新方式](http://docs.python.org /library/string.html#string-formatting)。 – 2012-04-17 14:22:45