Python教程

来源:互联网 发布:linux编程入门 编辑:程序博客网 时间:2024/05/30 04:46

1.Python基础

Python的语法比较简单,采用缩进方式,写出来的代码就像下面的样子:

# print absolute value of an integer:a = 100if a >= 0:    print(a)else:    print(-a)

当语句以冒号:结尾时,缩进的语句视为代码块。

python问题:IndentationError:expected an indented block错误

>>> if age>=18:... print('your age is',age)  File "<stdin>", line 2    print('your age is',age)        ^IndentationError: expected an indented block

在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。

代码修改以后如下:

 if age >=18:...     print('your age is',age)...     print('adult')... else:...     print('your age is', age)...     print('teenager')...your age is 3teenager

在C++中我们使用的是
if <条件判断1>:    <执行1>else if <条件判断2>:    <执行2>else if <条件判断3>:    <执行3>else:    <执行4>
但是python中使用的是:
if <条件判断1>:    <执行1>elif <条件判断2>:    <执行2>elif <条件判断3>:    <执行3>else:    <执行4>

再议 input

错误:
birth = input('birth: ')if birth < 2000:    print('00前')else:    print('00后')
正确:
s = input('birth: ')birth = int(s)if birth < 2000:    print('00前')else:    print('00后')
input()返回的数据类型是strstr不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情:


练习

小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:

  • 低于18.5:过轻
  • 18.5-25:正常
  • 25-28:过重
  • 28-32:肥胖
  • 高于32:严重肥胖

if-elif判断并打印结果:


>>> height=1.75>>> weight=80.5>>> bmi=weight/(height*height)>>> if bmi < 18.5:...     print('过轻')... elif bmi < 25:...     print('正常')... elif bmi < 28:...     print('过重')... elif bmi < 32:...     print('肥胖')... else:...     print('严重肥胖')...过重

2.循环

Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句。

range()函数,可以生成一个整数序列,再通过list()函数可以转换为list。比如range(5)生成的序列是从0开始小于5的整数:

>>> list(range(5))[0, 1, 2, 3, 4]


计算1-100的整数之和:

>>> sum=0>>> for x in range(101):...     sum=sum+x...     print(sum)


练习

请利用循环依次对list中的每个名字打印出Hello, xxx!

# -*- coding: utf-8 -*-L = ['Bart', 'Lisa', 'Adam']
答案:
>>> L=['Bart', 'Lisa', 'Adam']>>> for x in L:...     print('Hello', x)...Hello BartHello LisaHello Adam

使用dict和set












0 0
原创粉丝点击