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 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 判断奇数偶数

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

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

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

输入一个数字: 3
3 是奇数
笔记

优化加入输入判断:

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

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

输入一个年份: 2000
2000 是闰年
输入一个年份: 2011
2011 不是闰年
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))
执行以上代码输出结果为:

2
b
2
2
80, 100, 1000 最大值为: 1000
-20, 100, 400最大值为: 400
-80, -20, -10最大值为: -10
0, 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("请输入一个数字: "))

质数大于 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
请输入一个数字: 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输入区间最大值: 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
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 实现斐波那契数列代码如下:

实例(Python 3.0+)

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

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

实例(Python 3.0+)

Filename : test.py

author by : www.runoob.com

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

获取用户输入的数字

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

初始化变量

sumsum = 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 是阿姆斯特朗数
获取指定期间内的阿姆斯特朗数

实例(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
最大值: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
以上实例中我们输出了 1 到 10000 之间的阿姆斯特朗数。

好了,本文就给大伙分享到这里,文末分享一波福利

获取方式:加python群 839383765 即可获取!

原文地址:https://blog.51cto.com/14186420/2404797

时间: 2024-08-29 23:55:06

Python3 实例(二)的相关文章

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

DWR入门实例(二)

DWR(Direct Web Remoting) DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. Dwr能让在服务器端的java代码和浏览器客户端的javascript代码尽可能简单的相互调用. DWR is Easy Ajax for Java!  官网:http://d

Hibernate实例二

Hibernate实例二 一.测试openSession方法和getCurrentSession方法 hebernate中可以通过上述两种方法获取session对象以对数据库进行操作,下面的代码以及注解是对两种方法的辨析 SessionTest.java 1 import java.sql.Connection; 2 import java.sql.SQLException; 3 import java.util.Date; 4 5 import org.hibernate.Session; 6

Linux DNS的主从服务器配置实例(二)

在主DNS服务器运行正常的情况下,在另外的一台与之相同的服务器上配置从DNS服务器:操作如下: 我们这里创建DNS从服务器是实验,没有注册,,实际工作中需要注册才能正常使用,明白!!嘻嘻你懂得! 从服务器配置前提调试:(网络必须相同,小孩都知道的!)  1.统一时间  #ntpdate 172.16.0.1 -----指定时间服务器地址(瞬间跟新时间)  #corntab -e----------------------计划任务可以设置定期更新   */3 * * * * /sbin/ntpda

c#事件实例二

c#事件实例二 事件驱动程序与过程式程序最大的不同就在于,程序不再不停地检查输入设备,而是呆着不动,等待消息的到来,每个输入的消息会被排进队列,等待程序处理它.如果没有消息在等待, 则程序会把控制交回给操作系统,以运行其他程序. 操作系统只是简单地将消息传送给对象,由对象的事件驱动程序确定事件的处理方法.操作系统不必知道程序的内部工作机制,只是需要知道如何与对象进行对话,也就是如何传递消息. 先来看看事件编程有哪些好处. 1.使用事件,可以很方便地确定程序执行顺序. 2.当事件驱动程序等待事件时

C语言库函数大全及应用实例二

原文:C语言库函数大全及应用实例二                                              [编程资料]C语言库函数大全及应用实例二 函数名: bioskey 功 能: 直接使用BIOS服务的键盘接口 用 法: int bioskey(int cmd); 程序例: #i nclude #i nclude #i nclude #define RIGHT 0x01 #define LEFT 0x02 #define CTRL 0x04 #define ALT 0x0

Json转换利器Gson之实例二-Gson注解和GsonBuilder

有时候我们不需要把实体的所有属性都导出,只想把一部分属性导出为Json. 有时候我们的实体类会随着版本的升级而修改. 有时候我们想对输出的json默认排好格式. ... ... 请看下面的例子吧: 实体类: [java] view plaincopy import java.util.Date; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public 

WPF中的多进程(Threading)处理实例(二)

原文:WPF中的多进程(Threading)处理实例(二) 1 //错误的处理 2 private void cmdBreakRules_Click(object sender, RoutedEventArgs e) 3 { 4 Thread thread = new Thread(UpdateTextWrong); 5 thread.Start(); 6 } 7 8 private void UpdateTextWrong() 9 { 10 txt.Text = "Here is some n

Android笔记三十四.Service综合实例二

综合实例2:client訪问远程Service服务 实现:通过一个button来获取远程Service的状态,并显示在两个文本框中. 思路:如果A应用须要与B应用进行通信,调用B应用中的getName().getAuthor()方法,B应用以Service方式向A应用提供服务.所以.我们能够将A应用看成是client,B应用为服务端,分别命名为AILDClient.AILDServer. 一.服务端应用程序 1.src/com.example.aildserver/song.aidl:AILD文