一、python第一行代碼: 二、變數: name前後變化,而name2 = name已經將“SunDM12”賦值給了name2,name變化後,name2不再變化 三、交互: input函數:用戶可以在界面上顯示輸入字元,並賦值給了username 在屏幕列印的第一種格式。 %s是字元串;%d是雙 ...
一、python第一行代碼:
1 name = "你好,世界" 2 print(name)
二、變數:
1 name = "SunDM12" 2 name2 = name 3 print("my name : ",name, name2) 4 5 name = "wangba" 6 print(name, name2)
name前後變化,而name2 = name已經將“SunDM12”賦值給了name2,name變化後,name2不再變化
三、交互:
1 username = input("username : ") 2 print(username)
input函數:用戶可以在界面上顯示輸入字元,並賦值給了username
1 name = input("name :") 2 age = input("age :") 3 job = input("job :") 4 salary = input("salary :") 5 6 info = ''' 7 ------ info of %s ------ 8 name : %s 9 age : %s 10 job : %s 11 salary : %s 12 '''%(name, name, age, job, salary)
在屏幕列印的第一種格式。
%s是字元串;%d是雙精度;%f是浮點型
1 info2 = ''' 2 ------- info of {_name} ------- 3 name : {_name} 4 age : {_age} 5 job : {_job} 6 salary : {_salary} 7 '''.format(_name=name, 8 _name=name,_age=age,_job=job,_salary=salary)
在屏幕列印的第二種格式。
1 info3 = ''' 2 ------ info of {0} ------ 3 name : {0} 4 age : {1} 5 job : {2} 6 salary : {3} 7 '''.format(name,age,job,salary)
在屏幕列印的第三種格式。
四、登陸密碼:
1 import getpass 2 3 _username = 'SunDM12' 4 _password = '123456' 5 6 username = input('username :') 7 password = input('password :') 8 print(username,password) 9 10 if _username == username and _password == password 11 print("welcome user {name} login...".format(name = username)) 12 else: 13 print("Invalid username or password!")
其中getpass是一個package,提供可移植的面膜輸入
1. getpass.getpass()
2. getpass.getuser()
五、猜密碼游戲
1 correct_number = 12 2 guess_number = int(input("guess number:")) 3 4 if correct_number == guess_number: 5 print("yes,you got it...") 6 elif guess_number >correct_number: 7 print("think smaller...") 8 else: 9 print("think bigeer...")
其中input函數輸入是一個字元,此時要將其強制轉換為整型
5.1 while迴圈
1 count = 0 2 while True: 3 print("count :",count) 4 count = count +1 5 if count == 1000: 6 break
其中break表示跳出整個迴圈
correct_number = 12 count = 0 while count<3: guess_number = int(input("guess number:")) if correct_number == guess_number: print("yes,you got it...") elif guess_number >correct_number: print("think smaller...") else: print("think bigeer...") count + = 1 else: print("you have tried too many times.")
利用while迴圈進行設計猜數字游戲
5.2 for迴圈
1 for i in range(10): 2 print("loop ",i)
顯示1到10
1 for i in range(0,10,2): 2 print("loop :",i)
2是步長
correct_number = 12 for i in range(3): guess_number = int(input("guess number:")) if correct_number == guess_number: print("yes,you got it...") elif guess_number >correct_number: print("think smaller...") else: print("think bigeer...") else: print("you have tried too many times.")
利用for迴圈進行猜數字游戲
5.3 continue和break的區別
1 for i in range(10): 2 if i<5: 3 print("loop",i) 4 else: 5 continue 6 print("....") 7 8 for i in range(10): 9 print('-------',i) 10 for j in range(10): 11 print(j) 12 if j>5: 13 break
continue忽略當前語句,繼續執行下一行
break跳出當前執行的整個迴圈