python基础笔记1

参考书1:《python编程快速上手–让繁琐工作自动化》
参考书2:《python3程序开发指南》

ubuntu已经安装了python,python3

idle的环境是交互环境窗口,提示符是>>>,命令行窗口下,python/python3命令后加参数-V(大写的V)打印python/python3的版本

$ sudo apt-get install python3
$ sudo apt-get install idle3
$ sudo apt-get install python3-pip
$ python -V
Python 2.7.12
$ python3 -V
Python 3.5.2

ubuntu修复idle3清屏

  1. 网址https://bugs.python.org/file14303/ClearWindow.py下载ClearWindow.py
  2. sudo cp ClearWindow.py /usr/lib/python3.5/idlelib/
  3. sudo gedit /usr/lib/python3.5/idlelib/config-extensions.def
  4. 末尾加上:
[ClearWindow]
enable=1
enable_editor=0
enable_shell=1
[ClearWindow_cfgBindings]
clear-window=
  1. Ctrl-l 实现清屏

数学运算

操作符 操作 示例
** 指数运算 2**3 = 8
% 取模 25 % 8 = 1
// 整除 25 // 8 = 3
/ 除法 25 / 8 = 3.125
* 乘法 3 * 8 = 24
- 减法 10 - 1 = 9
+ 加法 9 + 1 = 10

a operator= b, a = a operator b,前者只查询一次a的值,更快

字符串复制

python的字符串是通过匹配的双引号、单引号括起来的文本,strs(/stirs/)

通过字符串+字符串–字符串连接,字符串*整型值–字符串复制整型值次

>>> "hello" + 'world]'
'helloworld]'
>>> 'alice' * 3
'alicealicealice'
>>> 'alice' * 'abc'
Traceback (most recent call last):
  File "", line 1, in 
    'alice' * 'abc'
TypeError: can't multiply sequence by non-int of type 'str'
>>> 'alice'*3.3
Traceback (most recent call last):
  File "", line 1, in 
    'alice'*3.3
TypeError: can't multiply sequence by non-int of type 'float'
>>> 3 * 'alice'
'alicealicealice'
>>> 3.5 * 'alice'
Traceback (most recent call last):
  File "", line 1, in 
    3.5 * 'alice'
TypeError: can't multiply sequence by non-int of type 'float'

变量

变量被使用,第一次存入一个值–初始化,不初始化会报错name‘ ’is not defined

之后的改写–赋值,变量可以指向不同类型

合法的变量名(与C/C++类似):
1. 变量名区分大小写,惯例用小写字母开头,名字具有描述性
2. 变量名只能包含字母、数字和下划线
3. 不能以数字开头

>>> hello
Traceback (most recent call last):
  File "", line 1, in 
    hello
NameError: name 'hello' is not defined
>>> hello = 'hello'*3
>>> hello
'hellohellohello'
>>> hello = 500
>>> hello
500
>>> hello = 3.3333
>>> hello
3.3333

python脚本

shebang行(shell执行行),首行头两个字节如果是ASCII字符#!,那么该脚本就由该行指定的解释器执行
1. 注释,#标志之后的该行文本
2. print()函数,将括号内的字符串显示在屏幕上
3. input()函数,等待用户在键盘上输入文本,返回用户输入的字符串

#! /usr/bin/python3
# 或者
#! /usr/bin/env python3

print()函数允许传入一个整型值、字符串、浮点、变量,下列的出错原因是,+只能用于操作两个数值类型,或两个字符串,不能让一个整数和字符串相加,整数应该转换为字符串

str(),int(),float()分别求值为传入值的字符串、整数和浮点数形式

>>> print('My age is ' + 25 + ' years old')
Traceback (most recent call last):
  File "", line 1, in 
    print('My age is ' + 25 + ' years old')
TypeError: Can't convert 'int' object to str implicitly
# 问题:下列语句在脚本中能正确执行,但是在idle3上报错
>>> hello = 'I am ' + str(25) + ' years old'
>>> hello
'I am 25 years old'
>>> print(hello)
Traceback (most recent call last):
  File "", line 1, in 
    print(hello)
TypeError: 'int' object is not callable

你可能感兴趣的:(python3,ubuntu)