2015-06-21 45 views
-2

如何使用python引用字符串中的整數?我對編碼完全陌生,我試圖做這個bug收集練習,用戶將輸入一週中每天收集的錯誤數量,並顯示一週結束時收集的錯誤總數。參考字符串內的整數? Python

這是我到目前爲止的代碼。

totalBugs = 0.0 
day = 1 

for day in range(7): 
    bugsToday = input('How many bugs did you get on day', day,'?') 
    totalBugs = totalBugs + bugsToday 

print 'You\'ve collected ', totalBugs, ' bugs.' 

,所以我試圖讓內循環bugsToday提示詢問 用戶「有多少錯誤你第1天收?」 「您在第2天收集了多少個錯誤?」 等等。

我該怎麼做?

+0

你想「從用戶輸入讀取」。檢查:http://stackoverflow.com/questions/3345202/python-getting-user-input – doublesharp

+0

可能的重複[如何將字符串轉換爲整數在Python?](http://stackoverflow.com/questions/642154/如何將字符串轉換爲整數在Python中) – Paul

+0

's =「34」''n = int(s)''print n + 1'' 35' – Paul

回答

1

我會做如下的方式。 http://www.learnpython.org/en/String_Formatting

文章,我寫的raw_input左右與輸入爲安全起見,如果你在一個有興趣:

total_bugs = 0 #assuming you can't get half bugs, so we don't need a float 

for day in xrange(1, 8): #you don't need to declare day outside of the loop, it's declarable in the for loop itself, though can't be refernced outside the loop. 
    bugs_today = int(raw_input("How many bugs did you collect on day %d" % day)) #two things here, stick to raw_input for security reasons, and also read up on string formatting, which is what I think answers your question. that's the whole %d nonsense. 
    total_bugs += bugs_today #this is shorthand notation for total_bugs = total_bugs + bugs_today. 

print total_bugs 

要在字符串格式化讀了https://medium.com/@GallegoDor/python-exploitation-1-input-ac10d3f4491f

從Python文檔:

CPython實現細節:如果s和t都是字符串,一些Python實現(如CPython)通常可以執行一個就地優化形式爲s = s + t或s + = t的點燃。如果適用,這種優化使得二次運行時間不太可能。這種優化是版本和實現相關的。對於性能敏感的代碼,最好使用str.join()方法,以確保不同版本和實現之間的一致性線性級聯性能。

編程起初看起來不堪一擊,只要堅持下去就不會後悔。祝你好運,我的朋友!

+0

謝謝!這正是我正在尋找的!我一定會記得%d。 –

+0

沒問題,很樂意幫忙。我可能錯過了一些東西,xrange比範圍更快,所以我習慣性地使用它。 (1,8)1-7而不是0-6,我雖然更好,但取決於你。我在raw_input上使用了int(),因爲raw_input返回一個字符串,我們需要一個int類型。還要注意,%d是整數,%s是字符串,%f是浮點數等,你可能會發現.format方法更容易。 –

1

您可以嘗試

... 
for day in range(7): 
    bugsToday = input('How many bugs did you get on day %d ?' % day) 
    totalBugs = totalBugs + bugsToday 
... 
2

我個人很喜歡format()。你可以寫代碼如下:

totalBugs = 0 
for day in range(1, 8): 
    bugsToday = raw_input('How many bugs did you get on day {} ?'.format(day)) 
    totalBugs += int(bugsToday) 

print 'You\'ve collected {} bugs.'.format(totalBugs) 

range(1, 8)經過day = 1day = 7,如果這是你想要做什麼。