日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python基礎(chǔ)

系統(tǒng) 1678 0

?此篇博客為自己開始學(xué)Python語言一邊學(xué)習(xí)一邊記錄自己所學(xué)的程序所創(chuàng)(一邊學(xué)習(xí)一邊更新)

所有程序皆為使用Pycharm的Python3.0的程序

Hello Wrold小程序

            
              print('Hello wrold!')
            
          

數(shù)字游戲

            
              import random
print('猜猜我現(xiàn)在心里想的數(shù)字是那個?')
result = random.randint(0, 20)
while True:
    # 下面兩個語句用于顯示自己產(chǎn)生的隨機(jī)數(shù)
    # print('生成的數(shù)字是')
    # print(result)
    a = int(input('請輸入你猜的數(shù)字:\n'))
    if a == result:
        print('你猜對了')
        print('但是沒有獎勵哦')
        break
    else:
        print('你猜錯了哈哈哈')


            
          

基本的數(shù)學(xué)運算符

            
              # 基本的數(shù)學(xué)運算符程序
print('9 + 3\t\t= ',9+3)
print('9 - 3\t\t= ',9-3)
print('9 * 3\t\t= ',9*3)
print('9 // 4\t\t = ',9//4)  # 真除法
print('9 / 4\t\t = ',9/4)    # 取整除法
print('9 % 3\t\t= ',9%3)
print('9 ** 3\t\t= ',9**3)
print('(2+3) * 2 \t\t= ',(2+3)*2)
# 字符串的乘法
print('\'-\' * 10\t= ','*'*10)

            
          

小數(shù)的格式

            
              from fractions import Fraction
# 格式如下
# 前一位數(shù)是分子,后一位書是分母
y = Fraction(2,4)
# 自動約分
print("2/4 =",y)
            
          

基本輸入格式?

            
              input('Please enter an integer:')
print('Please enter an other integer')
integer1 = int(input('integer1 = '))
print('The integer of that you entered is ',integer1)
str1 = input('Please enter an str\nstr1 = ')
print('The string of you entered is ','\'',str1,'\'')
float1 = float(input('Please enter a floating-point number: '))
print('The floating-point number you entered is ',float1)
            
          

買蘋果程序

            
              # 先輸入字符串變量
price_str = input('Please enter the price of Apple/kg:')
weight_str = input('Please enter the weight of Apple/kg:')
# 將字符串轉(zhuǎn)換為浮點數(shù)類型
price = float(price_str)
weight = float(weight_str)
money = price * weight
# 格式化輸出
print('Apple %.1f per kilogram and you want to buy %.1f kilograms apple, you need to pay for %.1f RMB.'%(price, weight, money))
            
          

格式化

            
              # string's format
name = 'Xiaoming'
print('Name is %s'%name)
# floatint-point number's format
float1 = float(input('請輸入一個數(shù)字:'))
print('The number of you entered is %02.1f' % float1)
# Percent's format
scale = 0.25
print('%.2f%%' % scale * 100)
            
          

導(dǎo)入包(import體驗)

            
              import keyword
print(keyword.kwlist)
            
          

猜拳游戲(選擇結(jié)構(gòu))

            
              import random
# 石頭 1 剪刀 2 布 3
print('這是一個猜拳游戲,石頭(1) 剪刀(2) 布(3)')
player = int(input('請輸入你要出的拳:\t '))
computer = random.randint(1,3)
print('電腦出的拳是:\t\t',computer)
# 比較勝負(fù)
if player == computer:
     print('雙方平局')
elif (computer-player == 1 or (computer == 3 and player == 1)):
    print('玩家勝利')
else:
    print('電腦勝利')

            
          

循環(huán)結(jié)構(gòu):

while

            
              i = 0
while i < 5:
    print('Hello Python')
    i=i+1
            
          

死循環(huán)

            
              i = 0
while i < 5:
    print('Hello Python')
    # i=i+1
            
          

0 - 100求和

            
              i = 0
Sum = 0
while i <= 100:
    Sum += i
    i = i+1
print('The sum from 0 to 100 is',Sum)
            
          

0-100偶數(shù)求和(if 和 while的嵌套)

            
              # 偶數(shù)求和
i = 0
Sum = 0
while i <= 100:
    if i%2==0:
        Sum += i
    i = i+1
print('The sum of even number from 0 to 100 is',Sum)
            
          

兩種方式實現(xiàn)打印小星星(循環(huán)嵌套初體驗)

            
              # 打印小星星

# 利用循環(huán)嵌套實現(xiàn)
# rows = 1
# while rows <= 4:
#     num = 0
#     while num < rows:
#         # 輸出一行不會換行
#         print('*',end='')
#         num += 1
#     # 此處再實現(xiàn)換行操作
#     print('')
#     rows += 1

# 利用字符串的乘法實現(xiàn)
rows = 0
while rows < 5:
    print('*'*(rows+1))
    rows += 1
            
          

循環(huán)嵌套實現(xiàn)99乘法表

            
              # 利用循環(huán)嵌套實現(xiàn)99乘法表
rows = 1
cols = 1
while rows <= 9:
    cols = 1
    while cols <= rows:
        # 不換行,普通方法
        # print(cols,end=' * ')
        # print(rows,end=' = ')
        # print(rows*cols,end='\t')
        # 格式化的方法
        print('%d * %d = %d\t'%(cols,rows,cols*rows),end='')
        cols += 1
    print('')
    rows += 1
            
          

使用range自帶函數(shù)實現(xiàn)99乘法表

            
              for i in range(1,10):
    for j in range(1,i+1):
        print("%sx%s=%s" % (j,i,j*i),end="\t")
    print()
            
          

小小程序(純屬自娛自樂)

            
              print("你想對誰說一句話,請留下Ta的名字:")
a=input()
print(a)
print("接下來請輸入你想說的一句話:")
b=input()
print("你想說的話是"+b)
print("那么接下來就是見證奇跡的時刻了")
print(a+"你知道嗎,有一句話藏在我心里很久了,今天我必須要說給你聽,那就是"+b+"\n")
            
          

函數(shù)的嵌套調(diào)用

            
              # The first function
def text1():
    print('Hello World1!')
    print('Hello World2!')

# The second function
def text2():
    text1()
    print('Hello World3!')

# Nested Function
text2()
            
          

List

            
              name_list=["張三","李四"]
print(name_list)
for s in name_list:
    print(s)
print(name_list[1])
            
          
              
                # list.sort()?? # 升序排序
# list.sort(reverse=True)? # 降序排序
# list.clear()? # 清除數(shù)據(jù)
# list.pop(x)?? # 彈出第x個元素,無參數(shù)則默認(rèn)最后一個元素彈出
# list.count(數(shù)據(jù))? # 返回數(shù)據(jù)出現(xiàn)的次數(shù)
# list.index(數(shù)據(jù))??? # 獲取數(shù)據(jù)第一次出現(xiàn)的索引(即下標(biāo))
# list.remove(數(shù)據(jù))?? # 刪除第一個出現(xiàn)的指定數(shù)據(jù)
# list.append(數(shù)據(jù))? # 末尾追加
# list.insert(self,index,object)? # index后面插入一個對象
# list.extend(self,iterable)? # 在當(dāng)前列表的末尾插入一個新的列表
# del list[index]? # 從內(nèi)存中刪除數(shù)據(jù)
# list.reverse()? # 列表的翻轉(zhuǎn)(逆序)
              
            

元組 (tuple)

            
              info_tuple=('許嵩',18,1.80)
# print(type(info_tuple))
print(info_tuple[0])
# The init of empty tuple
empty_tuple=()
#  single tuple
single_tuple=(5)
print(type(single_tuple))
# 以上類型為 int類型

# # single tuple
# # plus ','
# single_tuple=(5,)
# print(type(single_tuple))
# # The above type is tuple

# methods
# be like to list
# tuple.count()
# tuple.index()
            
          

格式化輸出元組

            
              name=('許嵩',18,1.80)
print('%s,aged %d, %.2f high' %name)
# List to tuple and Tuple to list
# tuple(list)
# list(tuple)
            
          

字典的學(xué)習(xí)

            
              # 字典中的鍵集合
# dictionary.keys()
# 值集合
# dictionary.values()
# 所有鍵值元組列表
# Items()

# Key:Value(key must be only)
# 鍵值對之間用 , 分隔
# 列表是有序的對象集合
# 字典是無序的對象集合

xiaoming = {
    'name':'小明',
    'age':'18',
    #'gender':True,
    'height':'1.75',
    'weight':'50'
}

# 1.統(tǒng)計鍵值對的數(shù)目
print(len(xiaoming))

# 2.合并字典
temp_dic={
    '愛好':"睡覺",
    '喜歡':'玩'
          }
# 如果有同樣的鍵,那么會覆蓋原來字典里面的鍵的值
xiaoming.update(temp_dic)

# 3.clear()清空所有的鍵值對
# xiaoming.clear()

# 4.for 遍歷輸出
# k為鍵
for k in xiaoming:
    print('%s-%s\n'%(k,xiaoming[k]))

# # 1.取值
# print(xiaoming['age'])

# # 2.增加/修改
# xiaoming['age'] = 19

# # 3.刪除
# xiaoming.pop('age')

print(xiaoming)
            
          

字典和列表的串用

            
              # 使用鍵值對,存儲描述一個物體的相關(guān)信息
# 將 多個字典 放在一個列表里面,再進(jìn)行遍歷
card_list=[
    {'name':'I love Vae',
     'qq':'10128513777',
     'phone':'123123123'
     },
    {'name':'lisi',
     'qq':'26731595557',
     'phone':'12343556787'
     }
]
for k in card_list:
    print(k)
            
          

字符串

            
              str1 = "Hello Python"

str2 = 'My favourite singer is "Vae"'

length = str1.__len__()

print(length)

print(str1)

print(str2)

for char in str2:
    print(char)
# methods
# len(str)      calculate length of str
# count(data)   calculate the times of the data

# if use index if the Substring isn't exist,there will be error
# index(data) return index of the data

str_boy="Gou yi Zhou"
length_girl=str_boy.__len__()

for s in str_boy:
    print(s)
            
          

判斷數(shù)字的方法

            
              # Jude space
str_space = "     \t\n\r"

print(str_space)

# Jude digit
# But can't use in float-point number
# str_num = "1"
str_num = "\u00b2"
print(str_num)

print(str_num.isdecimal())  # 純數(shù)字
print(str_num.isdigit())    # 數(shù)字加Unicode編碼
print(str_num.isnumeric())  # 數(shù)字加Unicode加中文數(shù)字
            
          

字符串的方法

            
              str_1 = "Hello world!"

# 1.string.startswith(str)  check the string's start
print(str_1.startswith("He"))

# 2.string.endswith(str)  check the string's end
print(str_1.endswith("ld!"))

# 3.string.find("str")  find "str" in string
# if "str" not here this function will return -1
# return str's index
print(str_1.find("llo"))

print(str_1.find("abd"))

# 4.replace string
# return another string but can't change the old string
print(str_1.replace("world","python"))
print(str_1)
            
          

文本的格式化輸出

            
              # Example:The lecture from internet
# Demand :Order output and center the output of the following
poem = ["登鸛雀樓",
        "王之渙",
        "白日依山盡",
        "黃河入海流",
        "欲窮千里目",
        "更上一層樓"
        ]
for poem_str in poem:
    print("|%s|" % poem_str.center(10))

for poem_str in poem:
    print("|%s|" % poem_str.ljust(10))

for poem_str in poem:
    print("|%s|" % poem_str.rjust(10))

            
          

?去除空白字符

            
              # str_1 = "\t\nHello \t\n\tWorld!"
# Example:The lecture from internet
# Demand :Order output and center the output of the following
poem = ["\t\t\n\n登鸛雀樓\t\t",
        "王之渙\n\n",
        "白日依山盡",
        "黃河入海流",
        "欲窮千里目",
        "更上一層樓"
        ]
for poem_str in poem:
    print("|%s|" % poem_str.strip.center(10))

for poem_str in poem:
    print("|%s|" % poem_str.ljust(10))

for poem_str in poem:
    print("|%s|" % poem_str.rjust(10))



            
          

?字符串的拆分和拼接

            
              poem = "登鸛雀樓\t 王之渙\t 白日依山盡\t 黃河入海流\t 欲窮千里目\n\t更上一層樓\n\t"

# 1.去掉所有空白字符
# 2.將字符串連接為一個大的字符串

print(poem)

# 1.拆分字符串
# 大字符串拆分為多個列表
poem_list=poem.split()
print(poem_list)
 
# 2.拼接
result = " ".join(poem_list)  # 接受列表返回以惡搞字符串
print(result)
            
          

字符串的切片

            
              # 字符串[開始索引:結(jié)束索引:步長]  # 用于間隔切片
# 順序和倒敘索引從右到左是 -1
# 想要獲取最后的字符 則結(jié)束索引為0
num_str = "0123456789"

print("截取2-6索引的字符串")
num_str_1 = num_str[2:6]
print(num_str_1,'\n')

print("截取2到末尾索引的字符串")
num_str_1 = num_str[2:]
print(num_str_1,'\n')

print("截取0-6索引的字符串")
num_str_1 = num_str[0:6]
print(num_str_1,'\n')

print("截取0-6索引的字符串")
num_str_1 = num_str[:6]
print(num_str_1,'\n')

print("截取全部的字符串")
num_str_1 = num_str[:]
print(num_str_1,'\n')

print("截取全部的字符串,2為步長")
num_str_1=num_str[::2]
print(num_str_1,'\n')

print("截取從索引1開始的字符串,2為步長")
num_str_1=num_str[1::2]
print(num_str_1,'\n')

print("取最后的那個字符")
num_str_1=num_str[-1]
print(num_str_1,'\n')

print("截取從2索引開始的字符串,到倒數(shù)第二個字符為止")
num_str_1=num_str[2:-1]
print(num_str_1,'\n')

print("截取從右向左第二個開始的字符串,到該字符串的最后端")
num_str_1=num_str[-2:]
print(num_str_1,'\n')

print("截取從頭開始的字符串,-1為步長")
num_str_1=num_str[0::-1]
print(num_str_1,'\n')

print("截取全部的字符串,-1為步長,即從右向左截取")  # 即逆序
num_str_1=num_str[::-1]
print(num_str_1,'\n')
            
          

公共方法

            
              # max
# len
# del
# min
# slice 切片
# 字典無法進(jìn)行切片
str = "abcdefg"
print(str)

print(len(str),"\n")

print(max(str),"\n")

print(min(str),"\n")

list_1 = [1,2,3,4,5,6]
list_1[1::2]
print(list_1[1::2])
            
          
            
              # 列表的乘法
list_1 = [1,2]
list_1 = list_1*2
print(list_1)

# 字典同樣無法做乘法

list_1 = [1,2]
list_1+=[3,4]
# 使用+號后會生成一個新的列表
# 而字符串的append(追加元素),extend(追加列表)函數(shù)則會把內(nèi)容整合到原來的那個列表里去
print(list_1)

            
          

名片管理系統(tǒng)

主程序

            
              import cards_tool

#  功能實現(xiàn)
# 1.歡迎界面
# 2.功能

while True:

    cards_tool.show_menu()
    a = input("請輸入你要選擇的功能:")
    print("你輸入的操作代碼是:", a)
    if a in ["1", "2", "3"]:

        #   新增名片
        if a=="1":
            cards_tool.new_card()
        #   pass
        #   顯示全部
        elif a =="2":
            cards_tool.show_all()
        #   pass
        #   查詢名片
        elif a=="3":
            cards_tool.search_card()
        #   pass
        #   pass僅僅是個占位符,保證程序的正確
        #   pass
        #   如果輸入0則退出系統(tǒng)
    elif a == "0":
        print("歡迎再次使用【名片管理系統(tǒng)】")
        break
        #   pass關(guān)鍵字不會執(zhí)行任何的操作
        #   pass
        #   輸入的內(nèi)容錯誤,讓用戶重新選擇
    else:
        print("您輸入的格式不正確,請重新輸入!")
            
          

工具程序

            
              def show_menu():
    """顯示菜單"""
    print("*" * 50)
    print("歡迎使用名片管理系統(tǒng) V1.0")
    print("")
    print("1.新增名片")
    print("2.顯示全部")
    print("3.搜索名片")
    print("")
    print("0.退出系統(tǒng)")
    print("*" * 50)


#   使用字典的特性來保存一個物體的全部信息
card_list = []


def new_card():
    '''新增名片'''
    print("-" * 50)
    print("\t\t新增名片")
    print("-" * 50)

    # 1. 提示用戶輸入名片的詳細(xì)信息
    name_str = input("請輸入姓名:")
    phone_str = input("請輸入電話:")
    qq_str = input("請輸入QQ:")
    email_str = input("請輸入郵箱:")
    # 2. 使用用戶輸入的信息來建立一個名片字典
    card_temp = {"name": name_str,
                 "phone": phone_str,
                 "qq": qq_str,
                 "email": email_str
                 }
    # 3. 將名片字典添加到列表中
    card_list.append(card_temp)

    # print(card_list) 調(diào)試語句 可忽略
    # 4.
    print("添加 %s 的名片成功" % name_str)


def show_all():
    """顯示所有的名片"""
    print("-" * 50)
    print("\t\t顯示所有的名片")
    print("-" * 50)
    # 判斷是否有名片記錄
    if len(card_list) == 0:
        print("沒有名片記錄,請使用新建功能添加")

        # return 可以返回一個函數(shù)的執(zhí)行結(jié)果
        # return 下方的代碼不會被執(zhí)行
        # 返回到調(diào)用函數(shù)的位置去
        # 不返回任何的結(jié)果
        return
    # 打印表頭
    for name in ["姓名", "電話", "qq", "郵箱"]:
        print(name, end="\t\t\t")
    print()
    print("=" * 50)
    for card_temp in card_list:
        print("%s\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t" % (
        card_temp["name"], card_temp["phone"], card_temp["qq"], card_temp["email"]))

    print("=" * 50)


def search_card():
    """搜索名片"""
    print("-" * 50)
    print("\t\t搜索名片")
    print("-" * 50)
    # 1. 提示用戶輸入要搜索的姓名
    find_name = input("請輸入要搜索的姓名:")

    # 2. 遍歷名片列表,查詢要搜索的姓名,如果沒有,需要提示用戶
    for card_temp in card_list:

        if card_temp["name"] == find_name:
            print("找到了")
            print("姓名\t\t\t電話\t\t\tQQ\t\t\temail")
            print("=" * 50)
            print("%s\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t" % (
                card_temp["name"],
                card_temp["phone"],
                card_temp["qq"],
                card_temp["email"]))
            print("=" * 50)

            deal_card(card_temp)

            break

    else:
        print("抱歉,沒找到")


def deal_card(card_temp):
    """
    處理名片的信息
    :param card_temp: 字典中的東西
    :return: 
    """
    # 1.提示用戶進(jìn)行什么操作

    # print(card_temp)
    action_str = input("請選擇你要進(jìn)行的操作  "
                       "[1] 修改 [2] 刪除 "
                       "[0] 返回上一級菜單")
    if action_str == "1":
        # 修改操作
        card_temp["name"] = input_card_info(card_temp["name"], "name:")
        card_temp["phone"] = input_card_info(card_temp["phone"], "phone:")
        card_temp["qq"] = input_card_info(card_temp["qq"], "qq:")
        card_temp["email"] = input_card_info(card_temp["email"], "email")
        print("修改名片")

    elif action_str == "2":
        # 刪除操作
        card_list.remove(card_temp)
        print("刪除名片成功!")

    elif action_str == "0":
        return


def input_card_info(card_temp, tip_message):
    """
    輸入名片信息
    :param card_temp: 字典中的原有的值
    :param tip_message: 輸入的值
    :return: 
    """
    # 1.提示用戶輸入信息內(nèi)容
    result_str = input(tip_message)

    # 2. 針對用戶的輸入進(jìn)行判斷,如果用戶輸入了內(nèi)容,直接就返回結(jié)果
    if len(result_str) > 0:

        return result_str

    # 3.如果沒有輸入內(nèi)容,返回字典中原有的值
    else:
        return card_temp

            
          

遞歸求階乘

            
              def factorial(number):

    if number <=1:
        return 1
    else:
        return number * factorial(number - 1)

# range函數(shù)生成從0 到 里面的數(shù)的值 - 1
for i in range(11):
    print("%2d! = %d"% (i,factorial(i)))
            
          

?


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 大兴区| 九寨沟县| 澎湖县| 南漳县| 博乐市| 常德市| 米林县| 广平县| 奉贤区| 靖边县| 和田市| 普定县| 呈贡县| 利川市| 平果县| 宜城市| 方山县| 普定县| 禹城市| 睢宁县| 礼泉县| 固镇县| 宁化县| 法库县| 芦山县| 大石桥市| 年辖:市辖区| 兴仁县| 玉门市| 岱山县| 广州市| 大竹县| 毕节市| 阿拉善盟| 陆川县| 岑巩县| 桑植县| 潢川县| 肇庆市| 烟台市| 大丰市|