Python编程快速上手第[1,2,3]章

第1章Python 基础

  • 在交互式环境中输入表达式
    IDLE 窗口现在应该显示下面这样的文本:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 2 + 2
4
>>>
  • 整型、浮点型和字符串数据类型
>>>int(4.555)
>>>float(4)
>>>str(1)
  • 字符串连接和复制
    "+"在用于两个字符串时,它将字符串连接起来,成为“字符串连接”操作符。
>>> 'Alice' + 'Bob'
'AliceBob'

*操作符用于一个字符串值和一个整型值时,它变成了“字符串复制”操作符。

>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
  • 在变量中保存值
  1. 赋值语句
>>> spam = 40
>>> spam
40
>>> eggs = 2
>>> spam + eggs
42
  1. 变量名
    你可以给变量取任何名字,只要它遵守以下 3 条规则:
    1.只能是一个词。
    2.只能包含字母、数字和下划线。
    3.不能以数字开头。
    本书的变量名使用了驼峰形式,没有用下划线。好的变量名描述了它包含的数据。
  • print()函数
  • input()函数
  • len()函数

第2章控制流

  • 布尔值(True/False)
  • 比较操作符
==等于
!=不等于
<小于
>大于
<=小于等于
>=大于等于
  • 布尔操作符
    1.二元布尔操作符(and/or)
    2.not 操作符
    Python 先求值 not 操作符,然后是 and 操作符,然后是 or 操作符。
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
  • 控制流语句
    if语句
    else语句
    elif语句
    while语句
    break语句
    continue语句
    for语句
    range()函数

while-else语句

count = 0
while count <= 5 :
    count += 1
    if count == 3:break
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
#当while中有break语句打断时,else不会执行。
#当while中没有被break语句打断时,else就会执行。
  • 导入模块
    import 关键字;
    模块的名称;
    可选的更多模块名称,之间用逗号隔开。
import random, sys, os, math

用 sys.exit()提前结束程序。
第3章函数
def 语句和参数:

def hello(name):
	print('Hello ' + name)
hello('Alice')
hello('Bob')

返回值和 return 语句:
return 关键字。
函数应该返回的值或表达式。

局部和全局作用域:
 全局作用域中的代码不能使用任何局部变量;
 但是,局部作用域可以访问全局变量;
 一个函数的局部作用域中的代码,不能使用其他局部作用域中的变量。
 如果在不同的作用域中,你可以用相同的名字命名不同的变量。也就是说,可
以有一个名为 spam 的局部变量,和一个名为 spam 的全局变量。

global 语句

def spam():
	global eggs
	eggs = 'spam'
eggs = 'gobal'
spam()
print(eggs)
def spam():
	global eggs
	eggs = 'spam' # this is the global
def bacon():
	eggs = 'bacon' # this is a local
def ham():
	print(eggs) # this is the global
eggs = 42 # this is the global
spam()
print(eggs

异常处理

def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
def spam(divideBy):
	return 42 / divideBy
try:
	print(spam(2))
	print(spam(12))
	print(spam(0))
	print(spam(1))
except ZeroDivisionError:
	print('Error: Invalid argument.')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值