2016-10-22 30 views
0

在這個問題中,我不得不創建一個程序,提示用戶輸入一個數字,然後再次提示要創建多少行。喜歡的東西:For循環方形圖案的數字

1 1 1 1 1 1 1 
2 2 2 2 2 2 2 
3 3 3 3 3 3 3 
4 4 4 4 4 4 4 

這是我想出了,我已經嘗試了許多不同的方法來得到相同的結果,但沒有奏效。

num=int(input("Enter a number between 1 and 10: ")) 
rows=int(input("Enter how many rows to of numbers: ")) 
for i in range(num): 
    print(i,end=" ") 
for x in range(rows): 
    print (x) 

這是我想出了輸出:

Enter a number between 1 and 10: 6 
Enter how many rows to of numbers: 4 
0 1 2 3 4 5 0 
1 
2 
3 

回答

1

你可能只是不喜歡它:

num = 5 
rows = 4 
for i in range(1, num+1): 
    print('{} '.format(i) * rows) 

輸出:

1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 
5 5 5 5 

說明: WHE如果您將某個str乘以某個數字,例如n,則返回原始字符串的新字符串,重複n次。這個做你會消除你的嵌套循環

+0

但我仍然需要提示用戶 – 3loosh

+0

這是演示代碼。我硬編碼'num'和'rows'。在你的代碼中使用你正在做的'input()'的值。只需替換我的for循環的邏輯。 –

+0

而不是使用範圍(1,num + 1),只需在for循環中使用i + 1即可。 – Jonas

0

簡單的解決方案:只需使用嵌套的for循環:

num = int(input("Enter a number between 1 and 10: ")) 
rows = int(input("Enter how many rows to of numbers: ")) 
for i in range(num): 
    print ('\n') 
    for x in range(rows): 
     print (i + 1) 

上面的代碼將通過範圍從0到NUM,印刷第一新行,然後打印出當前數行數次。