python3 入门 (一) 基础语法

时间:2022-05-08
本文章向大家介绍python3 入门 (一) 基础语法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.编码问题

默认情况下,Python 3源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 也可以为源码文件指定不同的编码,在文件头部加上:

# coding=gbk

2.关键字

保留字即关键字,Python的标准库提供了一个keyword module,可以输出当前版本的所有关键字:

>>> import keyword
>>> keyword.kwlist

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

3.注释

Python中单行注释以#开头,多行注释用三个单引号(''')或者三个双引号(""")将注释括起来。

4.变量

Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建

Python 3支持int、float、bool、complex(复数)。

数值运算:

  • Python可以同时为多个变量赋值,如a, b = 1, 2。
  • 一个变量可以通过赋值指向不同类型的对象。
  • 数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。
  • 在混合计算时,Python会把整型转换成为浮点数。

字符串:

python中的字符串str用单引号(' ')或双引号(" ")括起来,同时使用反斜杠()转义特殊字符

字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复

1 text = 'ice'+' cream'
2 print(text)
3 
4 text = 'ice cream '*3
5 print(text)

使用三引号('''...'''或"""...""")可以指定一个多行字符串

1 text = '''啦啦啦
2 喔呵呵呵呵
3 呵呵你妹'''
4 print(text)
5 text = 'ice
6         cream'
7 print(text)

如果不想让反斜杠发生转义,可以在字符串前面添加一个 r 或 R ,表示原始字符串。

如 r"this is a line with n" 则n会显示,并不是换行

1 text1 = r'E:notice'
2 text2 = "let's go!"
3 text3 = r'this is a line with n'
4 print(text1)  # E:notice
5 print(text2)  # let's go!
6 print(text3)  # this is a line with n

字符串有两种索引方式,第一种是从左往右,从0开始依次增加;第二种是从右往左,从-1开始依次减少。

python中没有单独的字符类型,一个字符就是长度为1的字符串

1 text = 'ice cream'
2 print(len(text))
3 
4 print(text[0])  # i
5 print(text[-9])  # i
6 
7 print(text[8])  # m
8 print(text[-1])  # m

python字符串不能被改变。向一个索引位置赋值会导致错误

1 text = 'ice cream'
2 text[0] = 't'  # 报错
3 print(text)

还可以对字符串进行切片,获取一段子串。用冒号分隔两个索引,形式为变量[头下标:尾下标]。

截取的范围是前闭后开的,并且两个索引都可以省略:

1 text = 'ice cream'
2 print(text[:3])  # ice
3 print(text[4:9])  # cream
4 print(text[4:])  # cream

5.三目运算符

1 x = 100
2 y = 200
3 z = x if x > y else y
4 print(z)  # 200

6.分支

if-else 语句与其他语言类似,不再赘述

if-elif-else 语句,相当于c或java语言中的if-else if-else :

 1 while True:
 2     score = int(input("Please input your score : "))
 3     if 90 <= score <= 100:
 4         print('A')
 5     elif score >= 80:
 6         print('B')
 7     elif score >= 70:
 8         print('C')
 9     elif score >= 60:
10         print('D')
11     else:
12         print('Your score is too low')

7.循环

while循环语句一般形式:

while 判断条件:

   statements

 1 import random
 2 
 3 print("hello world!n")
 4 number = random.randint(1, 10)
 5 temp = input("Please input a number : ")
 6 i = int(temp)
 7 
 8 while i != number:
 9     print("wrong...")
10     if i < number:
11         print("required a bigger number")
12     else:
13         print("required a smaller number")
14     temp = input("Please input a number : ")
15     i = int(temp)
16 
17 print("yes...")

for循环的一般格式如下:

for <variable> in <sequence>:

  <statements>

else:

  <statements>

1 languaegs = ['C','c++','java','python']
2 for language in languaegs:
3     print(language, len(language))

循环语句可以有else子句

它在穷尽列表(以for循环)或条件变为假(以while循环)循环终止时被执行

但循环被break终止时不执行.如下查寻质数的循环例子

1 for num in range(2, 10):
2     for x in range(2, num):
3         if num%x == 0:
4             print(num, 'equals', x, '*', num//x)
5             break
6     else:
7         # 循环中没有找到元素
8         print(num, 'is a prime number')

如果需要遍历数字序列,可以使用内置range()函数:

 1 # range()函数,含头不含尾
 2 # 0~4
 3 for i in range(5):
 4     print(i)
 5 
 6 # 2~7
 7 for i in range(2, 8):
 8     print(i)
 9 
10 # 1~9 步长为3
11 for i in range(1, 10, 3):
12     print(i)

range()函数与for循环结合:

1 languaegs = ['c','c++','java','python']
2 for i in range(len(languaegs)):
3     print(i, ':', languaegs[i])