Python必考的5道面試題集合
更新時間:2022年07月02日 08:46:39 作者:小旭2021
這篇文章介紹了Python必考的5道面試題,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
1、使用while循環(huán)實現(xiàn)輸出2 - 3 + 4 - 5 + 6 ... + 100的和
#方法一 #從2開始計算 i = 2 #定義一個變量用于保存結果 sum=0 while i <= 100: if i % 2 == 0: sum = sum + i else: sum = sum - i i += 1 print("2-3+4-5+6...+100=",sum)
#方法二 n=3 sum=2 while n<=100 : #n對2取余 if n % 2 != 0: sum = sum - n n = n + 1 else: sum = sum + n n = n + 1 print("2-3+4-5+6...+100=",sum)
運行結果:
2、從鍵盤獲取一個數(shù)字,然后計算它的階乘,例如輸入的是3,那么即計算3!的結果,并輸出。
提示:
1!等于1
2!等于1*2
3!等于1*2*3
n!等于1*2*3*...*n
n = int(input("請輸入一個非負的數(shù)字:")) # 負數(shù)不算階乘 def factorial(n): if n == 0: return 1 # 0的階乘是1 else: return n * factorial(n - 1) if __name__ == '__main__': result=factorial(n) print("{}的階乘為:{}".format(n,result))
3、用戶輸入考試成績,當分數(shù)高于90(包含90)時打印A;否則如果分數(shù)高于80(包含80)時打印B;否則如果當分數(shù)高于70(包含)時打印C;否則如果當分數(shù)高于60(包含60)時打印D;其他情況就打印E。
try: score=float(input('請輸入考試成績:')) if score>=90: print('A') elif 80<=score<90: print('B') elif 70<=score<80: print('C') elif 60<=score<70: print('D') else: print('E') except Exception as e: print('您輸入有誤!')
4、假設一年的定期利率為3.52%,需要幾年才能讓定期存款連本帶息的翻一番(例如:需要多少年10000才能變成20000)?
save_money = float(input("請輸入你要存入銀行的錢:")) print("你存了{}元到銀行".format(save_money)) total_money = save_money * 2 # 定義變量用于保存總錢數(shù) year = 1 # 定義變量用于記錄年份 while save_money < total_money: save_money *= (1 + 0.0352) year += 1 print("定期利率為3.52%,需要{}年本金和利息才能翻一番!".format(year))
5、將列表a =["I","T","e","s","t","e","r"]拼接成字符串,請用多種方法實現(xiàn)。
# 方法一 字符串函數(shù)調(diào)用 a = ["I","T","e","s","t","e","r"] print("".join(a)) #方法二 for循環(huán) a = ["I","T","e","s","t","e","r"] s = "" for item in a: s += item print(s)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
NumPy.npy與pandas DataFrame的實例講解
今天小編就為大家分享一篇NumPy.npy與pandas DataFrame的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07pytorch實現(xiàn)mnist手寫彩色數(shù)字識別
這篇文章主要介紹了pytorch-實現(xiàn)mnist手寫彩色數(shù)字識別,文章圍繞主題展開詳細的內(nèi)容姐介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09