Python初学关键字,运算符,%,while,for循环基础

本文详细介绍了Python的基础语法,包括常见关键字、条件语句、循环结构、数据类型如列表、元组和字典的使用,以及基本的输入输出操作。同时,还展示了算术运算符、比较和逻辑操作符的使用,适合初学者入门。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python常见关键字

and not or in del def for with 
if elif else while except try 
continue global raise 
assert finally  break 
pass  return  is  except  lambda yield
import from
exec  print

python 输出 hello world

[root@proxy ~]# vim hello.py 
#!/usr/bin/env python          #定义环境
#coding=utf-8                  #定义中文字符
print "hello world"
print "你好,世界"
[root@proxy ~]#  python hello.py 
hello world
你好,世界

>>> print 'hello world'  # one comment    //用#表示注释
hello world

In [8]  :   print("hello world")           这个是python3.0的格式(用Jupyter Notebook)

hello world 

函数abs() 接受一个数值,并输出这个数的绝对值

>>> abs(4)
4
>>> abs(-4)
4
>>> 

可以把一个字符串赋值给一个变量,先用print显示这个值,在用变量名称来显示

>>> mystring='This is a string'
>>> print mystring
This is a string
>>> mystring
'This is a string'
>>> _                                  //下划线在解释器中可以表示最后一个表达式的值
'This is a string'

print还可以与%(字符串格式操作符)结合使用,可以实现子替换功能,%s、%d、%f 分别表示由字符串、整型、浮点型替换

也支持将输出重定向到文件 用>>符号表示

>>> print "%s is number %d!" % ("Python",1)
Python is number 1!
>>> counter = 0
>>> miles = 1000.0
>>> name = 'Bob'
>>> counter = counter + 1
>>> kilometers = 1.609 * miles
>>> print '%f miles  is the same as %f km' % (miles,kilometers)
1000.000000 miles  is the same as 1609.000000 km
>>> print "%s is number %f!" % ("Python",1.0)
Python is number 1.000000!

import sys
>>> print >> sys.stderr, 'Fanal error:invalid input!'    //重定向到标准错误输出
Fanal error:invalid input!

logfile = open('/tmp/mylog.txt','a')                      //输出重定向到日志文件
>>> print >> logfile,'Fanal error:invalid input!'
logfile.close()


raw_input()内建函数,可以读取标准输入,并将读取的数据赋值指定变量,还可以使用int()内建函数将输入的字符串转换为整型

>>> user = raw_input('Enter login name:')
Enter login name:root
>>> print 'Your login is:',user
Your login is: root

>>> num = raw_input('Now enter a number:')
Now enter a number:1024
>>> print 'Doubling your number: %d' % (int(num) * 2)
Doubling your number: 2048
>>> help(raw_input)              //可以查看帮助

运算符  + - *  /(真正的除法)   //(地板除,取比商小的最大整数)   优先级 乘方 ** 最高  其次 * /  最后 + -

标准比较操作符 < <=    >     >=   ==    != (<>)     逻辑操作符  and or  not   布尔值 True(1) False(0)

>>> print -2 * 4 + 3 ** 3 
19
>>> 31.54 // 3.8
8.0
>>> 31.54 / 3.8
8.3
>>> 2 > 4
False
>>> 2 < 4
True
>>> 6.2 <= 6.9
True
>>> 6.2 >= 6
True
>>> 10.0 / 3   !=  10 / 3
True
>>> 10 / 3   !=  10 / 3
False
>>> 10.0 / 3
3.3333333333333335
>>> 10 / 3
3
>>> 4 > 2 or   3 > 5
True
>>> 4 > 2 and   3 > 5
False
>>> not 3 < 5
False
>>> 3 < 4 < 5  
True
>>> True + 1
2
>>> False + 1
1
>>> 

 列表和元组均属于数组,默认索引由0开始,列表用[ ]表示,个数和元素的值可以改变。元组用()表示,不可以更改,可以看成是只读的列表。可以用[ ])([ : ]切片运算得到子集,字典由键值key-value构成,用{ }包裹

>>> aList = [1,2,3,4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[1]=5\
...
KeyboardInterrupt
>>> aList[1]=5
>>> aList
[1, 5, 3, 4]

>>> aTuple = ('robots',77,93,'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[3]
'try'
>>> aTuple[:2]
('robots', 77)
>>> aTuple[0]  = 'machine'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


>>> aDict = {'host' : 'earth'}
>>> aDict['port'] = 443
>>> aDict
{'host': 'earth', 'port': 443}
>>> aDict.keys()
['host', 'port']
>>> for key in aDict :
...   print key,aDict[key]
...
host earth
port 443
>>>

python的代码块通过缩进对齐表达式来表达代码逻辑 python的两大特性:简洁,可读性好

while循环 while_suite 会被连续不断的执行 ,直到表达式的值变为0或者False 

>>> counter = 0
>>> while counter < 3 :
...   print 'loop #%d' % (counter)
...   counter += 1
...
loop #0
loop #1
loop #2
>>>

for循环 

[root@proxy ~]# vim for.py
#!/usr/bin/env python
print 'I like to use the Internet for: '
for item in ['e-mail','net-surfing','chat','homework']:
    print item ,
print

[root@proxy ~]# python for.py
I like to use the Internet for:
e-mail net-surfing chat homework
>>> for earchnumber in range(3):             //range()内建函数
...   print earchnumber ,
...
0 1 2


>>> foo = 'abcd'
>>> for i in range(len(foo)):
...   print foo[i] , '(%d)' % 1
...
a (1)
b (1)
c (1)
d (1)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值