2011-11-03 80 views
-3

我有這個問題---Python中的乘法表

編寫代碼將打印10個正整數的乘積表和10個正整數下行。提示用戶輸入列和行的起始值。

我試圖從另一個問題,不打印像Id期望它的一些解釋。我在哪裏調用print語句,什麼是錯的迭代

row = int(raw_input("Enter the first row number: " )) 
col = int(raw_input("Enter the frist column number: ")) 

lastRow = row + 10 
lastCol = col + 10 


while (row < lastRow): 
    print "%4d" % (col * row) 
    while(col < lastCol): 

     print "%4d" % (col * row), 
     col += 1 

    print "%4d" % (col * row) 
    row += 1 

這裏有一個二去,更好,但並不像我想得

 row = int(raw_input("Enter the first row number: " )) 
    col = int(raw_input("Enter the frist column number: ")) 

    lastRow = row + 10 
    lastCol = col + 10 

    x=row 
    y=col 

    while (x < lastRow): 
     while(y < lastCol): 
      y += 1 
      print "%4d" % (y * x) 
     x += 1 

很抱歉的重複後,我沒有知道這是不好的禮節

+3

[Python用戶輸入和乘法表]的可能重複(http://stackoverflow.com/questions/7990991/python-user-input-and-multiplication-table) – agf

回答

0

快速編輯,做的伎倆:在你的代碼

row = int(raw_input("Enter the first row number: " )) 
col = int(raw_input("Enter the frist column number: ")) 

lastRow = row + 5 
firstCol = col 
lastCol = col + 5 

while (row < lastRow): 
    while(col < lastCol): 
     print "%4d" % (col * row), 
     col += 1 

    col = firstCol 
    row += 1 
    print 

問題:

  1. col在保持在lastCol值第一次循環迭代的結束。每一行
  2. 太多不必要print
  3. row增量應的第一while

和尖端內部完成後,它應該是重置爲出發點:如果您遇到像這樣的問題,得到一張紙,放下簡單和小的起始值:row = 1,col = 1,最多3個,而不是10個。手工一步一步地重現您的算法。

+0

謝謝我不明白,行增量是在第一時間,而我只是忘記,我將不得不保存初始值,編碼對我來說依然陌生, – user1020349

3

(1)您的col變量沒有得到每個新行的重置。 它只是一直遞增。

也許使用另一對變量,如rc作爲迭代本身。

或者將原始行和列存儲在不同名稱的變量中。 (2)最後兩行的縮進似乎是錯誤的 - 它不應該在第一個while循環中嗎?

(3)您不需要太多的打印語句。 您應該只需要在內部循環中打印一條語句,而另一條(空的)就可以結束每一條線。

更新:請不要發佈重複的問題

+0

在這裏修正了縮進錯字,所以我需要將原始行和列存儲在循環外部? – user1020349

+0

@ user1020349:是的。見斯坦尼斯拉夫的答案。 – jwd

+0

對不起有關重複帖子,我不知道那是不好的禮節 – user1020349