阿爾法python練習(4-7答案)

4.基本數據類型

判斷奇偶數

# 請使用 input() 輸入一個整數 num
num=int(input("請輸入一個整數"))


# 請判斷這個數是奇數還是偶數
if num%2==0:
    print("even")
else:
    print("odd")

公倍數

# 請使用 input() 輸入一個正整數 num

num=int(input())
# 請判斷這個正整數是否是 5 和 7 的公倍數
if num%5==0 and num%7==0:
    print("yes")
else:
    print("no")

判斷平閏年

# 請使用 input() 輸入一個年份 year
year=int(input())

# 請判斷這個年份是否爲閏年
if (year%4==0) and (year%100!=0) or (year%400==0):
    print("leap year")
else:
    print("common year")

天天向上的力量第一問

dayup=pow(1.001,365)
daydown=pow(0.999,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))

天天向上的力量第二問

dayfactor=0.005
dayup=pow(1+dayfactor,365)
daydown=pow(1-dayfactor,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))

天天向上的力量第三問

dayup=1.0
dayfactor=0.01
for i in range(365):
    if i%7 in[6,0]:
        dayup=dayup*(1-dayfactor)
    else:
        dayup=dayup*(1+dayfactor)

天天向上的力量第四問

def dayUP(df):
    dayup=1
    for i in range(365):
        if i%7 in [6,0]:
            dayup=dayup*(1-0.01)
        else:
            dayup=dayup*(1+df)
    return dayup

dayfactor=0.01
while dayUP(dayfactor)<37.78:
    dayfactor+=0.001
print("工作日的努力參數是:{:.3f}".format(dayfactor))

拼接最大字符

# 請使用 input() 輸入兩個字符串 string1, string2
string1=input()
string2=input()
# 請分別比較兩個字符串中的每一個字符,將大的字符拼接成一個新的字符串,並輸出
str1=list(string1)
str2=list(string2)
str=""
for i in range(len(string1)):
    if str1[i]>=str2[i]:
        str=str+str1[i]
    else:
        str=str+str2[i]
print(str)

刪除字符

string = 'abcdefghijklmnopqrstuvwxyz'

# 請使用 input() 輸入索引 begin 和長度 length

begin=int(input())
length=int(input())

str1=list(string)
del str1[begin:begin+length]
for i in  range(len(str1)):
    print(str1[i],end="")

# 請將字符串 string 中,從索引 begin 開始,長爲 length 的字符串刪除,並將剩下的字符串內容輸出

插入字符

s = 'abcdefghijklmnopqrstuvwxyz'

sub=input()
pos=int(input())
str1=list(s)
str1.insert(pos,sub)
for i in range(len(str1)):
    print(str1[i],end="")

迴文字符串

s=input()
s1=list(s)
s1.reverse()
s2=list(s)
if s1==s2:
    print("yes")
else:
    print("no")

統計詞量

# 請使用 input() 輸入一斷文本 text

def word_len(text):
    return len([i for i in text.split(' ') if i])
def main():
    text=str(input("請輸入字符串: "))
    len=word_len(text)
    print(len)
main()
# 請統計這段文本中的單詞數量,並將統計結果輸出

你中無我

s1=input()
s2=input()
for i in s1:
    if i not in s2:
        print(i,end="")

時間格式化

import time
t=time.gmtime()
time.strftime("%Y-%M-%D %H:%M:%S",t)


文本進度條


import time
scale=50
print("執行開始".center(scale//2,"-"))
start=time.perf_counter()
for i in range(scale+1):
    a="*"*i
    b="-"*(scale-i)
    c=(i/scale)*100
    dur=time.perf_counter()-start
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end="")
    time.sleep(0.1)
print("\n"+"執行結束".center(scale//2,'-'))

5.程序的控制結構

大小寫轉換

# 請使用 input() 輸入一個英文字母 char
char=input("輸入一個英文字母")
if ord(char)>=ord('A') and ord(char)<=ord('Z'):
    print(chr(ord(char)+32))
else:
    print(chr(ord(char)-32))

# 請實現英文字母的大小寫轉化

判斷位數並打印各位的值

num=str(input("輸入一個數字"))
lens=len(num)
if len(num)==1:
    print("一")
elif len(num)==2:
    print("二")
elif len(num)==3:
    print("三")
elif len(num) == 4:
    print("四")
elif len(num) == 5:
    print("五")
i=0
while i<len(num):
    print(num[i],end=" ")
    i+=1

地鐵車票

# 請使用 input() 輸入乘坐的人數 per_num 和站數 sta_num


# 請判斷輸入的人數和站數是否正確,計算購買車票的總金額,並將計算結果輸出
per_num=int(input("乘坐的人數"))
sta_num=int(input("站數"))
if per_num<=0 or sta_num<=0:
    print("error")
elif sta_num<=4 and sta_num>=1:
    print(per_num*3)
elif sta_num <= 9 and sta_num >= 5:
    print(per_num*4)
elif sta_num >= 9:
    print(per_num*5)

考試評級

# 請使用 input() 輸入考試成績 score
score = int(input('請輸入考試成績: '))

# 請判斷成績屬於哪個級別
if 0<=score<=59:
    print('E')
elif 60<=score<=69:
    print('D')
elif 70<=score<=79:
    print('C')
elif 80<=score<=89:
    print('B')
elif 90<=score<=100:
    print('A')

判斷星期

# 請使用 input() 輸入單詞的前兩個字母 chars
chars = input()

# 請判斷輸入的是星期幾,並輸出對應的單詞
if chars=='mo':
    print("monday")
elif chars=='tu':
    print("tuesday")
elif chars=='we':
    print("wednesday")
elif chars=='th':
    print("thursday")
elif chars=='fr':
    print("friday")
elif chars=='sa':
    print("saturday")
elif chars=='su':
    print("sunday")
else:
    print("error")

身體質量指數BMI

height = float(input())
weight = float(input())
BMI=weight/pow(height,2)

print(f"BMI數值爲:{BMI:.2f}")
A='s'
B='s'
if BMI<18.5:
    A=B='偏瘦'
elif 18.5<=BMI<25:
    A='正常'
elif 25<=BMI<30:
    A='偏胖'
elif BMI>=30:
    A='肥胖'
if 18.5<=BMI<24:
    B='正常'
elif 24<=BMI<28:
    B='偏胖'
elif BMI>=28:
    B='肥胖'
print(f"BMI指標爲:國際'{A}',國內'{B}'")

階乘

# 請使用 input() 輸入一個正整數 num

num=int(input())
i=1
res=1
while i<=num:
    res*=i
    i+=1
print(res)
# 請計算這個正整數的階乘,並將計算結果輸出

水仙花數

# 請使用 input() 輸入一個三位數 num
num = int(input('請輸入一個三位數: '))

# 請找出 100 - num(含) 中的所有水仙花數,並將找出的水仙花數輸出
s=100
while s<=num:
    ge=s%10
    shi=s//10%10
    bai=s//100
    if pow(ge,3)+pow(shi,3)+pow(bai,3)==s:
        print(s)
    s+=1

猴子摘桃

# 請使用 input() 輸入一個天數 day
day = int(input('請輸入一個天數: '))

# 請計算第 day 天猴子摘的桃子個數,並將結果輸出
i=2
res=2
while i<=day:
    res=2*res+1
    i+=1
print(res)

素數

# 請使用 input() 輸入一個整數 num
num = int(input('請輸入一個整數: '))

for i in range(2,num+1):
    fg=0
    for j in range(2,i-1):
        if i%j==0:
            fg=1
            break

    if fg==0:
        print(i)
# 輸出 1 - num(含) 中的所有的素數

隨機密碼生成

import  random
import string
a=string.octdigits
key=[]

def genpwd(length):
    key=random.sample(a,length)
    keys="".join(key)
    return keys

length=eval(input())
random.seed(17)
for i in range(3):
    print(genpwd(length))

圓周率的計算

#調用random函數,並且使用了perf_counter這個函數,是可以用來計時的一部分
from random import random
from time import perf_counter
#定義變量,當作拋灑點的總數量
DARTS = 1000 * 1000
#撒在圓內部點爲0
hits = 0.0
start = perf_counter()
for i in range(1,DARTS+1):
    x,y = random(),random()
    dist = pow(x ** 2 + y ** 2,0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits / DARTS)
print("圓周率值是:{}".format(pi))
print("運行時間是:{:.5f}s".format(perf_counter() - start))

求pi的近似值

e = float(input())

# 請根據 e 計算 pi 的近似值
x=-1
n=2
result=1
while(1/(2*n-3)>=e):
    result = result+x*(1/(2*n-1))
    x=x*(-1)
    n=n+1
count=4*result
print(count)

籃球彈跳

# 請使用 input() 輸入彈跳的次數 num
num=int(input("請輸入彈跳的次數: "))
result=10
for i in range(0,num):
    result=result/2
print(result)
# 請計算彈跳 num 次後的籃球高度,並將結果輸出

猜數字

# 導入random模塊
import random

# 生成隨機數,並賦值給num變量
num = random.randint(1, 100)

# 定義 guess_chances 變量,初始化猜的次數
guess_chances = 7
print('您只有7次猜數字的機會哦!')

# 循環輸入的次數
for i in range(1, guess_chances + 1):
    print('這是第' + str(i) + '次猜數字')

    # 實現對輸入數字的判斷

6.函數和代碼複用

打招呼函數

"""
練習:打招呼函數
要求:
1. 定義函數 say_hello
2. 有 1 個參數 name 表示要給誰打招呼
3. 實現函數功能,即在控制檯打印:`你好,<name>,認識你很高興!`(注:name 是函數的參數)
"""
def say_hello(name):
    print(f"你好,{name},認識你很高興!")
name="Jack"

say_hello(name)

能否組成三角形

"""
編寫 is_triangle 函數,此函數有 3 個參數,分別爲3個數字,
判斷這3個數字所代表的邊長能否組成一個三角形
"""

def is_triangle(a, b, c):
    if a<=0 or b<=0 or c<=0:
        return -1
    if a+b>c and a+c>b and b+c>a and a-b<c and a-c<b and b-c<a:
        return 1
    else:
        return 0
a=3
b=4
c=5
print(is_triangle(a,b,c))

轉換秒爲時間

# 定義一個 convert_from_seconds 函數, 參數 seconds, 返回表示時間的列表
def convert_from_seconds(seconds):
    a=seconds//86400
    b=seconds%86400//3600
    c=seconds%3600//60
    d=seconds%60
    list=[]
    list.append(a)
    list.append(b)
    list.append(c)
    list.append(d)
    return list

最大公約數

# 定義並實現函數 common_divisor

def common_divisor(num1,num2):
    if num1>num2:
        smaller=num2
    else:
        smaller=num1

    for i in  range(1,smaller+1):
        if((num1%i==0) and (num2%i)==0):
            res=i
    return res


# 調用函數
result = common_divisor(24, 16)
print(result)

簡單計算器實現

# 加法函數
def addition(num1, num2):
    return num2+num1

# 減法函數
def subtraction(num1, num2):
    return num1-num2

# 乘法函數
def multiplication(num1, num2):
    return num1*num2

# 除法函數
def division(num1, num2):
    return num1/num2

楊輝三角

# 定義函數 pascal_triangle 接受參數 num,並返回楊輝三角第 num 行
def pascal_triangle(num):
    # j行的數據, 應該由j - 1行的數據計算出來.
    # 假設j - 1行爲[1,3,3,1], 那麼我們前面插入一個0(j行的數據會比j-1行多一個),
    # 然後執行相加[0+1,1+3,3+3,3+1,1] = [1,4,6,4,1], 最後一個1保留即可.
    r=[1]
    for i in range(1,num):
        r.insert(0,0)
        # 因爲i行的數據長度爲i+1, 所以j+1不會越界, 並且最後一個1不會被修改.
        for j in range(i):
            r[j]=r[j]+r[j+1]
    return r

print(pascal_triangle(3))

七段數碼管繪製

#七段數碼管的繪製
import turtle as t
import time
def drawgap():
    t.pu()
    t.fd(5)
def drawline(draw):#繪製單段數碼管
    t.pendown() if draw else t.penup()
    t.fd(40)
    drawgap()
    t.right(90)
def drawdigit(digit):#根據數值繪製七段數碼管
    drawline(True) if digit in [2,3,4,5,6,8,9] else drawline(False)
    drawline(True) if digit in [0,1,3,4,5,6,7,8,9] else drawline(False)
    drawline(True) if digit in [0,2,3,5,6,8,9] else drawline(False)
    drawline(True) if digit in [0,2,6,8] else drawline(False)
    t.left(90)
    drawline(True) if digit in [0,4,5,6,8,9] else drawline(False)
    drawline(True) if digit in [0,2,3,5,6,7,8,9] else drawline(False)

    drawline(True) if digit in [0,1,2,3,4,7,8,9] else drawline(False)
    t.left(180)
    t.pu()#爲繪製後續數字確定位置
    t.fd(20)#爲繪製後續數字確定位置
def drawdate(date):#獲取日期
    t.pencolor("green")
    for i in date:
        if i == '年':
            t.write('年',font = ("Arial",18,"normal"))
            t.pencolor("blue")
            t.fd(40)
        elif i == "月":
            t.write('月',font = ("Arial",18,"normal"))
            t.pencolor("yellow")
            t.fd(40)
        elif i == "日":
            t.write('日',font = ("Arial",18,"normal"))
            t.pencolor("red")
        else:
            drawdigit(eval(i))#通過eval()將數字變成整數
def main(date):
    t.setup(1500,650,20,20)
    t.pu()
    t.fd(-600)
    t.pensize(5)
    drawdate(time.strftime("%Y年%m月%d日",time.gmtime()))
    t.fd(40)
    t.color("red")
    drawdate(date)
    t.hideturtle()
    t.done()
main(input("請輸入一個年月日,例:2019年01月22日:\n"))

斐波那契數列計算

# 定義一個 fbi 函數,參數 num,返回斐波那契數列第 num 項的值。

def fbi(num):
    list=[1,1,""]
    for i in range(2,num):
        list[i]=list[i-1]+list[i-2]
        list.append(list[i])
    return list[num]
print(fbi(4))

漢諾塔實踐

# 請在...補充一行或多行代碼
count = 0

def hanoi (n, src, dst, mid):
    global count
    if n == 1:
        print("{}: {}->{}".format(1, src, dst))
        count += 1
    else:
        #先把最上面的所有盤src->mid,移動過程用到dst
        hanoi(n-1,src,mid,dst)
        #把最下面的盤src->dst
        print("{}: {}->{}".format(n, src, dst))
      #  print(f"第{n}個盤從{src}-->{dst}")
        #把mid塔的所有盤從mid-->dst,移動過程使用到a
        hanoi(n-1,mid,dst,src)

hanoi(3, "A", "C", "B")
print(count)

科赫雪花小包裹

# 請在...補充一行或多行代碼

import turtle


def koch(size, n):
    if n==0:
        turtle.fd(size)
    else:
        for angle in [0,60,-120,60]:
            turtle.left(angle)
            koch(size/3,n-1)



def main(level):
    turtle.setup(600, 600)
    turtle.penup()
    turtle.goto(-200, 100)
    turtle.pendown()
    turtle.pensize(2)
    #level=2
    koch(400,level)
    turtle.right(120)
    koch(400,level)
    turtle.right(120)
    koch(400,level)
    turtle.hideturtle()


try:
    level = eval(input("請輸入科赫曲線的階: "))
    main(level)
except:
    print("輸入錯誤")

合法的用戶名


"""
實現 check_username 函數,檢查 username 是否有效
username 長度在 6-18 位之間,返回 True,否則返回 False
"""
def check_username(username):
    length=len(username)
    if 6<=length<=18:
        return True
    else:return False

user=input()
print(check_username(user))

密碼的強度

"""
實現密碼強度計算函數:
1. 實現函數 passworld_strength 返回 0-10 的數值,表示強度,數值越高,密碼強度越強
2. 密碼長度在 6 位及以上,強度 +1,
   在 8 位及以上,強度 +2,
   在 12 位及以上,強度 +4
3. 有大寫字母,強度 +2
4. 除字母外,還包含數字,強度 +2
5. 有除字母、數字以外字符,強度 +2
"""
import string

#string.ascii_uppercase所有大寫字母

#string.ascii_lowercase所有小寫字母

#string.ascii_letters所有字母

#string.digits所有數字


def password_strength(pwd):
    strong=0
    length=len(pwd)
    if length>=12:
        strong+=4
    elif length>=8:
        strong+=2
    elif length>=6:
        strong+=1
    flag1=False
    for i in pwd:
        if i in string.ascii_uppercase:
            strong+=2
            break
    for i in pwd:
        if i in string.ascii_letters:
            flag1=True
            break
    flag2=False
    for i in pwd:
        if i in string.digits and flag1:
            strong+=2
            flag2=True
            break
    for i in pwd:
        if i not in string.digits and i not in string.ascii_letters and flag2:
            strong+=2
            break
    return strong
password=input()
print(password_strength(password))

藏頭詩

poem1 = [
    "蘆花叢中一扁舟",
    "俊傑俄從此地遊",
    "義士若能知此理",
    "反躬難逃可無憂"
]

poem2 = [
    "我畫藍江水悠悠",
    "愛晚亭上楓葉愁",
    "秋月溶溶照佛寺",
    "香菸嫋嫋繞經樓"
]


def acrostic(poem):
    newstr=[]
    for i in range(len(poem)):
        str1=poem[i]
        rstr=list(str1)
        newstr.append(rstr[0])
        str1=""
    newstr1=''.join(newstr)
    return newstr1


print(acrostic(poem1))
print(acrostic(poem2))


統計字符出現次數

"""
統計字符串 string 中出現字符 char 的次數,並返回;
char 是長度爲 1 的字符串。
"""
def sum_char(string, char):
    str1=list(string)
    count=0
    for i in range(len(string)):
        if str1[i] == char:
            count+=1
    return count
str2=str(input())
char1=str(input())
print(sum_char(str2, char1))

文件擴展名

"""
獲取文件擴展名
說明:實現 file_ext 函數,該函數接受一個表示文件名的字符串參數 filename,返回它的擴展名
"""
def file_ext(filename):
    str1=list(filename)
    for i in range(len(filename)):
        if str1[i]!=".":
            continue
        elif str1[i]==".":
            str2=str1[i+1:]
            str3=''.join(str2)
            return str3
            break
        else:
            return "error"
            
    
filename1=input()
print(file_ext(filename1))
    

7.組合數據類型

創建水果列表

fruits = []
fruits.append("蘋果")
fruits.append("草莓")
fruits.append("香蕉")
fruits.append("梨")
fruits.append("百香果")

刪除水果

fruits = ['蘋果', '草莓', '香蕉', '梨', '百香果']
fruits.remove(fruits[1])
fruits.remove(fruits[3])

添加水果

fruits = ['蘋果', '香蕉', '梨']
fruits.append("西瓜")
fruits.append("葡萄")

計算總分和平均分

# 小明的期末考試成績分數如下:
scores = [95, 69, 98, 74, 64, 72, 53, 92, 83]

# 請計算小明的總分、平均分,並保存至變量 total_score, avg_score 中
total_score=0
avg_score=0
for i in range(len(scores)):
    total_score+=scores[i]
print(total_score)
avg_score=total_score/len(scores)
print(avg_score)

添加用戶

users = {
    "alpha": "alpha123",
    "beta": "betaisverygood",
    "gamma": "1919191923",
    "zhangsan":"zs123456",
    "lisi":"si123456"
}

模擬用戶登錄

users = {
    "alpha": "alpha123",
    "beta": "betaisverygood",
    "gamma": "1919191923",
    "zhangsan": "123456",
    "lisi": "123456",
    "admin": "ADMIN",
    "root": "Root123"
}

username = input()
password = input()

# 請在下面編寫代碼,判斷輸入的用戶名或密碼是否正確
if username not  in users.keys():
    print("not found")
elif username in users.keys() and users.get(username)==password:
    print("success")
else:print("password error")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章