Python3 实例

Python 判断字符串是否为数字

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

实例(Python 3.0+)

# -*- coding: UTF-8 -*-# Filename : test.py# author by : www.runoob.comdef 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‘)) # Falseprint(is_number(‘1‘)) # Trueprint(is_number(‘1.3‘)) # Trueprint(is_number(‘-1.37‘)) # Trueprint(is_number(‘1e3‘)) # True# 测试 Unicode# 阿拉伯语 5print(is_number(‘?‘)) # True# 泰语 2print(is_number(‘?‘)) # True# 中文数字print(is_number(‘四‘)) # True# 版权号print(is_number(‘©‘)) # False

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

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

FalseTrueTrueTrueTrueTrueTrueTrueFalse

Python 判断奇数偶数

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

实例(Python 3.0+)

# 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 语句来实现:

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

输入一个数字: 33 是奇数

笔记

优化加入输入判断:

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

Python 判断闰年

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

实例(Python 3.0+)

# -*- 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 语句来实现:

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

输入一个年份: 20002000 是闰年
输入一个年份: 20112011 不是闰年

Python 获取最大值函数

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

实例(Python 3.0+)

# -*- 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))

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

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

Python 质数判断

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

test.py 文件:

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

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

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

# 质数大于 1if 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 请输入一个数字: 11 不是质数$ python3 test.py 请输入一个数字: 44 不是质数2 乘于 2 是 4$ python3 test.py 请输入一个数字: 55 是质数

Python 输出指定范围内的素数

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

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

实例(Python 3.0+)

#!/usr/bin/python3# 输出指定范围内的素数# take input from the userlower = int(input("输入区间最小值: "))upper = int(input("输入区间最大值: "))for num inrange(lower,upper + 1): # 素数大于 1 if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)

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

$ python3 test.py 输入区间最小值: 1输入区间最大值: 1002357111317192329313741434753596167717379838997

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))

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

请输入一个数字: 33 的阶乘为 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{}={}	‘.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 实现斐波那契数列代码如下:

实例(Python 3.0+)

# -*- coding: UTF-8 -*-# Filename : test.py# author by : www.runoob.com# Python 斐波那契数列实现# 获取用户输入数据nterms = int(input("你需要几项?"))# 第一和第二项n1 = 0n2 = 1count = 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。

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

实例(Python 3.0+)

# Filename : test.py# author by : www.runoob.com# Python 检测用户输入的数字是否为阿姆斯特朗数# 获取用户输入的数字num = int(input("请输入一个数字: "))# 初始化变量 sumsum = 0# 指数n = len(str(num))# 检测temp = numwhile temp > 0: digit = temp % 10 sum += digit ** n temp //= 10

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

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

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

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

实例(Python 3.0+)

# 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

 ifnum == sum:  print(num)

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

最小值: 1最大值: 10000123456789153370371407163482089474

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

原文地址:https://www.cnblogs.com/sha777/p/10976981.html

时间: 2024-08-03 11:54:45

Python3 实例的相关文章

Python3 实例(二)

Python 判断字符串是否为数字 以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字: 实例(Python 3.0+) -- coding: UTF-8 -- Filename : test.py author by : www.runoob.com def is_number(s):try: float(s)return Trueexcept ValueError: pass try: import unicodedata unicodedata.numeric(

Python3 实例(三)

Python 十进制转二进制.八进制.十六进制 以下代码用于实现十进制转二进制.八进制.十六进制: 实例(Python 3.0+) -- coding: UTF-8 -- Filename : test.py author by : www.runoob.com 获取用户输入十进制数 dec = int(input("输入数字:")) print("十进制数为:", dec)print("转换为二进制为:", bin(dec))print(&qu

Python3 实例(八)

Python 归并排序 归并排序(英语:Merge sort,或mergesort),是创建在归并操作上的一种有效的排序算法.该算法是采用分治法(Divide and Conquer)的一个非常典型的应用. 分治法: 分割:递归地把当前序列平均分割成两半. 集成:在保持元素顺序的同时将上一步得到的子序列集成到一起(归并). 实例 def merge(arr, l, m, r): n1 = m - l + 1n2 = r- m # 创建临时数组 L = [0] * (n1) R = [0] * (

Python3 实例(一)

Python Hello World 实例 以下实例为学习Python的第一个实例,即如何输出"Hello World!": 实例 -- coding: UTF-8 -- Filename : helloworld.py author by : www.runoob.com 该实例输出 Hello World! print('Hello World!')执行以上代码输出结果为: Hello World!Python 数字求和 以下实例为通过用户输入两个数字,并计算两个数字之和: 实例(

Python3 实例(五)

Python 翻转列表 定义一个列表,并将它翻转. 例如,对调第一个和第三个元素: 翻转前 : list = [10, 11, 12, 13, 14, 15]翻转后 : [15, 14, 13, 12, 11, 10]实例 1 def Reverse(lst): return [ele for ele in reversed(lst)] lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst)) 以上实例输出结果为: [15, 14, 13, 12, 1

Python3 实例(六)

Python 判断字符串是否存在子字符串 给定一个字符串,然后判断指定的子字符串是否存在于改字符串中. 实例 def check(string, sub_str): if (string.find(sub_str) == -1): print("不存在!") else: print("存在!") string = "www.runoob.com"sub_str ="runoob"check(string, sub_str)执行

django python3 实例 mysql数据库

views.py中代码: def show_all_user(req): num=1 if 'pagenum' in req.POST: num=req.POST['pagenum'] tlist=User.objects.all() p=Paginator(tlist,30) page=p.page(num) return render_to_response('show_all_user.html',{'all_user':page.object_list,'pagenum':num,'to

python3实例

1.一行代码求一个数的阶乘 例如:求5的阶乘 from functools import reduce print((lambda k: reduce(int.__mul__, range(1, k+1), 1))(5)) 借鉴:https://www.cnblogs.com/QI1125/p/7496129.html 原文地址:https://www.cnblogs.com/yjt1993/p/10364461.html

Python基础之 一 字符编码及转换

python2 / python3编码转换 先上图一张: 说明:python编码转换的流程是 先进行decode解码,然后进行encode编码 解释: u'你好'  -->带u表示为unicode编码 b'\xc4\xe3\xba\xc3'   --> 带b的表示bytes类型由于utf8 是unicode的扩展,所以unicode和utf8之间是可以直接打印 注意:所有decode动作都是将已编码文件解码为unicode,然后在进行其他编码格式转换(通过encode) 直接举例说明:#pyt