# while 跟 for 迴圈的基本學習 (彭彭老師第七堂) ## 嘗試用while迴圈 寫出等差級數的相加 > while的迴圈裏面 > 要記得給變異數累加的數值 (n=n+1 or n+=1) > 否則迴圈轉不起來 ```= n=1 sum=0 while n<=10: sum=sum+n n+=1 # n持續+1 迴圈的重要條件 print(sum) ``` ## 嘗試用for in 寫出等差級數的相加 ```= x=1 sum=0 for x in range(11): sum=sum+x print(sum) ``` ## 嘗試用while 寫出讓使用者輸入的等差級數相加 ```= s1=int(input("開始的數字:")) s2=int(input("結束的數字:")) s3=int(input("公差:")) sum=0 while s1<=s2: sum=sum+s1 s1+=s3 print(sum) ``` ## 嘗試用 for in 寫出讓使用者輸入的等差級數相加 * range(起始數值,結束數值(不含此數),步數(公差)) * 若不給公差,預設為1 ```= x=int(input("開始的數字:")) y=int(input("結束的數字:")) z=int(input("公差:")) sum=0 for x in range(x,y+1,z): sum=sum+x print(sum) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up