Python基础(1)
一、行和缩进
Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。
缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。如:
1 if True: 2 print("True") 3 else: 4 print("False")
二、输入
Python提供了一个input()
,可以让用户输入字符串,并存放到一个变量里。比如输入用户的名字:
>>> name = input('您的名字:') 您的名字: >>> name = input('您的名字:') 您的名字:yaoyao >>> name 'yaoyao'
三、Python变量命名规则
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线开头,但不能以数字开头,例如,可将变量命名为message_1,但不能将其命名为1_message。
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
- 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print。
- 变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。
- 慎用小写字母l和大写字母O,因给他们可能被人错看成数字1和0;
注意:应使用小写的Python变量名。在变量名中使用大写字母虽然不会导致错误,但避免使用大写字母是个不错的注意。
四、条件语句
1、一个简单的if语句:
1 username1 = 'Tim' 2 password1 = 'abc123' 3 4 username = input("username:") 5 password = input("password:") 6 7 if username == username1 and password == password1: 8 print("Congratulations,You have logon!")
输入Tim abc123后,结果如下:
username:Tim
password:abc123
Congratulations,You have logon!
2、if...else语句:
1 username1 = 'Tim' 2 password1 = 'abc123' 3 4 username = input("username:") 5 password = input("password:") 6 7 if username == _username1: 8 print("username is correct...") 9 if password == password1: 10 print("Congratulations,You have logon!") 11 12 else: 13 print("password is invalid...") 14 15 else: 16 print("your username is not correct...")
输入Tim,abc123后结果:
username:Tim password:abc123 username is correct... Congratulations,You have logon!
输入用户名正确,密码不正确如下:
username:Tim password:123 username is correct... password is invalid...
输入用户名不正确,如下:
username:king password:123 your username is not correct...
五、while循环
1、基本循环
1 while 条件: 2 3 # 循环体 4 5 # 如果条件为真,那么循环体则执行 6 # 如果条件为假,那么循环体不执行
2、break
break用于退出所有循环
1 while True: 2 print("123") 3 break 4 print("456")
输出:
123
3、continue
continue用于退出当前循环,继续下一次循环
1 while True: 2 print("123") 3 continue 4 print("456")
输出:
123 123
。。。(无限循环)