天天看点

python3字符串转数字_Python3 实例(二)Python 判断字符串是否为数字Python 判断奇数偶数Python 判断闰年Python 获取最大值函数

python3字符串转数字_Python3 实例(二)Python 判断字符串是否为数字Python 判断奇数偶数Python 判断闰年Python 获取最大值函数

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 最大值为: