前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python基本概念

Python基本概念

作者头像
py3study
发布2020-01-13 20:10:24
4660
发布2020-01-13 20:10:24
举报
文章被收录于专栏:python3python3

一 基本概念

1 字面意义上的常量,如2、‘This is ok'这样的字符串

>>> print('a,2,3')

a,2,3

2 字符串

  • 单引号(‘) 使用单引号指示字符串,类似shell中的强引用,所有的空格、制表符照原样保留。

>>> print('This is ok')

This is ok

print 'I\'d mouch you \'not\'.' 也可以这样表示: print "I'd mouch you 'not'."

print 'I "said" do not touch this.'

备注:注意单引号和双引号的混合使用

  • 双引号(“) 在双引号中的字符串与单引号中的字符串使用完全相同

>>> print("This is ok")

This is ok

  • 三引号(''') 利用三引号,可以指示一个多行的字符串,可以在三引号中自由的使用单引号和双引号。

>>> '''This is am string.This is the first line.

... This is the second line.

... "What's your name?" Lasked.

... He said "Bond,JamesBond."'''

'This is am string.This is the first line.\nThis is the second line.\n"What\'s your name?" Lasked.\nHe said "Bond,JamesBond."'

  • 转义符

>>> 'what \'s your name'            #在单引号中实现单引号的使用

"what 's your name"

或使用双引号

>>> "what'your name"

"what'your name"

>>> "This is \"ok\","               #双引号中实现双引号的引用

'This is "ok",'

备注:行尾单独反斜杠,表示字符串在下一行继续,如:

>>> 'This is ok\

... ,hello'

'This is ok,hello'

  • 自然字符串 如果不需要转义符那样特别处理的字符串,那么可以给字符串加上前缀r或R来指定一个自然字符串

>>> r'New line are by \n'

'New line are by \\n'

3 对象:python在程序中把用到的任何东西都称为对象。

4 变量:

>>> i=100;print(i);

100

5 缩进:每个缩进层次使用2个或4个空格或单个制表符,使用其中的一种风格并且一值使用它。

二 表达式:Python大多数语句都包含表达式,如2+3,一个表达式可以分解为运算符和操作数。在上面的例子中,+为运算符,2和3为操作数。

示例:

>>> 2+3

5

>>> 3+3*2

9

三 控制流:

1 if语句

#!/bin/env python

number=23

guess=int(raw_input('Enter an integer: '))

if guess==number:

  print 'Congratulations,you guessed it.'

  print "(but you do not win any prizes!)"

elif guess<number:

  print 'No,it is a little highers than that'

else:

  print 'No,it is a little lower than that'

print 'Done'

2 for语句:

#!/bin/env python

for i in range(1,5):

  print i

else:

  print 'The for loop is over'

3 while语句

#!/bin/env python

number=23

running=True

while running:

  guess=int(raw_input('Enter an integer:'))

  if guess==number:

    print 'Congratulations,you guessedit.'

    running=False

  elif guess<number:

    print 'No,it is a little higher than that'

  else:

    print 'No,it is a little lower than that'

else:

  print 'The while loop is over.'

print 'Done'

四 函数:函数是重复使用的程序段,并且可以在你的程序的任何地方使用,这被称为调用函数。在Python中有许多的内建函数,如len()。

函数通过def定义,示例如下:

#!/bin/env python

def abc():

  print'This is abc'

abc()

五 关于编码:通常情况下,在Python程序中,不应有中文,如果要有的话,需要添加以下参数:

#!/bin/env python

#-- coding:utf-8 --

#chickents:

print "I will now count my chickents:"

#计算数值:

print "Hens", 25 + 30 /6

print "Roosters", 100 - 25 * 3 % 4

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档