第一范文网 - 专业文章范例文档资料分享平台

python语言经典基础级案例(含源代码)

来源:用户分享 时间:2025/6/6 17:37:47 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

python语言经典案例(基础级)

案例1:

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析:利用 while 或 for 语句,条件为输入的字符不为 '\\n'。

实例 - 使用 while 循环

#!/usr/bin/python

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

import string

s = raw_input('请输入一个字符串:\\n') letters = 0 space = 0 digit = 0 others = 0 i=0

while i < len(s): c = s[i] i += 1

if c.isalpha(): letters += 1 elif c.isspace(): space += 1 elif c.isdigit(): digit += 1 else:

others += 1

print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)

实例 - 使用 for 循环 #!/usr/bin/python

-

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

import string

s = raw_input('请输入一个字符串:\\n') letters = 0 space = 0 digit = 0 others = 0 for c in s:

if c.isalpha(): letters += 1 elif c.isspace(): space += 1 elif c.isdigit(): digit += 1 else:

others += 1

print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)

以上实例输出结果为:

请输入一个字符串: 123runoobc kdf235*(dfl char = 13,space = 2,digit = 6,others = 2

案例2:

题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

程序分析:无 程序源代码:

欢迎下载

2

-

Python 实例

#!/usr/bin/python

# -*- coding: UTF-8 -*- tour = [] height = []

hei = 100.0 # 起始高度 tim = 10 # 次数

for i in range(1, tim + 1):

# 从第二次开始,落地时的距离应该是反弹高度乘以2(弹到最高点再落下)

if i == 1:

tour.append(hei) else:

tour.append(2*hei) hei /= 2

height.append(hei)

print('总高度:tour = {0}'.format(sum(tour)))

print('第10次反弹高度:height = {0}'.format(height[-1]))

以上实例输出结果为:

总高度:tour = 299.609375

第10次反弹高度:height = 0.09765625

案例3:

两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。

程序源代码:

欢迎下载

3

搜索更多关于: python语言经典基础级案例(含源代码) 的文档
python语言经典基础级案例(含源代码).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c1xgkr9gvut6zh7s4eqk6667gj1yjqg01cjj_1.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top