博主上周起开始0基础自学python,每周都会更新一次自己的学习代码,请各位监督。

这里用的是Python3.x,用的是Mac电脑上自带的Python

 

一、var篇

在Unix下创建hello.py文件,输入


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

print
('Hello, world!')

然后输入执行命令: python hello.py,输出

XutekiMacBook-Pro:~ xumengyuan$ python hello.python
Hello, world!

ps:执行前,需给hello.py执行权限,chmod 755 hello.py

 

输出一个变量:

>>> name = 'Alex Li'
>>> print(name)
Alex Li

 

当将一个变量赋给另一个变量时,观察两个变量的输出结果:

>>> name_1 = 'Alex Li'
>>> name_2 = name_1
>>> name_1 = 'Xmy'
>>> print(name_1)
Xmy
>>> print(name_2)
Alex Li

 

可见改变初始变量name_1后,并不会影响被赋值的变量name_2的输出结果。

 

输出多行变量,用'''***''':

>>> msg='''
... print('hello world')
... name = 'Alex Li'
... print(name)
... '''
>>> print(msg)

print('hello world')
name = 'Alex Li'
print(name)

 

二、interaction篇

用input()函数打到交互效果

>>> name = input('name:')
name:Xmy
>>> print(name)
Xmy

 

现在,我们需要输入一个人的姓名、年龄、工作、薪水这些信息,可以用'''name'''+name的方式进行操作,具体如下:

>>> name = input('name:')
name:XMY
>>> age = input('age:')
age:24
>>> job = input('job:')
job:IT
>>> salary = input('salary:')
salary:2000
>>> info = '''
... -------------info of ''' + name + '''-----------
... name:''' + name + '''
... age:''' + str(age) + '''
... job: ''' + job + '''
... salary: ''' + salary
>>> print(info)

-------------info of XMY-----------
name:XMY
age:24
job: IT
salary: 2000

 

此外,我们还可以用%s的形式来进行操作

>>> info_2 = '''
... -------------info of %s -----------
... name:%s
... age:%d
... job:%s
... salary:%s
... ''' % (name,name,age,job,salary)
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
TypeError: %d format: a number is required, not str

这时,我们会发现,在age:之后我们家的是%d,即规定了后面必须要用number格式来进行输入,然而在一开始age = input('age:')中,age的格式是字符串,我们可以用int()对其紧张转换成整形

>>> info_2 = '''
... -------------info of %s -----------
... name:%s
... age:%d
... job:%s
... salary:%s
... ''' % (name,name,age,job,salary)
>>> print(info_2)

-------------info of XMY -----------
name:XMY
age:18
job:IT
salary:2000

转换成整形后,得出结果:

>>> age = input('age:')
age:18
>>> print(type(age))
<class 'str'>
>>> age = int(input('age:'))
age:18
>>> print(type(age))
<class 'int'>

 

此外,我们还可以用format进行输出,format的形式主要分为两种:

1.通过赋值:

>>> info_3 = '''
... -------------info of {_name} -----------
... name:{_name}
... age:{_age}
... job:{_job}
... salary:{_salary}
... '''.format(_name=name,
...            _age=age,
...            _job=job,
...            _salary=salary)
>>> print(info_3)

-------------info of XMY -----------
name:XMY
age:18
job:IT
salary:2000

2.通过指定位置:

>>> info_4 = '''
... -------------info of {0} -----------
... name:{0}
... age:{1}
... job:{2}
... salary:{3}
... '''.format(name,age,job,salary)
>>> print(info_4)

-------------info of XMY -----------
name:XMY
age:18
job:IT
salary:2000

ps:这里需要指出,在python中,位置是以0开始的。

 

三、if...else篇

 假如我们现在有一个登录界面,你已经注册号了用户名和密码,需要通过判断你输入的是否正确给出提示,我们可以通过if...else语句来实现:

>>> _username = 'Xmy'
>>> _password = 'Xmy123'
>>># 输入错误密码
>>> username = input('username:')
username:Xmy
>>> password = input('password:')
password:234 
>>> if _username == username and _password == password :
...     print("Welcome user {name} login ...".format(name=username))
... else:
...     print("Invalid username or password.")
... 
Invalid username or password.  # 密码或用户名错误
>>># 密码和用户名正确
>>> username = input('username:')
username:Xmy
>>> password = input('password:')
password:Xmy123
>>> if _username == username and _password == password :
...     print("Welcome user {name} login ...".format(name=username))
... else:
...     print("Invalid username or password.")
... 
Welcome user Xmy login ... # 欢迎登录

 

一般,我们登录界面的密码会显示成暗文,可以用getpass模块进行实现:

>>> import getpass
>>> username = input('username:')
username:Xmy
>>> password = getpass.getpass('password:') #在python中显示暗文
password:
>>> if _username == username and _password == password :
...     print("Welcome user {name} login ...".format(name=username))
... else:
...     print("Invalid username or password.")
... 
Welcome user Xmy login ...

 

四、while循环篇

 while是一种常见的循环,我们可以通过一个简单的例子来了解他的使用。

假定我们给一个初始变量赋值count赋值为0,通过while循环,让每一次循环给count加一,则可以这么实现:

count = 0
while True:
    print('count:',count)
    count += 1 # 相当于count = count+1

通过上述代码我们完成了循环目的,却发现这个循环无法结束,会一直运行下去,所以我们需要通过增加条件来终止这一段代码。

假定,我们希望在count=10时,结束代码,可以用break来实现:

>>> while True:
...     print('count:',count)
...     count += 1 # count = count+1
...     if count == 10:
...         break
... 
count: 0
count: 1
count: 2
count: 3
count: 4
count: 5
count: 6
count: 7
count: 8
count: 9

 

现在,我们初步了解了while的使用原理后,我们可以结合之前学习的if...else来完成一个小例子。

假设我们给定一个人的年龄,来猜测他的真实年龄,并给错误结果给出相应的提示,而猜的机会只有三次,超过三次猜错,则退出程序。

可以通过如下代码实现:

>>> age_of_oldboy = 56
>>> count = 0 >>> while count <3: ... guess_age = int(input('guess age:')) ... if guess_age == age_of_oldboy: ... print('yes, you got it!') ... break ... elif guess_age > age_of_oldboy: ... print('think smaller...') ... else: ... print('think bigger...') ... count += 1 ... else: ... print('you have tried too many times... Fuck off!') ... guess age:1 think bigger... guess age:7 think bigger... guess age:89 think smaller... you have tried too many times... Fuck off!

 

现在,我们队这个小程序做一些改进。

如果三次猜错后,会出现“是否要继续?”的提示,如果要继续,则回答y,重新进入循环,如果希望退出,则回答n,退出循环:

>>> age_of_oldboy = 56 
>>> count = 0
>>> while count <3:
...     guess_age = int(input('guess age:'))
...     if guess_age == age_of_oldboy:
...         print('yes, you got it!')
...         break
...     elif guess_age > age_of_oldboy:
...         print('think smaller...')
...     else:
...         print('think bigger...')
...     count += 1
...     if count == 3:
...         continue_confirm = input('Do you want ot keep trying?(y/n)')
...         if continue_confirm != 'n':
...             count = 0
... else:
...     print('you have tried too many times... Fuck off!')
... 
guess age:46
think bigger...
guess age:58
think smaller...
guess age:50
think bigger...
Do you want ot keep trying?(y/n)y
guess age:36
think bigger...
guess age:50
think bigger...
guess age:54
think bigger...
Do you want ot keep trying?(y/n)n
you have tried too many times... Fuck off!

 

五、for循环篇

for循环作为另一种十分常见的循环,相比while循环更为简洁:

>>> for i in range(10):
...     print('loop:',i)
... 
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9

在这里,需要对range()做一个特别的介绍,如果我们要取0-9中偶数可以写成range(0,10,2)

最后,我们用for循环来完成之前的拿到例题:

>>> age_of_oldboy = 56
>>> 
>>> 
>>> count = 0
>>> for i in range(3):
...     guess_age = int(input('guess age:'))
...     if guess_age == age_of_oldboy:
...         print('yes, you got it!')
...         break
...     elif guess_age > age_of_oldboy:
...         print('think smaller...')
...     else:
...         print('think bigger...')
... else:
...     print('you have tried too many times... Fuck off!')
... 
guess age:2
think bigger...
guess age:57
think smaller...
guess age:54
think bigger...
you have tried too many times... Fuck off!