7、寫代碼
(1)實現用戶輸入用戶名和密碼,當用戶名為 seven 且 密碼為 123 時,顯示登陸成功,否則登陸失敗!
_name = "seven"_pwd= "123"name= input("username:").strip()
pwd= input("password:").strip()if name == _name and pwd ==_pwd:print("logon successfully!")else:print("wrong username or password!")
View Code
(2)實現用戶輸入用戶名和密碼,當用戶名為 seven 且 密碼為 123 時,顯示登陸成功,否則登陸失敗,失敗時允許重復輸入三次
_name = "seven"_pwd= "123"i= 1
while i <= 3:
name= input("username:").strip()
pwd= input("password:").strip()if name == _name and pwd ==_pwd:print("登錄成功!")break
else:print("用戶名或密碼錯誤! 還剩%s次機會" % (3-i))
i+= 1
else:if i == 4:print("3次輸入錯誤,退出!")
View Code
(3)實現用戶輸入用戶名和密碼,當用戶名為 seven 或 alex 且 密碼為 123 時,顯示登陸成功,否則登陸失敗,失敗時允許重復輸入三次
_names = ["seven", "alex"]
_pwd= "123"i= 1
while i <= 3:
name= input("username:").strip()
pwd= input("password:").strip()if name in _names and pwd ==_pwd:print("登錄成功!")break
else:print("用戶名或密碼錯誤! 還剩%s次機會" % (3-i))
i+= 1
else:if i == 4:print("3次輸入錯誤,退出!")
View Code
8、寫代碼
a. 使用while循環實現輸出2-3+4-5+6...+100 的和
sum =0
i= 2
while i <= 100:if i % 2 ==0:
sum+=ielse:
sum-=i
i+= 1
print(sum)
View Code
b. 使用 while 循環實現輸出 1,2,3,4,5, 7,8,9, 11,12
i = 1
while i < 13:if i == 6 or i == 10:pass
else:print(i)
i+= 1
View Code
c. 使用while 循環輸出100-50,從大到小,如100,99,98...,到50時再從0循環輸出到50,然后結束
i = 100
while i >0:if i >= 50:print(i)else:print(50 -i)
i-= 1
View Code
d. 使用 while 循環實現輸出 1-100 內的所有奇數
i = 1
while i <= 100:if i % 2 !=0:print(i)
i+= 1
View Code
e. 使用 while 循環實現輸出 1-100 內的所有偶數
i = 1
while i <= 100:if i % 2 ==0:print(i)
i+= 1
View Code
10、制作趣味模板程序(編程題) 需求:等待用戶輸入名字、地點、愛好,根據用戶的名字和愛好進行任意顯示
如:敬愛可愛的xxx,最喜歡在xxx地方干xxx
name = input("name:").strip()
addr= input("address:").strip()
hobby= input("hobby:").strip()#使用format函數輸出:
print("敬愛可愛的{},最喜歡在{}地方干{}".format(name, addr, hobby)) #使用位置參數
print("敬愛可愛的{a1},最喜歡在{a2}地方干{a3}".format(a1=name, a3=hobby, a2=addr)) #使用關鍵參數
#使用%s格式化輸出:
print("敬愛可愛的%s,最喜歡在%s地方干%s" % (name, addr, hobby))
View Code
11、輸入一年份,判斷該年份是否是閏年并輸出結果。(編程題) 注:凡符合下面兩個條件之一的年份是閏年。 (1) 能被4整除但不能被100整除。 (2) 能被400整除。
year = input("輸入年份:").strip()if year.isdigit(): #判斷輸入是否合法
year =int(year)if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: #判斷是否閏年
print("{}是閏年".format(year))else:print("{}不是閏年".format(year))else:print("輸入不合法")
View Code
12、假設一年期定期利率為3.25%,計算一下需要過多少年,一萬元的一年定期存款連本帶息能翻番?
money = 10000year= 1
whileTrue:
money= money * (1+0.0325) #本金+利息
if money >= 20000: #翻番
print(year)breakyear+= 1
View Code
13、使用while,完成以下圖形的輸出:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
代碼:
i = 1j= 4
while i <= 5:print("*" *i)
i+= 1
while j >= 1:print("*" *j)
j-= 1
View Code
未完待續。。。。。。。