python_class 6.0001 lec2__python

來源:互聯網
上載者:User
#-*- coding:utf-8 -*- #!usr/env/bin python """ lec2 branching, iteration strings branching-if/elif/else while loops for loops """
# strings hi = "hello there" name = "ana" greet = hi + name print(greet) greeting = hi + " " + name print(greeting) silly = hi + ( " " + name) * 3 print(silly) """ 字串的運算,拼接,重複等 """
# output x = 1 print(x) x_str = str(x) print( "my fav number is", x, ".", "x=", x) print( "my fav number is", x_str + "." + "x=" + x_str) print( "my fav number is" + x_str + "." + "x=" + x_str) """ , 號預設是加空格的可用於整數 + 號用於字串的拼接 """
# input text = input( "Type anything...") print( 5 *text) num = int( input( "Type a number...")) print( 5 *num) """ 對於輸入用input()函數, 可以強制轉換輸入的類型(預設是字元類型)"""
# conditionals/branching x = float( input( "Enter a number for x: ")) y = float( input( "Enter a number for y: ")) if x == y: print( "x and y are equal") if y != 0: print( "therefore, x/y is", x /y) elif x < y: print( "x is smaller") elif x > y: print( "y is smaller") print( "thanks!") """ 分支語句的用法,用於判斷兩個變數的關係, 跳轉控制 if ->elif ->else C表示: if -> else if -> else """
# remainder num = int( input( "Enter a number: ")) if num % 2 == 0: print( "number is even") else: print( "number is odd") """ 經常用於判斷一個數的性質,素數,最大公約數等 """
# while loops n = 0 while n < 5: print(n) n = n + 1 while n > 5 and n == 10: print( "Just explain") l = True while l: print( "control the while loop") n = int( input( "Enter the n:")) if n == 11: l = False """ while 迴圈可以控制一個迴圈一直執行, 但為了避免死迴圈需要 設定一個出口推出迴圈。while + 邏輯語句控制-> 條件控制 """
# for loops for n in range( 5): print(n)
mysum = 0 for i in range( 10): mysum += 1 print(mysum)
mysum = 0 for i in range( 7, 10): mysum += 1 print(mysum)
mysum = 0 for i in range( 5, 11, 2): mysum += 1 if mysum == 5: break mysum += 1 print(mysum) """ for 迴圈可用於控制迴圈步數, range(start, stop, step) 包含start但是不包含stop step控制步頻 for i in [1, 10] 控制i的取值 for i in strings 可以取出字串的每個字元 """ # perfect squares ans = 0 neg_flag = False x = int( input( "Enter an integer: ")) if x > 0: neg_flag = True while ans ** 2 < x: ans = ans + 1 if ans ** 2 == x: print( "Square root of", x, "is", ans) else: print(x, "is not a perfect square") if neg_flag: print( "Just checking... did you mean", -x, ">") """ 理解程式的控制流程 """

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.