我是靠谱客的博主 俏皮导师,最近开发中收集的这篇文章主要介绍python-10.菜鸟教程-5-总纲实例演示,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Python 数字求和

以下实例为通过用户输入两个数字,并计算两个数字之和:


# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
# 用户输入数字
num1 = input('输入第一个数字:')
num2 = input('输入第二个数字:')
 
# 求和
sum = float(num1) + float(num2)
 
# 显示计算结果
print('数字 {0} 和 {1} 相加结果为: {2}'.format(num1, num2, sum))

执行以上代码输出结果为:

输入第一个数字:1.5
输入第二个数字:2.5
数字 1.5 和 2.5 相加结果为: 4.0

在该实例中,我们通过用户输入两个数字来求和。使用了内置函数 input() 来获取用户的输入,input() 返回一个字符串,所以我们需要使用 float() 方法将字符串转换为数字。

两数字运算,求和我们使用了加号 (+)运算符,除此外,还有 减号 (-), 乘号 (*), 除号 (/), 地板除 (//) 或 取余 (%)。更多数字运算可以查看我们的Python 数字运算。

我们还可以将以上运算,合并为一行代码:


# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
print('两数之和为 %.1f' %(float(input('输入第一个数字:'))+float(input('输入第二个数字:'))))

执行以上代码输出结果为:

$ python test.py 
输入第一个数字:1.5
输入第二个数字:2.5
两数之和为 4.0

Python 平方根

平方根,又叫二次方根,表示为〔√ ̄〕,如:数学语言为:√ ̄16=4。语言描述为:根号下16=4。

以下实例为通过用户输入一个数字,并计算这个数字的平方根:


# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
num = float(input('请输入一个数字: '))
num_sqrt = num ** 0.5
print(' %0.3f 的平方根为 %0.3f'%(num ,num_sqrt))

执行以上代码输出结果为:

$ python test.py 
请输入一个数字: 4
 4.000 的平方根为 2.000

在该实例中,我们通过用户输入一个数字,并使用指数运算符 ** 来计算该数的平方根。

该程序只适用于正数。负数和复数可以使用以下的方式:


# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
# 计算实数和复数平方根
# 导入复数数学模块
 
import cmath
 
num = int(input("请输入一个数字: "))
num_sqrt = cmath.sqrt(num)
print('{0} 的平方根为 {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

执行以上代码输出结果为:

$ python test.py 
请输入一个数字: -8
-8 的平方根为 0.000+2.828j

该实例中,我们使用了 cmath (complex math) 模块的 sqrt() 方法。

Python 二次方程

以下实例为通过用户输入数字,并计算二次方程:


# Filename : test.py
# author by : www.runoob.com
 
# 二次方程式 ax**2 + bx + c = 0
# a、b、c 用户提供,为实数,a ≠ 0
 
# 导入 cmath(复杂数学运算) 模块
import cmath
 
a = float(input('输入 a: '))
b = float(input('输入 b: '))
c = float(input('输入 c: '))
 
# 计算
d = (b**2) - (4*a*c)
 
# 两种求解方式
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
 
print('结果为 {0} 和 {1}'.format(sol1,sol2))

执行以上代码输出结果为:

$ python test.py 
输入 a: 1
输入 b: 5
输入 c: 6
结果为 (-3+0j) 和 (-2+0j)

该实例中,我们使用了 cmath (complex math) 模块的 sqrt() 方法 来计算平方根。

Python 计算三角形的面积

以下实例为通过用户输入三角形三边长度,并计算三角形的面积:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com


a = float(input('输入三角形第一边长: '))
b = float(input('输入三角形第二边长: '))
c = float(input('输入三角形第三边长: '))

# 计算半周长
s = (a + b + c) / 2

# 计算面积
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print('三角形面积为 %0.2f' % area)

执行以上代码输出结果为:

$ python test.py 
输入三角形第一边长: 5
输入三角形第二边长: 6
输入三角形第三边长: 7
三角形面积为 14.70

Python 计算圆的面积

圆的面积公式为 :

公式中 r 为圆的半径。

# 定义一个方法来计算圆的面积
def findArea(r):
    PI = 3.142
    return PI * (r * r)


# 调用方法
print("圆的面积为 %.6f" % findArea(5))

以上实例输出结果为:

圆的面积为 78.550000

Python 随机数生成

以下实例演示了如何生成一个随机数:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# 生成 0 ~ 9 之间的随机数

# 导入 random(随机数) 模块
import random

print(random.randint(0, 9))

执行以上代码输出结果为:

4

以上实例我们使用了 random 模块的 randint() 函数来生成随机数,你每次执行后都返回不同的数字(0 到 9),该函数的语法为:

random.randint(a,b)

函数返回数字 N ,N 为 a 到 b 之间的数字(a <= N <= b),包含 a 和 b。

Python 摄氏温度转华氏温度 

以下实例演示了如何将摄氏温度转华氏温度:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# 用户输入摄氏温度

# 接收用户输入
celsius = float(input('输入摄氏温度: '))

# 计算华氏温度
fahrenheit = (celsius * 1.8) + 32
print('%0.1f 摄氏温度转为华氏温度为 %0.1f ' % (celsius, fahrenheit))

执行以上代码输出结果为:

输入摄氏温度: 38
38.0 摄氏温度转为华氏温度为 100.4 

以上实例中,摄氏温度转华氏温度的公式为 celsius * 1.8 = fahrenheit - 32。所以得到以下式子:

celsius = (fahrenheit - 32) / 1.8

 摄氏度和华氏度相互转换

eg1:

#!/usr/bin/python
# -*- coding:utf-8 -*-

a = int(input('摄氏度转换为华氏温度请按1n华氏温度转化为摄氏度请按2n'))
while a != 1 and a != 2:
    a = int(input('你选择不正确,请重新输入。n摄氏度转换为华氏温度请按1n华氏温度转换为摄氏度请按2n'))
if a == 1:
    celsius = float(input('输入摄氏度:'))
    fahrenheit = (celsius * 1.8) + 32  # 计算华氏温度
    print('%.1f摄氏度转为华氏温度为%.1f' % (celsius, fahrenheit))
else:
    fahrenheit = float(input('输入华氏度:'))
    celsius = (fahrenheit - 32) / 1.8  # 计算摄氏度
    print('%.1f华氏度转为摄氏度为%.1f' % (fahrenheit, celsius))
摄氏度转换为华氏温度请按1
华氏温度转化为摄氏度请按2
3
你选择不正确,请重新输入。
摄氏度转换为华氏温度请按1
华氏温度转换为摄氏度请按2
9
你选择不正确,请重新输入。
摄氏度转换为华氏温度请按1
华氏温度转换为摄氏度请按2
2
输入华氏度:100.4
100.4华氏度转为摄氏度为38.0

eg2: 

a = input("请输入带有符号的温度值: ")
if a[-1] in ['F', 'f']:
    C = (eval(a[0:-1]) - 32) / 1.8
    print("转换后的温度是{:.1f}C".format(C))
elif a[-1] in ['C', 'c']:
    F = 1.8 * eval(a[0:-1]) + 32
    print("转换后的温度是{:.1f}F".format(F))
else:
    print("输入格式错误")

 测试结果:

请输入带有符号的温度值: 38C
转换后的温度是100.4F

 

请输入带有符号的温度值: 100.4F
转换后的温度是38.0C

Python 交换变量

以下实例通过用户输入两个变量,并相互交换:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# 用户输入

x = input('输入 x 值: ')
y = input('输入 y 值: ')

# 创建临时变量,并交换
temp = x
x = y
y = temp

print('交换后 x 的值为: {}'.format(x))
print('交换后 y 的值为: {}'.format(y))

执行以上代码输出结果为:

输入 x 值: 2
输入 y 值: 3
交换后 x 的值为: 3
交换后 y 的值为: 2

以上实例中,我们创建了临时变量 temp ,并将 x 的值存储在 temp 变量中,接着将 y 值赋给 x,最后将 temp 赋值给 y 变量。

不使用临时变量

我们也可以不创建临时变量,用一个非常优雅的方式来交换变量:

x,y = y,x

所以以上实例就可以修改为:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# 用户输入

x = input('输入 x 值: ')
y = input('输入 y 值: ')

# 不使用临时变量
x, y = y, x

print('交换后 x 的值为: {}'.format(x))
print('交换后 y 的值为: {}'.format(y))

执行以上代码输出结果为:

输入 x 值: 1
输入 y 值: 2
交换后 x 的值为: 2
交换后 y 的值为: 1

异或形式

# 交换变量
x = int(input('输入 X 值:'))
y = int(input('输入 Y 值:'))
x = x ^ y
y = x ^ y
x = x ^ y
print('交换后的 X 值为:', x)
print('交换后的 Y 值为:', y)
输入 X 值:2
输入 Y 值:3
交换后的 X 值为: 3
交换后的 Y 值为: 2

 不使用临时变量:

# -*- coding: UTF-8 -*-

# 用户输入
x = int(input('输入 x 值: '))
y = int(input('输入 y 值: '))

x = x + y
y = x - y
x = x - y

print('交换后 x 的值为: {}'.format(x))
print('交换后 y 的值为: {}'.format(y))
输入 x 值: 2
输入 y 值: 3
交换后 x 的值为: 3
交换后 y 的值为: 2

Python if 语句

以下实例通过使用 if...elif...else 语句判断数字是正数、负数或零:


# Filename : test.py
# author by : www.runoob.com
 
# 用户输入数字
 
num = float(input("输入一个数字: "))
if num > 0:
   print("正数")
elif num == 0:
   print("零")
else:
   print("负数")

执行以上代码输出结果为:

输入一个数字: 3
正数

我们也可以使用内嵌 if 语句来实现:


# Filename :test.py
# author by : www.runoob.com
 
# 内嵌 if 语句
 
num = float(input("输入一个数字: "))
if num >= 0:
   if num == 0:
       print("零")
   else:
       print("正数")
else:
   print("负数")

执行以上代码输出结果为:

输入一个数字: 0
零

优化增加输入字符的判断以及异常输出:

while True:
    try:
        num = float(input('请输入一个数字:'))
        if num == 0:
            print('输入的数字是零')
        elif num > 0:
            print('输入的数字是正数')
        else:
            print('输入的数字是负数')
        break
    except ValueError:
        print('输入无效,需要输入一个数字')
请输入一个数字:@
输入无效,需要输入一个数字
请输入一个数字:KKK
输入无效,需要输入一个数字
请输入一个数字:-6
输入的数字是负数

Python 判断字符串是否为数字

以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字:

# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False


# 测试字符串和数字
print(is_number('foo'))    # False
print(is_number('1'))      # True
print(is_number('1.3'))    # True
print(is_number('-1.37'))  # True
print(is_number('1e3'))    # True

# 测试 Unicode
# 阿拉伯语 5
print(is_number('٥'))      # True
# 泰语 2
print(is_number('๒'))      # True
# 中文数字
print(is_number('四'))     # True
# 版权号
print(is_number('©'))      # False

我们也可以使用内嵌 if 语句来实现:

执行以上代码输出结果为:

False
True
True
True
True
True
True
True
False

更多方法

Python isdigit() 方法检测字符串是否只由数字组成。

Python isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。

注意:教程代码当出现多个汉字数字时会报错,通过遍历字符串解决  False 如下

# 中文数字
print(is_number('四百五十六'))     # False


False

# 教程代码当出现多个汉字数字时会报错,通过遍历字符串解决
# 对汉字表示的数字也可分辨


def is_number(s):
    try:                            # 如果能运行float(s)语句,返回True(字符串s是浮点数)
        float(s)
        return True
    except ValueError:              # ValueError为Python的一种标准异常,表示"传入无效的参数"
        pass                        # 如果引发了ValueError这种异常,不做任何事情(pass:不做任何事情,一般用做占位语句)
    try:
        import unicodedata          # 处理ASCii码的包
        for i in s:
            unicodedata.numeric(i)  # 把一个表示数字的字符串转换为浮点数返回的函数
            # return True
        return True
    except (TypeError, ValueError):
        pass
    return False


# 测试字符串和数字
print(is_number('foo'))             # False
print(is_number('1'))               # True
print(is_number('1.3'))             # True
print(is_number('-1.37'))           # True
print(is_number('1e3'))             # True

# 测试 Unicode
# 阿拉伯语 5
print(is_number('٥'))               # True
# 泰语 2
print(is_number('๒'))               # True
# 中文数字
print(is_number('四百五十六'))       # True
# 版权号
print(is_number('©'))               # False
False
True
True
True
True
True
True
True
False

Python 判断奇数偶数

以下实例用于判断一个数字是否为奇数或偶数:

# Filename : test.py
# author by : www.runoob.com

# Python 判断奇数偶数
# 如果是偶数除于 2 余数为 0
# 如果余数为 1 则为奇数

num = int(input("输入一个数字: "))
if (num % 2) == 0:
    print("{0} 是偶数".format(num))
else:
    print("{0} 是奇数".format(num))

我们也可以使用内嵌 if 语句来实现:

执行以上代码输出结果为:

输入一个数字: 3
3 是奇数
while True:
    try:
        num = int(input('输入一个整数:'))  # 判断输入是否为整数
    except ValueError:  # 不是纯数字需要重新输入
        print("输入的不是整数!")
        continue
    if num % 2 == 0:
        print('偶数')
    else:
        print('奇数')
    break
输入一个整数:SS
输入的不是整数!
输入一个整数:GG
输入的不是整数!
输入一个整数:6.23
输入的不是整数!
输入一个整数:6.28
输入的不是整数!
输入一个整数:7.0
输入的不是整数!
输入一个整数:7
奇数

 Python 判断闰年

以下实例用于判断用户输入的年份是否为闰年:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

year = int(input("输入一个年份: "))
if (year % 4) == 0:
    if (year % 100) == 0:
        if (year % 400) == 0:
            print("{0} 是闰年".format(year))   # 整百年能被400整除的是闰年
        else:
            print("{0} 不是闰年".format(year))
    else:
        print("{0} 是闰年".format(year))       # 非整百年能被4整除的为闰年
else:
    print("{0} 不是闰年".format(year))

我们也可以使用内嵌 if 语句来实现:

执行以上代码输出结果为:

输入一个年份: 2000
2000 是闰年
输入一个年份: 2011
2011 不是闰年

参考方法:

#!/usr/bin/python3

year = int(input("请输入一个年份:"))
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    print("{0}是闰年".format(year))
else:
    print("{0}不是闰年".format(year))

但其实 Python 的 calendar 库中已经封装好了一个方法 isleap() 来实现这个判断是否为闰年:

import calendar

print(calendar.isleap(2000))

print(calendar.isleap(1900))

根据用户输入判断:

import calendar

year = int(input("请输入年份:"))
check_year = calendar.isleap(year)
if check_year:
    print("闰年")
else:
    print("平年")
Calendar.py
"""Calendar printing functions

Note when comparing these calendars to the ones printed by cal(1): By
default, these calendars have Monday as the first day of the week, and
Sunday as the last (the European convention). Use setfirstweekday() to
set the first day of the week (0=Monday, 6=Sunday)."""

import sys
import datetime
import locale as _locale
from itertools import repeat

__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
           "firstweekday", "isleap", "leapdays", "weekday", "monthrange",
           "monthcalendar", "prmonth", "month", "prcal", "calendar",
           "timegm", "month_name", "month_abbr", "day_name", "day_abbr",
           "Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar",
           "LocaleHTMLCalendar", "weekheader"]

# Exception raised for bad input (with string parameter for details)
error = ValueError

# Exceptions raised for bad input
class IllegalMonthError(ValueError):
    def __init__(self, month):
        self.month = month
    def __str__(self):
        return "bad month number %r; must be 1-12" % self.month


class IllegalWeekdayError(ValueError):
    def __init__(self, weekday):
        self.weekday = weekday
    def __str__(self):
        return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday


# Constants for months referenced later
January = 1
February = 2

# Number of days per month (except for February in leap years)
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

# This module used to have hard-coded lists of day and month names, as
# English strings.  The classes following emulate a read-only version of
# that, but supply localized names.  Note that the values are computed
# fresh on each call, in case the user changes locale between calls.

class _localized_month:

    _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
    _months.insert(0, lambda x: "")

    def __init__(self, format):
        self.format = format

    def __getitem__(self, i):
        funcs = self._months[i]
        if isinstance(i, slice):
            return [f(self.format) for f in funcs]
        else:
            return funcs(self.format)

    def __len__(self):
        return 13


class _localized_day:

    # January 1, 2001, was a Monday.
    _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]

    def __init__(self, format):
        self.format = format

    def __getitem__(self, i):
        funcs = self._days[i]
        if isinstance(i, slice):
            return [f(self.format) for f in funcs]
        else:
            return funcs(self.format)

    def __len__(self):
        return 7


# Full and abbreviated names of weekdays
day_name = _localized_day('%A')
day_abbr = _localized_day('%a')

# Full and abbreviated names of months (1-based arrays!!!)
month_name = _localized_month('%B')
month_abbr = _localized_month('%b')

# Constants for weekdays
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)


def isleap(year):
    """Return True for leap years, False for non-leap years."""
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


def leapdays(y1, y2):
    """Return number of leap years in range [y1, y2).
       Assume y1 <= y2."""
    y1 -= 1
    y2 -= 1
    return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)


def weekday(year, month, day):
    """Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31)."""
    if not datetime.MINYEAR <= year <= datetime.MAXYEAR:
        year = 2000 + year % 400
    return datetime.date(year, month, day).weekday()


def monthrange(year, month):
    """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
       year, month."""
    if not 1 <= month <= 12:
        raise IllegalMonthError(month)
    day1 = weekday(year, month, 1)
    ndays = mdays[month] + (month == February and isleap(year))
    return day1, ndays


def monthlen(year, month):
    return mdays[month] + (month == February and isleap(year))


def prevmonth(year, month):
    if month == 1:
        return year-1, 12
    else:
        return year, month-1


def nextmonth(year, month):
    if month == 12:
        return year+1, 1
    else:
        return year, month+1


class Calendar(object):
    """
    Base calendar class. This class doesn't do any formatting. It simply
    provides data to subclasses.
    """

    def __init__(self, firstweekday=0):
        self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday

    def getfirstweekday(self):
        return self._firstweekday % 7

    def setfirstweekday(self, firstweekday):
        self._firstweekday = firstweekday

    firstweekday = property(getfirstweekday, setfirstweekday)

    def iterweekdays(self):
        """
        Return an iterator for one week of weekday numbers starting with the
        configured first one.
        """
        for i in range(self.firstweekday, self.firstweekday + 7):
            yield i%7

    def itermonthdates(self, year, month):
        """
        Return an iterator for one month. The iterator will yield datetime.date
        values and will always iterate through complete weeks, so it will yield
        dates outside the specified month.
        """
        for y, m, d in self.itermonthdays3(year, month):
            yield datetime.date(y, m, d)

    def itermonthdays(self, year, month):
        """
        Like itermonthdates(), but will yield day numbers. For days outside
        the specified month the day number is 0.
        """
        day1, ndays = monthrange(year, month)
        days_before = (day1 - self.firstweekday) % 7
        yield from repeat(0, days_before)
        yield from range(1, ndays + 1)
        days_after = (self.firstweekday - day1 - ndays) % 7
        yield from repeat(0, days_after)

    def itermonthdays2(self, year, month):
        """
        Like itermonthdates(), but will yield (day number, weekday number)
        tuples. For days outside the specified month the day number is 0.
        """
        for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday):
            yield d, i % 7

    def itermonthdays3(self, year, month):
        """
        Like itermonthdates(), but will yield (year, month, day) tuples.  Can be
        used for dates outside of datetime.date range.
        """
        day1, ndays = monthrange(year, month)
        days_before = (day1 - self.firstweekday) % 7
        days_after = (self.firstweekday - day1 - ndays) % 7
        y, m = prevmonth(year, month)
        end = monthlen(y, m) + 1
        for d in range(end-days_before, end):
            yield y, m, d
        for d in range(1, ndays + 1):
            yield year, month, d
        y, m = nextmonth(year, month)
        for d in range(1, days_after + 1):
            yield y, m, d

    def itermonthdays4(self, year, month):
        """
        Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples.
        Can be used for dates outside of datetime.date range.
        """
        for i, (y, m, d) in enumerate(self.itermonthdays3(year, month)):
            yield y, m, d, (self.firstweekday + i) % 7

    def monthdatescalendar(self, year, month):
        """
        Return a matrix (list of lists) representing a month's calendar.
        Each row represents a week; week entries are datetime.date values.
        """
        dates = list(self.itermonthdates(year, month))
        return [ dates[i:i+7] for i in range(0, len(dates), 7) ]

    def monthdays2calendar(self, year, month):
        """
        Return a matrix representing a month's calendar.
        Each row represents a week; week entries are
        (day number, weekday number) tuples. Day numbers outside this month
        are zero.
        """
        days = list(self.itermonthdays2(year, month))
        return [ days[i:i+7] for i in range(0, len(days), 7) ]

    def monthdayscalendar(self, year, month):
        """
        Return a matrix representing a month's calendar.
        Each row represents a week; days outside this month are zero.
        """
        days = list(self.itermonthdays(year, month))
        return [ days[i:i+7] for i in range(0, len(days), 7) ]

    def yeardatescalendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting. The return
        value is a list of month rows. Each month row contains up to width months.
        Each month contains between 4 and 6 weeks and each week contains 1-7
        days. Days are datetime.date objects.
        """
        months = [
            self.monthdatescalendar(year, i)
            for i in range(January, January+12)
        ]
        return [months[i:i+width] for i in range(0, len(months), width) ]

    def yeardays2calendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting (similar to
        yeardatescalendar()). Entries in the week lists are
        (day number, weekday number) tuples. Day numbers outside this month are
        zero.
        """
        months = [
            self.monthdays2calendar(year, i)
            for i in range(January, January+12)
        ]
        return [months[i:i+width] for i in range(0, len(months), width) ]

    def yeardayscalendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting (similar to
        yeardatescalendar()). Entries in the week lists are day numbers.
        Day numbers outside this month are zero.
        """
        months = [
            self.monthdayscalendar(year, i)
            for i in range(January, January+12)
        ]
        return [months[i:i+width] for i in range(0, len(months), width) ]


class TextCalendar(Calendar):
    """
    Subclass of Calendar that outputs a calendar as a simple plain text
    similar to the UNIX program cal.
    """

    def prweek(self, theweek, width):
        """
        Print a single week (no newline).
        """
        print(self.formatweek(theweek, width), end='')

    def formatday(self, day, weekday, width):
        """
        Returns a formatted day.
        """
        if day == 0:
            s = ''
        else:
            s = '%2i' % day             # right-align single-digit days
        return s.center(width)

    def formatweek(self, theweek, width):
        """
        Returns a single week in a string (no newline).
        """
        return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)

    def formatweekday(self, day, width):
        """
        Returns a formatted week day name.
        """
        if width >= 9:
            names = day_name
        else:
            names = day_abbr
        return names[day][:width].center(width)

    def formatweekheader(self, width):
        """
        Return a header for a week.
        """
        return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())

    def formatmonthname(self, theyear, themonth, width, withyear=True):
        """
        Return a formatted month name.
        """
        s = month_name[themonth]
        if withyear:
            s = "%s %r" % (s, theyear)
        return s.center(width)

    def prmonth(self, theyear, themonth, w=0, l=0):
        """
        Print a month's calendar.
        """
        print(self.formatmonth(theyear, themonth, w, l), end='')

    def formatmonth(self, theyear, themonth, w=0, l=0):
        """
        Return a month's calendar string (multi-line).
        """
        w = max(2, w)
        l = max(1, l)
        s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
        s = s.rstrip()
        s += 'n' * l
        s += self.formatweekheader(w).rstrip()
        s += 'n' * l
        for week in self.monthdays2calendar(theyear, themonth):
            s += self.formatweek(week, w).rstrip()
            s += 'n' * l
        return s

    def formatyear(self, theyear, w=2, l=1, c=6, m=3):
        """
        Returns a year's calendar as a multi-line string.
        """
        w = max(2, w)
        l = max(1, l)
        c = max(2, c)
        colwidth = (w + 1) * 7 - 1
        v = []
        a = v.append
        a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
        a('n'*l)
        header = self.formatweekheader(w)
        for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
            # months in this row
            months = range(m*i+1, min(m*(i+1)+1, 13))
            a('n'*l)
            names = (self.formatmonthname(theyear, k, colwidth, False)
                     for k in months)
            a(formatstring(names, colwidth, c).rstrip())
            a('n'*l)
            headers = (header for k in months)
            a(formatstring(headers, colwidth, c).rstrip())
            a('n'*l)
            # max number of weeks for this row
            height = max(len(cal) for cal in row)
            for j in range(height):
                weeks = []
                for cal in row:
                    if j >= len(cal):
                        weeks.append('')
                    else:
                        weeks.append(self.formatweek(cal[j], w))
                a(formatstring(weeks, colwidth, c).rstrip())
                a('n' * l)
        return ''.join(v)

    def pryear(self, theyear, w=0, l=0, c=6, m=3):
        """Print a year's calendar."""
        print(self.formatyear(theyear, w, l, c, m), end='')


class HTMLCalendar(Calendar):
    """
    This calendar returns complete HTML pages.
    """

    # CSS classes for the day <td>s
    cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

    # CSS classes for the day <th>s
    cssclasses_weekday_head = cssclasses

    # CSS class for the days before and after current month
    cssclass_noday = "noday"

    # CSS class for the month's head
    cssclass_month_head = "month"

    # CSS class for the month
    cssclass_month = "month"

    # CSS class for the year's table head
    cssclass_year_head = "year"

    # CSS class for the whole year table
    cssclass_year = "year"

    def formatday(self, day, weekday):
        """
        Return a day as a table cell.
        """
        if day == 0:
            # day outside month
            return '<td class="%s">&nbsp;</td>' % self.cssclass_noday
        else:
            return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)

    def formatweek(self, theweek):
        """
        Return a complete week as a table row.
        """
        s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
        return '<tr>%s</tr>' % s

    def formatweekday(self, day):
        """
        Return a weekday name as a table header.
        """
        return '<th class="%s">%s</th>' % (
            self.cssclasses_weekday_head[day], day_abbr[day])

    def formatweekheader(self):
        """
        Return a header for a week as a table row.
        """
        s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
        return '<tr>%s</tr>' % s

    def formatmonthname(self, theyear, themonth, withyear=True):
        """
        Return a month name as a table row.
        """
        if withyear:
            s = '%s %s' % (month_name[themonth], theyear)
        else:
            s = '%s' % month_name[themonth]
        return '<tr><th colspan="7" class="%s">%s</th></tr>' % (
            self.cssclass_month_head, s)

    def formatmonth(self, theyear, themonth, withyear=True):
        """
        Return a formatted month as a table.
        """
        v = []
        a = v.append
        a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' % (
            self.cssclass_month))
        a('n')
        a(self.formatmonthname(theyear, themonth, withyear=withyear))
        a('n')
        a(self.formatweekheader())
        a('n')
        for week in self.monthdays2calendar(theyear, themonth):
            a(self.formatweek(week))
            a('n')
        a('</table>')
        a('n')
        return ''.join(v)

    def formatyear(self, theyear, width=3):
        """
        Return a formatted year as a table of tables.
        """
        v = []
        a = v.append
        width = max(width, 1)
        a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' %
          self.cssclass_year)
        a('n')
        a('<tr><th colspan="%d" class="%s">%s</th></tr>' % (
            width, self.cssclass_year_head, theyear))
        for i in range(January, January+12, width):
            # months in this row
            months = range(i, min(i+width, 13))
            a('<tr>')
            for m in months:
                a('<td>')
                a(self.formatmonth(theyear, m, withyear=False))
                a('</td>')
            a('</tr>')
        a('</table>')
        return ''.join(v)

    def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
        """
        Return a formatted year as a complete HTML page.
        """
        if encoding is None:
            encoding = sys.getdefaultencoding()
        v = []
        a = v.append
        a('<?xml version="1.0" encoding="%s"?>n' % encoding)
        a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">n')
        a('<html>n')
        a('<head>n')
        a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />n' % encoding)
        if css is not None:
            a('<link rel="stylesheet" type="text/css" href="%s" />n' % css)
        a('<title>Calendar for %d</title>n' % theyear)
        a('</head>n')
        a('<body>n')
        a(self.formatyear(theyear, width))
        a('</body>n')
        a('</html>n')
        return ''.join(v).encode(encoding, "xmlcharrefreplace")


class different_locale:
    def __init__(self, locale):
        self.locale = locale

    def __enter__(self):
        self.oldlocale = _locale.getlocale(_locale.LC_TIME)
        _locale.setlocale(_locale.LC_TIME, self.locale)

    def __exit__(self, *args):
        _locale.setlocale(_locale.LC_TIME, self.oldlocale)


class LocaleTextCalendar(TextCalendar):
    """
    This class can be passed a locale name in the constructor and will return
    month and weekday names in the specified locale. If this locale includes
    an encoding all strings containing month and weekday names will be returned
    as unicode.
    """

    def __init__(self, firstweekday=0, locale=None):
        TextCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = _locale.getdefaultlocale()
        self.locale = locale

    def formatweekday(self, day, width):
        with different_locale(self.locale):
            if width >= 9:
                names = day_name
            else:
                names = day_abbr
            name = names[day]
            return name[:width].center(width)

    def formatmonthname(self, theyear, themonth, width, withyear=True):
        with different_locale(self.locale):
            s = month_name[themonth]
            if withyear:
                s = "%s %r" % (s, theyear)
            return s.center(width)


class LocaleHTMLCalendar(HTMLCalendar):
    """
    This class can be passed a locale name in the constructor and will return
    month and weekday names in the specified locale. If this locale includes
    an encoding all strings containing month and weekday names will be returned
    as unicode.
    """
    def __init__(self, firstweekday=0, locale=None):
        HTMLCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = _locale.getdefaultlocale()
        self.locale = locale

    def formatweekday(self, day):
        with different_locale(self.locale):
            s = day_abbr[day]
            return '<th class="%s">%s</th>' % (self.cssclasses[day], s)

    def formatmonthname(self, theyear, themonth, withyear=True):
        with different_locale(self.locale):
            s = month_name[themonth]
            if withyear:
                s = '%s %s' % (s, theyear)
            return '<tr><th colspan="7" class="month">%s</th></tr>' % s


# Support for old module level interface
c = TextCalendar()

firstweekday = c.getfirstweekday

def setfirstweekday(firstweekday):
    if not MONDAY <= firstweekday <= SUNDAY:
        raise IllegalWeekdayError(firstweekday)
    c.firstweekday = firstweekday

monthcalendar = c.monthdayscalendar
prweek = c.prweek
week = c.formatweek
weekheader = c.formatweekheader
prmonth = c.prmonth
month = c.formatmonth
calendar = c.formatyear
prcal = c.pryear


# Spacing of month columns for multi-column year calendar
_colwidth = 7*3 - 1         # Amount printed by prweek()
_spacing = 6                # Number of spaces between columns


def format(cols, colwidth=_colwidth, spacing=_spacing):
    """Prints multi-column formatting for year calendars"""
    print(formatstring(cols, colwidth, spacing))


def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
    """Returns a string formatted from n strings, centered within n columns."""
    spacing *= ' '
    return spacing.join(c.center(colwidth) for c in cols)


EPOCH = 1970
_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()


def timegm(tuple):
    """Unrelated but handy function to calculate Unix timestamp from GMT."""
    year, month, day, hour, minute, second = tuple[:6]
    days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
    hours = days*24 + hour
    minutes = hours*60 + minute
    seconds = minutes*60 + second
    return seconds


def main(args):
    import argparse
    parser = argparse.ArgumentParser()
    textgroup = parser.add_argument_group('text only arguments')
    htmlgroup = parser.add_argument_group('html only arguments')
    textgroup.add_argument(
        "-w", "--width",
        type=int, default=2,
        help="width of date column (default 2)"
    )
    textgroup.add_argument(
        "-l", "--lines",
        type=int, default=1,
        help="number of lines for each week (default 1)"
    )
    textgroup.add_argument(
        "-s", "--spacing",
        type=int, default=6,
        help="spacing between months (default 6)"
    )
    textgroup.add_argument(
        "-m", "--months",
        type=int, default=3,
        help="months per row (default 3)"
    )
    htmlgroup.add_argument(
        "-c", "--css",
        default="calendar.css",
        help="CSS to use for page"
    )
    parser.add_argument(
        "-L", "--locale",
        default=None,
        help="locale to be used from month and weekday names"
    )
    parser.add_argument(
        "-e", "--encoding",
        default=None,
        help="encoding to use for output"
    )
    parser.add_argument(
        "-t", "--type",
        default="text",
        choices=("text", "html"),
        help="output type (text or html)"
    )
    parser.add_argument(
        "year",
        nargs='?', type=int,
        help="year number (1-9999)"
    )
    parser.add_argument(
        "month",
        nargs='?', type=int,
        help="month number (1-12, text only)"
    )

    options = parser.parse_args(args[1:])

    if options.locale and not options.encoding:
        parser.error("if --locale is specified --encoding is required")
        sys.exit(1)

    locale = options.locale, options.encoding

    if options.type == "html":
        if options.locale:
            cal = LocaleHTMLCalendar(locale=locale)
        else:
            cal = HTMLCalendar()
        encoding = options.encoding
        if encoding is None:
            encoding = sys.getdefaultencoding()
        optdict = dict(encoding=encoding, css=options.css)
        write = sys.stdout.buffer.write
        if options.year is None:
            write(cal.formatyearpage(datetime.date.today().year, **optdict))
        elif options.month is None:
            write(cal.formatyearpage(options.year, **optdict))
        else:
            parser.error("incorrect number of arguments")
            sys.exit(1)
    else:
        if options.locale:
            cal = LocaleTextCalendar(locale=locale)
        else:
            cal = TextCalendar()
        optdict = dict(w=options.width, l=options.lines)
        if options.month is None:
            optdict["c"] = options.spacing
            optdict["m"] = options.months
        if options.year is None:
            result = cal.formatyear(datetime.date.today().year, **optdict)
        elif options.month is None:
            result = cal.formatyear(options.year, **optdict)
        else:
            result = cal.formatmonth(options.year, options.month, **optdict)
        write = sys.stdout.write
        if options.encoding:
            result = result.encode(options.encoding)
            write = sys.stdout.buffer.write
        write(result)


if __name__ == "__main__":
    main(sys.argv)

Python 获取最大值函数

以下实例中我们使用max()方法求最大值:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# 最简单的
print(max(1, 2))
print(max('a', 'b'))

# 也可以对列表和元组使用
print(max([1, 2]))
print(max((1, 2)))

# 更多实例
print("80, 100, 1000 最大值为: ", max(80, 100, 1000))
print("-20, 100, 400最大值为: ", max(-20, 100, 400))
print("-80, -20, -10最大值为: ", max(-80, -20, -10))
print("0, 100, -400最大值为:", max(0, 100, -400))

执行以上代码输出结果为:

2
b
2
2
80, 100, 1000 最大值为:  1000
-20, 100, 400最大值为:  400
-80, -20, -10最大值为:  -10
0, 100, -400最大值为: 100

max() 函数介绍:Python max()函数。

Python 质数判断

一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数。

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# Python 程序用于检测用户输入的数字是否为质数

# 用户输入数字
num = int(input("请输入一个数字: "))

# 质数大于 1
if num > 1:
    # 查看因子
    for i in range(2, num):
        if (num % i) == 0:
            print(num, "不是质数")
            print(i, "乘于", num // i, "是", num)
            break
    else:
        print(num, "是质数")

# 如果输入的数字小于或等于 1,不是质数
else:
    print(num, "不是质数")

执行以上代码输出结果为:

$ python3 test.py 
请输入一个数字: 1
1 不是质数
$ python3 test.py 
请输入一个数字: 4
4 不是质数
2 乘于 2 是 4
$ python3 test.py 
请输入一个数字: 5
5 是质数

Python 输出指定范围内的素数

素数(prime number)又称质数,有无限个。除了1和它本身以外不再被其他的除数整除。

以下实例可以输出指定范围内的素数:

# !/usr/bin/python3

# 输出指定范围内的素数

# take input from the user
lower = int(input("输入区间最小值: "))
upper = int(input("输入区间最大值: "))

for num in range(lower, upper + 1):
    # 素数大于 1
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            print(num)

执行以上程序,输出结果为:

输入区间最小值: 1
输入区间最大值: 23
2
3
5
7
11
13
17
19
23

Python 阶乘实例

整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。

# !/usr/bin/python3

# Filename : test.py
# author by : www.runoob.com

# 通过用户输入数字计算阶乘

# 获取用户输入的数字
num = int(input("请输入一个数字: "))
factorial = 1

# 查看数字是负数,0 或 正数
if num < 0:
    print("抱歉,负数没有阶乘")
elif num == 0:
    print("0 的阶乘为 1")
else:
    for i in range(1, num + 1):
        factorial = factorial * i
    print("%d 的阶乘为 %d" % (num, factorial))

执行以上代码输出结果为:

请输入一个数字: 3
3 的阶乘为 6

Python 九九乘法表

以下实例演示了如何实现九九乘法表:
 

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# 九九乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        print('{}x{}={}t'.format(j, i, i * j), end='')
    print()

执行以上代码输出结果为:

1x1=1	
1x2=2	2x2=4	
1x3=3	2x3=6	3x3=9	
1x4=4	2x4=8	3x4=12	4x4=16	
1x5=5	2x5=10	3x5=15	4x5=20	5x5=25	
1x6=6	2x6=12	3x6=18	4x6=24	5x6=30	6x6=36	
1x7=7	2x7=14	3x7=21	4x7=28	5x7=35	6x7=42	7x7=49	
1x8=8	2x8=16	3x8=24	4x8=32	5x8=40	6x8=48	7x8=56	8x8=64	
1x9=9	2x9=18	3x9=27	4x9=36	5x9=45	6x9=54	7x9=63	8x9=72	9x9=81

通过指定end参数的值,可以取消在末尾输出回车符,实现不换行。

Python 斐波那契数列

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。

Python 实现斐波那契数列代码如下:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# Python 斐波那契数列实现

# 获取用户输入数据
nterms = int(input("你需要几项?"))

# 第一和第二项
n1 = 0
n2 = 1
count = 2

# 判断输入的值是否合法
if nterms <= 0:
    print("请输入一个正整数。")
elif nterms == 1:
    print("斐波那契数列:")
    print(n1)
else:
    print("斐波那契数列:")
    print(n1, ",", n2, end=" , ")
    while count < nterms:
        nth = n1 + n2
        print(nth, end=" , ")
        # 更新值
        n1 = n2
        n2 = nth
        count += 1

执行以上代码输出结果为:

你需要几项? 10
斐波那契数列:
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,

Python 阿姆斯特朗数

如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 例如1^3 + 5^3 + 3^3 = 153。

1000以内的阿姆斯特朗数: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407。

以下代码用于检测用户输入的数字是否为阿姆斯特朗数:

# Filename : test.py
# author by : www.runoob.com

# Python 检测用户输入的数字是否为阿姆斯特朗数

# 获取用户输入的数字
num = int(input("请输入一个数字: "))

# 初始化变量 sum
sum = 0
# 指数
n = len(str(num))

# 检测
temp = num
while temp > 0:
    digit = temp % 10
    sum += digit ** n
    temp //= 10

# 输出结果
if num == sum:
    print(num, "是阿姆斯特朗数")
else:
    print(num, "不是阿姆斯特朗数")

执行以上代码输出结果为:

$ python3 test.py 
请输入一个数字: 345
345 不是阿姆斯特朗数

$ python3 test.py 
请输入一个数字: 153
153 是阿姆斯特朗数

$ python3 test.py 
请输入一个数字: 1634
1634 是阿姆斯特朗数

获取指定期间内的阿姆斯特朗数


# Filename :test.py
# author by : www.runoob.com
 
# 获取用户输入数字
lower = int(input("最小值: "))
upper = int(input("最大值: "))
 
for num in range(lower,upper + 1):
   # 初始化 sum
   sum = 0
   # 指数
   n = len(str(num))
 
   # 检测
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** n
       temp //= 10
 
   if num == sum:
       print(num)

核心思想:%10取余从个位数到最高位数依次取余数,然后n次方,然后依次%10逐个拿到各位数的数值随后n次方,然后加总。

执行以上代码输出结果为:

最小值: 1
最大值: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474

以上实例中我们输出了 1 到 10000 之间的阿姆斯特朗数。

Python 十进制转二进制、八进制、十六进制

以下代码用于实现十进制转二进制、八进制、十六进制:


# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
# 获取用户输入十进制数
dec = int(input("输入数字:"))
 
print("十进制数为:", dec)
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为:", hex(dec))

执行以上代码输出结果为:

python3 test.py 
输入数字:5
十进制数为:5
转换为二进制为: 0b101
转换为八进制为: 0o5
转换为十六进制为: 0x5
python3 test.py 
输入数字:12
十进制数为:12
转换为二进制为: 0b1100
转换为八进制为: 0o14
转换为十六进制为: 0xc

Python ASCII码与字符相互转换

以下代码用于实现ASCII码与字符相互转换:

# Filename : test.py
# author by : www.runoob.com

# 用户输入字符
c = input("请输入一个字符: ")

# 用户输入ASCII码,并将输入的数字转为整型
a = int(input("请输入一个ASCII码: "))

print(c + " 的ASCII 码为", ord(c))
print(a, " 对应的字符为", chr(a))

执行以上代码输出结果为:

python3 test.py 
请输入一个字符: a
请输入一个ASCII码: 101
a 的ASCII 码为 97
101  对应的字符为 e

Python 最大公约数算法

以下代码用于实现最大公约数算法:

# Filename : test.py
# author by : www.runoob.com


# 定义一个函数
def hcf(x, y):
    """该函数返回两个数的最大公约数"""
    # 获取最小值
    if x > y:
        smaller = y
    else:
        smaller = x

    for i in range(1, smaller + 1):
        if (x % i == 0) and (y % i == 0):
            hcf = i

    return hcf


# 用户输入两个数字
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))

print(num1, "和", num2, "的最大公约数为", hcf(num1, num2))

执行以上代码输出结果为:

输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最大公约数为 6

Python 最小公倍数算法

以下代码用于实现最小公倍数算法:

# Filename : test.py
# author by : www.runoob.com


# 定义函数
def lcm(x, y):
    #  获取最大的数
    if x > y:
        greater = x
    else:
        greater = y

    while (True):
        if (greater % x == 0) and (greater % y == 0):
            lcm = greater
            break
        greater += 1

    return lcm


# 获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))

print(num1, "和", num2, "的最小公倍数为", lcm(num1, num2))

执行以上代码输出结果为:

输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最小公倍数为 216

Python 简单计算器实现

以下代码用于实现简单计算器实现,包括两个数基本的加减乘除运输:

# Filename : test.py
# author by : www.runoob.com


# 定义函数
def add(x, y):
    """相加"""

    return x + y


def subtract(x, y):
    """相减"""

    return x - y


def multiply(x, y):
    """相乘"""

    return x * y


def divide(x, y):
    """相除"""

    return x / y


# 用户输入
print("选择运算:")
print("1、相加")
print("2、相减")
print("3、相乘")
print("4、相除")

choice = input("输入你的选择(1/2/3/4):")

num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))

if choice == '1':
    print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':
    print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':
    print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':
    print(num1, "/", num2, "=", divide(num1, num2))
else:
    print("非法输入")

执行以上代码输出结果为:

选择运算:
1、相加
2、相减
3、相乘
4、相除
输入你的选择(1/2/3/4):2
输入第一个数字: 5
输入第二个数字: 2
5 - 2 = 3

Python 生成日历

以下代码用于生成指定日期的日历:


# Filename : test.py
# author by : www.runoob.com
 
# 引入日历模块
import calendar
 
# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
 
# 显示日历
print(calendar.month(yy,mm))

执行以上代码输出结果为:

输入年份: 2015
输入月份: 6
     June 2015
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

这个代码的缺点就是,我们日常用的日历都是星期天在前的。所以改进代码,应该加一行用以将星期天放在首位。

calendar.setfirstweekday(firstweekday=6)  # 设置第一天是星期天

Python 使用递归斐波那契数列

以下代码使用递归的方式来生成斐波那契数列:

# Filename : test.py
# author by : www.runoob.com


def recur_fibo(n):
    """递归函数
    输出斐波那契数列"""
    if n <= 1:
        return n
    else:
        return recur_fibo(n - 1) + recur_fibo(n - 2)


# 获取用户输入
nterms = int(input("您要输出几项? "))

# 检查输入的数字是否正确
if nterms <= 0:
    print("输入正数")
else:
    print("斐波那契数列:")
    for i in range(nterms):
        print(recur_fibo(i))

执行以上代码输出结果为:

您要输出几项? 10
斐波那契数列:
0
1
1
2
3
5
8
13
21
34

Python 文件 IO

以下代码演示了Python基本的文件操作,包括 open,read,write:


# Filename : test.py
# author by : www.runoob.com
 
# 写文件
with open("test.txt", "wt") as out_file:
    out_file.write("该文本会写入到文件中n看到我了吧!")
 
# Read a file
with open("test.txt", "rt") as in_file:
    text = in_file.read()
 
print(text)

执行以上代码输出结果为:

该文本会写入到文件中
看到我了吧!

Python 字符串判断

以下代码演示了Python字符串的判断:

# Filename : test.py
# author by : www.runoob.com

# 测试实例一
print("测试实例一")
str = "runoob.com"
print(str.isalnum()) # 判断所有字符都是数字或者字母
print(str.isalpha()) # 判断所有字符都是字母
print(str.isdigit()) # 判断所有字符都是数字
print(str.islower()) # 判断所有字符都是小写
print(str.isupper()) # 判断所有字符都是大写
print(str.istitle()) # 判断所有单词都是首字母大写,像标题
print(str.isspace()) # 判断所有字符都是空白字符、t、n、r

print("------------------------")

# 测试实例二
print("测试实例二")
str = "runoob"
print(str.isalnum())
print(str.isalpha())
print(str.isdigit())
print(str.islower())
print(str.isupper())
print(str.istitle())
print(str.isspace())

执行以上代码输出结果为:

测试实例一
False
False
False
True
False
False
False
------------------------
测试实例二
True
True
False
True
False
False

Python 字符串大小写转换

以下代码演示了如何将字符串转换为大写字母,或者将字符串转为小写字母等:

# Filename : test.py
# author by : www.runoob.com

str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 

执行以上代码输出结果为:

WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

Python 计算每个月天数

以下代码通过导入 calendar 模块来计算每个月的天数:

# !/usr/bin/python3
# author by : www.runoob.com

import calendar

monthRange = calendar.monthrange(2016, 9)
print(monthRange)

执行以上代码输出结果为:

(3, 30)

输出的是一个元组,第一个元素是所查月份的第一天对应的是星期几(0-6),第二个元素是这个月的天数。以上实例输出的意思为 2016 年 9 月份的第一天是星期四,该月总共有 30 天。

Python list 常用操作

0.list 总结

print("--------------------------------------------------------# 1.list 定义")
# 1.list 定义
li = ["a", "b", "mpilgrim", "z", "example"]
print(li)
print(li[1])

print("--------------------------------------------------------# 2.list 负数索引")
# 2.list 负数索引
print(li[-1])
print(li[-3])
print(li[1:3])
print(li[1:-1])
print(li[0:3])

print("--------------------------------------------------------# 3.list 增加元素")
# 3.list 增加元素
li.append("new")
print(li)
li.insert(2, "new")
print(li)
li.extend(["two", "elements"])
print(li)

print("--------------------------------------------------------# 4.list 搜索")
# 4.list 搜索
print(li.index("example"))
print(li.index("new"))
print("c" in li)

print("--------------------------------------------------------# 5.list 删除元素")
# 5.list 删除元素
print(li)
li.remove("z")
print(li)
li.remove("new")  # 删除首次出现的一个值
print(li)
print(li.pop())  # pop 会做两件事: 删除 list 的最后一个元素, 然后返回删除元素的值。
print(li)

print("--------------------------------------------------------# 6.list 运算符")
# 6.list 运算符
li = ['a', 'b', 'mpilgrim']

li = li + ['example', 'new']
print(li)
li += ['two']
print(li)
li = [1, 2] * 3
print(li)

print("--------------------------------------------------------# 7.使用join链接list成为字符串")
# 7.使用join链接list成为字符串
params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}
print(["%s=%s" % (k, v) for k, v in params.items()])
print(";".join(["%s=%s" % (k, v) for k, v in params.items()]))

print("--------------------------------------------------------# 8.list 分割字符串")
# 8.list 分割字符串
li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
print(s)
print(s.split(";"))
print(s.split(";", 1))

print("--------------------------------------------------------# 9.list 的映射解析")
# 9.list 的映射解析
li = [1, 9, 8, 4]
print([elem * 2 for elem in li])
print(li)

li = [elem * 2 for elem in li]
print(li)

print("--------------------------------------------------------# 10.dictionary 中的解析")
# 10.dictionary 中的解析
params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}

print(params.keys())
print(params.values())
print(params.items())

print([k for k, v in params.items()])
print([v for k, v in params.items()])
print(["%s=%s" % (k, v) for k, v in params.items()])

print("--------------------------------------------------------# 11.list 过滤")
# 11.list 过滤
li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]

print([elem for elem in li if len(elem) > 1])
print([elem for elem in li if elem != "b"])
print([elem for elem in li if li.count(elem) == 1])

 PyCharm里运行結果如下:


--------------------------------------------------------# 1.list 定义
['a', 'b', 'mpilgrim', 'z', 'example']
b
--------------------------------------------------------# 2.list 负数索引
example
mpilgrim
['b', 'mpilgrim']
['b', 'mpilgrim', 'z']
['a', 'b', 'mpilgrim']
--------------------------------------------------------# 3.list 增加元素
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
--------------------------------------------------------# 4.list 搜索
5
2
False
--------------------------------------------------------# 5.list 删除元素
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']
elements
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
--------------------------------------------------------# 6.list 运算符
['a', 'b', 'mpilgrim', 'example', 'new']
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
[1, 2, 1, 2, 1, 2]
--------------------------------------------------------# 7.使用join链接list成为字符串
['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']
server=mpilgrim;database=master;uid=sa;pwd=secret
--------------------------------------------------------# 8.list 分割字符串
server=mpilgrim;uid=sa;database=master;pwd=secret
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']
--------------------------------------------------------# 9.list 的映射解析
[2, 18, 16, 8]
[1, 9, 8, 4]
[2, 18, 16, 8]
--------------------------------------------------------# 10.dictionary 中的解析
dict_keys(['server', 'database', 'uid', 'pwd'])
dict_values(['mpilgrim', 'master', 'sa', 'secret'])
dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
['server', 'database', 'uid', 'pwd']
['mpilgrim', 'master', 'sa', 'secret']
['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']
--------------------------------------------------------# 11.list 过滤
['mpilgrim', 'foo']
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
['a', 'mpilgrim', 'foo', 'c']

Process finished with exit code 0

1.list 定义

>>> li = ["a", "b", "mpilgrim", "z", "example"]
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1]        
'b'

2.list 负数索引

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1]
'example'
>>> li[-3]
'mpilgrim'
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3]  
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'z']
>>> li[0:3]  
['a', 'b', 'mpilgrim']

3.list 增加元素

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

4.list 搜索

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
>>> li.index("new")
2
>>> li.index("c")
Traceback (innermost last):
 File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li
False

5.list 删除元素

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.remove("z")  
>>> li
['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
>>> li.remove("new")    # 删除首次出现的一个值
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']    # 第二个 'new' 未删除
>>> li.remove("c")     #list 中没有找到值, Python 会引发一个异常
Traceback (innermost last):
 File "<interactive input>", line 1, in ?
ValueError: list.remove(x): x not in list
>>> li.pop()      # pop 会做两件事: 删除 list 的最后一个元素, 然后返回删除元素的值。
'elements'
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']

6.list 运算符

>>> li = ['a', 'b', 'mpilgrim']
>>> li = li + ['example', 'new']
>>> li
['a', 'b', 'mpilgrim', 'example', 'new']
>>> li += ['two']        
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
>>> li = [1, 2] * 3
>>> li
[1, 2, 1, 2, 1, 2]

7.使用join链接list成为字符串

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> ["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
'server=mpilgrim;uid=sa;database=master;pwd=secret'

join 只能用于元素是字符串的 list; 它不进行任何的类型强制转换。连接一个存在一个或多个非字符串元素的 list 将引发一个异常。

PyCharm里运行如下:

params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}
print(["%s=%s" % (k, v) for k, v in params.items()])
print(";".join(["%s=%s" % (k, v) for k, v in params.items()]))

['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']
server=mpilgrim;database=master;uid=sa;pwd=secret

8.list 分割字符串

>>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s = ";".join(li)
>>> s
'server=mpilgrim;uid=sa;database=master;pwd=secret'
>>> s.split(";")  
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s.split(";", 1)
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

split 与 join 正好相反, 它将一个字符串分割成多元素 list。

注意, 分隔符 (";") 被完全去掉了, 它没有在返回的 list 中的任意元素中出现。

split 接受一个可选的第二个参数, 它是要分割的次数。

PyCharm里运行如下:

li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
print(s)
print(s.split(";"))
print(s.split(";", 1))
server=mpilgrim;uid=sa;database=master;pwd=secret
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']
    def split(self, *args, **kwargs): # real signature unknown
        """
        Return a list of the words in the string, using sep as the delimiter string.
        
          sep
            The delimiter according which to split the string.
            None (the default value) means split according to any whitespace,
            and discard empty strings from the result.
          maxsplit
            Maximum number of splits to do.
            -1 (the default value) means no limit.
        """
        pass

9.list 的映射解析

>>> li = [1, 9, 8, 4]
>>> [elem*2 for elem in li]   
[2, 18, 16, 8]
>>> li
[1, 9, 8, 4]
>>> li = [elem*2 for elem in li]
>>> li
[2, 18, 16, 8]

PyCharm里运行如下:

li = [1, 9, 8, 4]
print([elem * 2 for elem in li])
print(li)

li = [elem * 2 for elem in li]
print(li)

 

[2, 18, 16, 8]
[1, 9, 8, 4]
[2, 18, 16, 8]

10.dictionary 中的解析

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> params.keys()
dict_keys(['server', 'database', 'uid', 'pwd'])
>>> params.values()
dict_values(['mpilgrim', 'master', 'sa', 'secret'])
>>> params.items()
dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
>>> [k for k, v in params.items()]
['server', 'database', 'uid', 'pwd']
>>> [v for k, v in params.items()]
['mpilgrim', 'master', 'sa', 'secret']
>>> ["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']

PyCharm里运行如下:

params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}

print(params.keys())
print(params.values())
print(params.items())

print([k for k, v in params.items()])
print([v for k, v in params.items()])
print(["%s=%s" % (k, v) for k, v in params.items()])
dict_keys(['server', 'database', 'uid', 'pwd'])
dict_values(['mpilgrim', 'master', 'sa', 'secret'])
dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
['server', 'database', 'uid', 'pwd']
['mpilgrim', 'master', 'sa', 'secret']
['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']

11.list 过滤

>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
>>> [elem for elem in li if len(elem) > 1]
['mpilgrim', 'foo']
>>> [elem for elem in li if elem != "b"]
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
>>> [elem for elem in li if li.count(elem) == 1]
['a', 'mpilgrim', 'foo', 'c']

PyCharm里运行如下:

# 11.list 过滤
li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]

print([elem for elem in li if len(elem) > 1])
print([elem for elem in li if elem != "b"])
print([elem for elem in li if li.count(elem) == 1])
['mpilgrim', 'foo']
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
['a', 'mpilgrim', 'foo', 'c']

Python 约瑟夫生者死者小游戏

30 个人在一条船上,超载,需要 15 人下船。

于是人们排成一队,排队的位置即为他们的编号。

报数,从 1 开始,数到 9 的人下船。

如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?
 

people = {}
for x in range(1, 31):
    people[x] = 1
# print(people)
check = 0
i = 1
j = 0
while i <= 31:
    if i == 31:
        i = 1
    elif j == 15:
        break
    else:
        if people[i] == 0:
            i += 1
            continue
        else:
            check += 1
            if check == 9:
                people[i] = 0
                check = 0
                print("{}号下船了".format(i))
                j += 1
            else:
                i += 1
                continue

执行以上实例,输出结果为:

9号下船了
18号下船了
27号下船了
6号下船了
16号下船了
26号下船了
7号下船了
19号下船了
30号下船了
12号下船了
24号下船了
8号下船了
22号下船了
5号下船了
23号下船了

Python 五人分鱼

A、B、C、D、E 五人在某天夜里合伙去捕鱼,到第二天凌晨时都疲惫不堪,于是各自找地方睡觉。

日上三杆,A 第一个醒来,他将鱼分为五份,把多余的一条鱼扔掉,拿走自己的一份。

B 第二个醒来,也将鱼分为五份,把多余的一条鱼扔掉拿走自己的一份。 。

C、D、E依次醒来,也按同样的方法拿鱼。

问他们台伙至少捕了多少条鱼?

def main():
    fish = 1
    while True:
        total, enough = fish, True
        for _ in range(5):
            if (total - 1) % 5 == 0:
                total = (total - 1) // 5 * 4
            else:
                enough = False
                break
        if enough:
            print(f'总共有{fish}条鱼')
            break
        fish += 1


if __name__ == '__main__':
    main()

运行结果:

总共有3121条鱼

Python 实现秒表功能

以下实例使用 time 模块来实现秒表功能:

import time

print('按下回车开始计时,按下 Ctrl + C 停止计时。')
while True:

    input("")  # 如果是 python 2.x 版本请使用 raw_input()
    starttime = time.time()
    print('开始')
    try:
        while True:
            print('计时: ', round(time.time() - starttime, 0), '秒', end="r")
            time.sleep(1)
    except KeyboardInterrupt:
        print('结束')
        endtime = time.time()
        print('总共的时间为:', round(endtime - starttime, 2), 'secs')
        break

测试结果为:

按下回车开始计时,按下 Ctrl + C 停止计时。

开始
计时:  3.0 秒
计时:  5.0 秒
^C结束 6.0 秒
总共的时间为: 6.69 secs

Python 计算 n 个自然数的立方和

# 定义立方和的函数
def sumOfSeries(n):
    sum = 0
    for i in range(1, n + 1):
        sum += i * i * i

    return sum


# 调用函数
n = 5
print(sumOfSeries(n))

以上实例输出结果为:

225

Python 计算数组元素之和

定义一个整型数组,并计算元素之和。

实现要求:

输入 : arr[] = {1, 2, 3}

输出 : 6

计算: 1 + 2 + 3 = 6

# 定义函数,arr 为数组,n 为数组长度,可作为备用参数,这里没有用到
def _sum(arr, n):
    # 使用内置的 sum 函数计算
    return sum(arr)


# 调用函数
arr = []
# 数组元素
arr = [12, 3, 4, 15]

# 计算数组元素的长度
n = len(arr)

ans = _sum(arr, n)

# 输出结果
print('数组元素之和为', ans)

以上实例输出结果为: 

数组元素之和为 34

用for循环实现:

list = [1, 3, 5, 7, 9, 34]
sum = 0
for i in range(0, len(list)):
    sum += list[i]
print(sum)

参考方法: 

from functools import reduce

list = [1, 3, 5, 7, 9, 34]

print(reduce(lambda x, y: x + y, list))

 

59

Python 数组翻转指定个数的元素

定义一个整型数组,并将指定个数的元素翻转到数组的尾部。

例如:(ar[], d, n) 将长度为 n 的 数组 arr 的前面 d 个元素翻转到数组尾部。

以下演示了将数组的前面两个元素放到数组后面。

原始数组:

翻转后:

def leftRotate(arr, d, n):
    for i in range(d):
        leftRotatebyOne(arr, n)


def leftRotatebyOne(arr, n):
    temp = arr[0]
    for i in range(n - 1):
        arr[i] = arr[i + 1]
    arr[n - 1] = temp


def printArray(arr, size):
    for i in range(size):
        print("%d" % arr[i], end=" ")


arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

以上实例输出结果为: 

3 4 5 6 7 1 2 
def leftRotate(arr, d, n):
    for i in range(gcd(d, n)):

        temp = arr[i]
        j = i
        while 1:
            k = j + d
            if k >= n:
                k = k - n
            if k == i:
                break
            arr[j] = arr[k]
            j = k
        arr[j] = temp


def printArray(arr, size):
    for i in range(size):
        print("%d" % arr[i], end=" ")


def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)


arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

以上实例输出结果为:

3 4 5 6 7 1 2
def rverseArray(arr, start, end):
    while start < end:
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end = end - 1


def leftRotate(arr, d):
    n = len(arr)
    rverseArray(arr, 0, d - 1)
    rverseArray(arr, d, n - 1)
    rverseArray(arr, 0, n - 1)


def printArray(arr):
    for i in range(0, len(arr)):
        print(arr[i], end=' ')


arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2)
printArray(arr)

以上实例输出结果为:

3 4 5 6 7 1 2

Python 将列表中的头尾两个元素对调

定义一个列表,并将列表中的头尾两个元素对调。

例如:

对调前 : [1, 2, 3]
对调后 : [3, 2, 1]
def swapList(newList):
    size = len(newList)

    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp

    return newList


newList = [1, 2, 3]

print(swapList(newList))

以上实例输出结果为:

[3, 2, 1]
def swapList(newList):
    newList[0], newList[-1] = newList[-1], newList[0]

    return newList


newList = [1, 2, 3]
print(swapList(newList))

以上实例输出结果为:

[3, 2, 1]
def swapList(list):
    get = list[-1], list[0]

    list[0], list[-1] = get

    return list


newList = [1, 2, 3]
print(swapList(newList))

以上实例输出结果为:

[3, 2, 1]

参考方法:

def function(arr):
    a = arr.pop(0)
    b = arr.pop()
    arr.append(a)
    arr.insert(0, b)
    return arr


list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(function(list))

以上实例输出结果为: 

[9, 2, 3, 4, 5, 6, 7, 8, 1]
def swaplist(len, arr, n):
    if n > (len // 2):
        print('无法翻转!')
    else:
        arr[:n], arr[-n:] = arr[-n:], arr[:n]
        print('翻转后的列表:', arr)


a = int(input('请输入数列的长度:'))
b = list(range(1, a + 1))
c = int(input('请输入头尾对调的数目:'))
print('翻转前的列表:', b)
swaplist(a, b, c)

 以上实例输出结果为:

请输入数列的长度:6
请输入头尾对调的数目:2
翻转前的列表: [1, 2, 3, 4, 5, 6]
翻转后的列表: [5, 6, 3, 4, 1, 2]

Python 将列表中的指定位置的两个元素对调

定义一个列表,并将列表中的指定位置的两个元素对调。

例如,对调第一个和第三个元素:

对调前 : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
对调后 : [19, 65, 23, 90]
def swapPositions(list, pos1, pos2):
    list[pos1], list[pos2] = list[pos2], list[pos1]
    return list


List = [23, 65, 19, 90]
pos1, pos2 = 1, 3

print(swapPositions(List, pos1 - 1, pos2 - 1))

以上实例输出结果为:

[19, 65, 23, 90]
def swapPositions(list, pos1, pos2):
    first_ele = list.pop(pos1)
    second_ele = list.pop(pos2 - 1)

    list.insert(pos1, second_ele)
    list.insert(pos2, first_ele)

    return list


List = [23, 65, 19, 90]
pos1, pos2 = 1, 3

print(swapPositions(List, pos1 - 1, pos2 - 1))

以上实例输出结果为:

[19, 65, 23, 90]
def swapPositions(list, pos1, pos2):
    get = list[pos1], list[pos2]

    list[pos2], list[pos1] = get

    return list


List = [23, 65, 19, 90]

pos1, pos2 = 1, 3
print(swapPositions(List, pos1 - 1, pos2 - 1))

以上实例输出结果为:

[19, 65, 23, 90]

引入中间变量:

def reversal(list, n1, n2):
    temp = list[n1]
    list[n1] = list[n2]
    list[n2] = temp
    print(list)


list = [1, 2, 3, 4, 5, 6, 7]
reversal(list, 4, 5)

以上实例输出结果为:

[1, 2, 3, 4, 6, 5, 7]

 

最后

以上就是俏皮导师为你收集整理的python-10.菜鸟教程-5-总纲实例演示的全部内容,希望文章能够帮你解决python-10.菜鸟教程-5-总纲实例演示所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部