1.进入python世界
print('Hello World')
2.变量名的使用
#!/user/bin/env python3 # -*- coding:utf-8 -*- user_name = 'Roy Chen'
第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释;
第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。
变量名的规则:
变量名只能是 字母、数字或下划线的任意组合
变量名的第一个字符不能是数字
以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
3.变量的赋值
#!/user/bin/env python3 # -*- coding:utf-8 -*-
a = 3 b = a print (a, b) a = 4 print(a, b)
a赋值3,b指向a为3,当a改为4时,b还是3,b只是通过a赋值为3,无论a怎么改变,b依然是3.
4.注释
# 当行注释
‘’‘ 多行注释 ’‘’
5.用户输入
#!/user/bin/env python3 # -*- coding:utf-8 -*-
name = input('input your name:') print('Hello', name)
加密输入可用 .getpass方法
#!/user/bin/env python3 # -*- coding:utf-8 -*- import getpass password = getpass.getpass('输入密码:') print(password)
在pycharm中无法实现,只能在命令行中使用。
6.数据类型
int:整型,即整数。
float:浮点型,即小数。
布尔值:True or False
str:字符串
7.for 循环
#!/user/bin/env python3 # -*- coding:utf-8 -*- for i in range(10): #遍历0~9 if i < 3: print(i) else: continue # continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续 进行下一轮循环。 print('hehe')
#!/user/bin/env python3 # -*- coding:utf-8 -*-
for i in range(10): print('-------', i) for j in range(10): print(j) if j > 5: break
8.占位符,%s 和 .format
#!/user/bin/env python3 # -*- coding:utf-8 -*-
name = 'lil'
age = 23
heigh = 1.78
print('my name is %s, i am %d years old,heigh is %.2f.' % (name, age, heigh))
print('My name is {}, I am {} years old,heigh is {}'.format(name, age, heigh))
%s 表示字符串, %d 表示整数,,%f表示小数, %.2f 保留小数点后2位数的小数
9.练习:猜数字游戏
#!/user/bin/env python3 # -*- coding:utf-8 -*- age = 53 count = 0 while count < 3: guess = int(input('guess:')) if guess == age: print('yes you got it...') break elif guess > age: print('think smaller...') else: print('think bigger...') count += 1 if count == 3: continue_confirm = input('do you want to continue?') if continue_confirm != 'n': count = 0