Python基础——语法简介

前言:

python的学习纯粹是出于好奇与乐趣,为什么呢?因为python被说的出神入化,掌握了有史以来最优秀的C语言(几乎所有操系统都是由C语言编写的)及扩展的C++语言,总觉得还差点什么,或许python是一个好的选择,Python语言可以作为胶水语言,可以方便的嵌入C/C++。in a word,we need python!

标识符

  • 第一个字符必须是字母表中字母或下划线 _ 。
  • 标识符的其他的部分由字母、数字和下划线组成。
  • 标识符对大小写敏感。

在 Python 3 中,非 ASCII 标识符也是允许的了。

python保留字

保留字即关键字,我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:

D:\Python3\demo1>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

注释

Python中单行注释以 # 开头,实例如下:

#打印字符串,print在python3中已经是一个函数
print("hello python")

多行注释可以用多个 # 号,还有 ''' 和 """:

"""
li = 'lily i love you'

hi = "it's a long story"
"""

行与缩进

python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。

缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:

a = 3

if a==3:
    print("a = ",  a)
else:
    print("a != 3")
   print(a)    #IndentationError: unindent does not match any outer indentation level

print(a)没有严格对齐,python识别不出是哪一个级别的语句

多行语句

Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠(\)来实现多行语句,例如:

a = 3;b = 4;c = 5

total = a +\
        b +\
        c

print("total = ",total)

多条语句在同一行,可以用分号";"隔开

python基本数据类型

Python3 中有六个标准的数据类型:

  • Number(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Sets(集合)
  • Dictionary(字典)

Number(数字)

Python3 支持 int、float、bool、complex(复数)

在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。

像大多数语言一样,数值类型的赋值和计算都是很直观的。

内置的type()函数可以用来查询变量所指的对象类型。

  • int (整数), 如 1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
  • bool (布尔), 如 True。
  • float (浮点数), 如 1.23、3E-2
  • complex (复数), 如 1 + 2j、 1.1 + 2.2j

例子:

a = 3;b = 4;c = 5.1; d = 7 + 8j

total = a +\
        b +\
        c + \
        d

print("total = ",total)

print(type(a),type(b),type(c),type(d),type(total))

结果:

total =  (19.1+8j)
<class 'int'> <class 'int'> <class 'float'> <class 'complex'> <class 'complex'>

字符串(String)

  • python中单引号和双引号使用完全相同。
  • 使用三引号('''或""")可以指定一个多行字符串。
  • 转义符 '\'
  • 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n" 则\n会显示,并不是换行。
  • 按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
  • 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
  • Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
  • Python中的字符串不能改变。
  • Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
  • 字符串的截取的语法格式如下:变量[头下标:尾下标]

空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:空行也是程序代码的一部分。

用户输入

1.input

函数input()的工作原理,函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在 一个变量中,以方便你使用。 示例代码如下:输入的类型是字符

函数功能:接受一个标准输入数据,返回string类型。ctrl+z结束输入。

默认input():等待一个任意字符的输入

str = input('input a string:\n')

print("str =", str)

x = input('input a int num for x:');
y = input('input a int num for y:');

print(type(x),type(y));
print("x = ", x)
print("y = ", y)

结果:

input a string:
i love lily
str = i love lily
input a int num for x:3 + 2i
input a int num for y:9
<class 'str'> <class 'str'>
x =  3 + 2i
y =  9

接受多个数据输入,使用eval()函数,间隔符必须是逗号

print("input 3 characters")
x,y,z = eval(input())

print("x = , y = , z = ", x, y,z)

input 3 characters
3+4j,7,10
x = , y = , z =  (3+4j) 7 10

2.使用int()来获取数值输入,在上面的简单示例代码中是用户输入一个字符串,然后得到的也为一个字符串,如果用户需要输入一个数值的话,就会导致出现问题,如下面代码所示:float 同理

age = int(input("input your age:"))
#age = int(age)  #获取数值

print("your age is", age)
print(type(age))
if age > 18:
    print("You are the adult!")
else:
    print("You are not adult!")

score = int(input("input your score:"))
#score = float(score)
print(type(score))

使用input ,float 类型来转换输入类型

测试文件

#! /usr/bin/env python3

#打印字符串,print在python3中已经是一个函数
print("hello python")

a = 3

if a==3:
    print("a = ",  a)
else:
    print("a != 3")
   #print(a)


li = 'lily i love you'

hi = "it's a long story"


print(li)
print(li[0:-1]) #输出第一个到倒数第二个的所有字符
print(li[2:5])  #输出从第三个开始到第五个的字符,包括2,但是不包括5
print(li[2:])   #输出从第三个开始的所有字符
print(li *2 )    #输出字符两次

li += 'r sister'    #连接字符串
print(li)


a = 3;b = 4;c = 5.1; d = 7 + 8j

total = a +\
        b +\
        c + \
        d

print("total = ",total)

print(type(a),type(b),type(c),type(d),type(total))



"""
str = input('input a string:\n')

print("str =", str)

x = input('input a int num for x:');
y = input('input a int num for y:');

print(type(x),type(y));
print("x = ", x)
print("y = ", y)
"""
'''
print("input 3 characters")
x,y,z = eval(input())

print("x = , y = , z = ", x, y,z)
'''
age = int(input("input your age:"))
#age = int(age)  #获取数值

print("your age is", age)
print(type(age))
if age > 18:
    print("You are the adult!")
else:
    print("You are not adult!")

score = int(input("input your score:"))
#score = float(score)
print(type(score))

Print 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""

#!/usr/bin/python3
 
x="a"
y="b"
# 换行输出
print( x )
print( y )
 
print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值