日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python基础(五)---python3中的内置函数

發布時間:2024/3/12 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python基础(五)---python3中的内置函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python3中的常用內置函數


  • input()函數:

    在終端打印括號中的消息,等待用戶輸入信息,然后將輸入值返回并存儲在內存中

    例如:

    name = input("What's your name? ")#輸入John Smithprint("My name is " + name)

    輸出:

    D:\Python37\python.exe "D:/pycharm project/myFirstPython.py"What's your name? John SmithMy name is John SmithProcess finished with exit code 0

    e.g.1

    Ask two questions: person’name and favourite color.
    then,print a message like ‘Mosh like blue’

    Solution:
    name = input("What's your name? ")#輸入Moshfavourite_color = input("What's your favourite color? ")#輸入blueprint(name + " likes " + favourite_color)

    輸出:

    D:\Python37\python.exe "D:/pycharm project/myFirstPython.py"What's your name? MoshWhat's your favourite color? blueMosh likes blueProcess finished with exit code 0

    e.g.2

    實現通過輸入出生年份,獲取年齡:

    birth_year = input("Birth year: ")#輸入1999age = 2020 - birth_yearprint("My age is" + age)

    輸出:

    D:\Python37\python.exe "D:/pycharm project/myFirstPython.py"Birth year: 1999Traceback (most recent call last):File "D:/pycharm project/myFirstPython.py", line 9, in <module>age = 2020 - birth_yearTypeError: unsupported operand type(s) for -: 'int' and 'str'Process finished with exit code 1

    錯誤解釋:

    無論birth_year輸入什么,都將轉換為一個String類型的字符串,而age中的2020是一個int類型的整數,
    Python無法解釋int類型的2020減去string類型的birth_year,導致報錯。


  • 其余常用內置函數:

    參考網址:https://www.runoob.com/python/python-built-in-functions.html

    主要內置函數:

    int() 函數用于將一個字符串或數字轉換為整型。
    str() 函數將對象轉化為適于人閱讀的形式。
    bool() 函數用于將給定參數轉換為布爾類型,如果沒有參數,返回 False。(bool 是 int 的子類)
    float() 函數用于將整數和字符串轉換成浮點數。
    max() 方法返回給定參數的最大值,參數可以為序列。
    type() 函數如果你只有第一個參數則返回對象的類型,三個參數返回新的類型對象。

    這時我們再回頭看上邊e.g.2里的錯誤,可以改為以下代碼:

    birth_year = input("Birth year: ")print(type(birth_year)) #顯示birth_year的數據類型age = 2020 - int(birth_year) #將birth_year變為int類型print(type(age)) #顯示age的數據類型print("My age is " + str(age))

    輸出:

    D:\Python37\python.exe "D:/pycharm project/myFirstPython.py"Birth year: 1999<class 'str'><class 'int'>My age is 21Process finished with exit code 0

    e.g.3

    Ask a user their weight( in pounds), convert it to kilograms and print on the terminal.

    Solution:
    weight_lbs = input('weight(lbs) ')weight_kg = int(weight_lbs) * 0.45print(weight_kg)

    輸出:

    D:\Python37\python.exe "D:/pycharm project/myFirstPython.py"weight(lbs) 18081.0Process finished with exit code 0
  • 總結

    以上是生活随笔為你收集整理的Python基础(五)---python3中的内置函数的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。