栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

高中信息技术教资考试-Python程序设计(二)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

高中信息技术教资考试-Python程序设计(二)

一、选择结构程序设计

无( )与{ },用冒号:和缩进执行

【例1】

1、c++

#include
using namespace std;
int main()
{
	double x=0, total=0;
	cin>>x;
	if(x<2.5)
	total=8.4*x;
	else
	total=7.6*x;
	cout<<"共花费"< 

2、Python

注意:Python无double只有float

>>> x=float(input())
3
>>> if x<2.5:
...     print("总价为:",8.4*x)
... else:
...     print("总价为:",7.6*x)
...
总价为: 22.799999999999997

以上两种写法采用最简单的if-else样式均未考虑输入错误数据,如负数时的情况。

正确写法应该采用if-else的嵌套,如下所示:

#include
using namespace std;
int main()
{
	double x=0, total=0;
	cin>>x;
	if(x>0)
	{
		if(x<2.5)
			total=8.4*x;
		else
			total=7.6*x;
		cout<<"共花费"< 

二、循环结构程序设计[Python 无 i++、i--]

1、while循环(无( )与{ },用冒号:和缩进执行)

:循环条件

缩进——>条件为真执行缩进,为假执行未缩进

【例2.1】编写程序,求s=1+2+3+……+100的值

#include
using namespace std;
int main()
{
	int s=0,i=1;
	while(i<=100)
	{
		s=s+i;
		i++;
	 } 
	 cout< 
>>> s=0
>>> i=1
>>> while i<=100:
...     s=s+i
...     i=i+1
...
>>> print(s)
5050

2、for循环

for 变量名 in range(start,stop,step)

【例2.2】编写程序,求s=1+2+3+……+100的值

#include
using namespace std;
int main()
{
	int s=0;
	for(int i=1;i<=100;i++)
		s=s+i;
	cout< 
>>> s=0
>>> for i in range(1,101):
...     s=s+i
...
>>> print(s)
5050
>>>

【例3】

#include
using namespace std;
int main()
{
	int	i=0,flag=0;
	while(flag==0){
		if(i%3==2&&i%5==3&&i%7==2)
		{
			cout< 
>>> i=0
>>> flag=0
>>> while flag==0:
...     if i%3==2 and i%5==3 and i%7==2:
...             print(i)
...             flag=1
...     else:
...             i=i+1
...
23
>>>

三、自定义函数  def 函数名 (形参):

【例4】编写函数求两数中的较小数

#include
using namespace std;
int min(double a,double b){
	if(a>=b)
	return b;
	else
	return a;
}
int main()
{
	double x=0,y=0,t=0;
	cin>>x>>y;
	t=min(x,y);
	cout< 
>>> def min(a,b):
...     if a>=b:
...             return b
...     else:
...             return a
>>> x=float(input())
3
>>> y=float(input())
5
>>> z=min(x,y)
>>> print(z)
3.0

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号