Python3学习(一)

本文详细介绍了Python的基本用法,包括交互模式、变量定义、输入输出、条件语句、循环结构等核心概念。同时,深入探讨了Python2与Python3的差异,如输入功能的不同,以及数据类型和类型转换的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python的交互模式,ipython

python和ipython的区别是ipython不仅支持python语法,也支持shell指令

ubuntu@ubuntu-Lenovo:~$ ipython3 
Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: ls
11.txt                                Oracle_VM_VirtualBox_Extension_Pack-5.2.22.vbox-extpack
1.wav                                 Oracle_VM_VirtualBox_Extension_Pack-6.0.0.vbox-extpack
2.1.0.201909191925_RS/                Pictures/
2.1.0.201909191925_RS.rar             Public/
audio_log.sh*                         pychame_project/
AX2129_V005_20190830_DCC_sign/        ripgrep_11.0.2_amd64.deb
AX2129_V005_20190830_DCC_sign.zip     setup64*
AX2129_V006_20190917_DCC_sign/        share/
AX2129_V006_20190917_DCC_sign.zip     smartgit-19_1_5-2336c4e758ed42587f927f02537401d414ab0759.deb
bin/                                  sogoupinyin_2.2.0.0108_amd64.deb
brepo/                                Source Insight/
client.ovpn                           sourceinsight_proj/
Desktop/                              SP_Flash_Tool_exe_Linux_v5.1924.00.101/
Documents/                            SP_Flash_Tool_exe_Linux_v5.1928.01.100/
Downloads/                            SP_Flash_Tool_exe_Linux_v5.1928.01.100.zip

   #ubuntu下安装ipython version2
   sudo apt-get install ipython
   #ubuntu下安装ipython version3
   sudo apt-get install ipython3

python2的中文解决

python version 2不支持注释中有中文,怎么解决呢?
在代码的最前面添加

#coding=utf-8
或者
#-*- coding:utf-8 -*- #python推荐使用

python 注释

注释有三种写法:
1.井号#,#右边为注释的内容
2.’’'注释内容’‘’ #三个单引号之间
3.""“注释内容”"" #三个双引号之间

定义变量,使用变量

在一个程序中一个变量第一次出现,那边就是定义变量,之后在操作这个变量就是使用变量
比如:

 #coding=utf-8                                                                                   
 value = 10 #定义变量
 value = value + 10 #变量赋值使用
 print(value) #打印变量

输入输出

high = input("please input your high:")#输入
print("your high is %s" %high) # %high之前不能有逗号,可以有空格
print("your high is ", high) # 不用指定输出的类型%s,需要加逗号 
>>> a = "lao"
>>> b = "wang"
>>> print("name = %s" %(a+b))
name = laowang
>>> print("name = ",a+b)
name =  laowang

python2和python3的输入功能不同

#ipython默认使用python2
ubuntu@ubuntu-Lenovo:/work/python$ ipython
Python 2.7.6 (default, Nov 13 2018, 12:45:42) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: a = input("please input value:")
please input value:laowang
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-8e3b95b3288a> in <module>()
----> 1 a = input("please input value:")

<string> in <module>()

NameError: name 'laowang' is not defined

In [2]: a = input("please input value:")
please input value:1+2

In [3]: a
Out[3]: 3

注意:python2中的input()函数,输入的内容默认当成代码去执行了,而不是字符串

ubuntu@ubuntu-Lenovo:/work/python$ ipython3
Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: a = input("please input value:")
please input value:laowang

In [2]: a
Out[2]: 'laowang'

In [3]: a = input("please input value:")
please input value:1+2

In [4]: a
Out[4]: '1+2'

In [5]: 

python3中使用的input()函数的输入,是当成字符串的。

那么如何解决python2中的这个问题?
在python2中使用raw_input(),python3中没有raw_input()

ubuntu@ubuntu-Lenovo:/work/python$ ipython
Python 2.7.6 (default, Nov 13 2018, 12:45:42) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: a = raw_input("please input value:")
please input value:laowang

In [2]: a
Out[2]: 'laowang'

In [3]: a = raw_input("please input value:")
please input value:1+2

In [4]: a
Out[4]: '1+2'

类型及类型转换

变量定义的时候,不用管你定义的变量类型是什么,你写好之后,python编译器自动会识别你定义的变量类型,比如 a = 100,编译器自动会识别变量a的类型是int无符号整型。

判断变量的数据类型函数 type()

ubuntu@ubuntu-Lenovo:/work/python$ ipython3
Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: a = 100

In [2]: b = 3.1415

In [3]: c = "laowang"

In [4]: type(a)
Out[4]: builtins.int

In [5]: type(b)
Out[5]: builtins.float

In [6]: type(c)
Out[6]: builtins.str

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

Number(数字)–>(int、float、bool、complex(复数))
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)
Python3 的六个标准数据类型中:

不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。

input获取的所有数据,都当作字符串类型

#if.py
age = input("please input your age:")  
                                                                                                                                                                                
if age > 18:
    print("You can go to the internat bar")

ubuntu@ubuntu-Lenovo:/work/python$ python3 if.py 
please input your age:17
Traceback (most recent call last):
  File "if.py", line 3, in <module>
    if age > 18:
TypeError: unorderable types: str() > int()
#if.py
age = input("please input your age:")                                                                                                                                                                                   
age_num = int(age)
if age_num > 18:
    print("You can go to the internat bar")
    
ubuntu@ubuntu-Lenovo:/work/python$ python3 if.py 
please input your age:19
You can go to the internat bar

在这里插入图片描述
int(x,base)
int() 函数用于将一个字符串或数字转换为整型
x – 字符串或数字。
base – 进制数,默认十进制。

>>>int()               # 不传入参数时,得到结果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16)        # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
18
>>> int('0xa',16)  
10  
>>> int('10',8)  
8

if

if 条件:
(Tab键)*******
else:
(Tab键)******

if-else

#if-else.py
age = input("please input your age:")  
                                                                                                                                                                                
if age > 18:
    print("You can go to the internat bar")
else:
	print("You can go home now")

if-elif-else

if 条件:
(Tab键)*******
elif 条件:
(Tab键)******
elif 条件:
(Tab键)******
else(Tab键)******
  1
  2 age = int(input("please input your age:"))
  3 
  4 if age >= 18:
  5     print("You can go to the internet bar")
  6 elif age >=16 and age < 18:
  7     print("your age is 16---18")
  8 else:
  9     print("You can go home")

if嵌套

  1                                                                                                                                                                
  2 ticket = int(input("Do you have a ticket? 1 or 0\n"))
  3 
  4 if ticket == 1:
  5     print("You can pull in")
  6     Knife = int(input("Do you have a knife? 1 or 0\n"))
  7     if Knife == 1:
  8         KnifeLength = int(input("How long is it?\n")) #cm
  9         if KnifeLength <= 10:
 10             print("You can get on the train")
 11         else:
 12             print("Waiting for check")
 13     else:
 14         print("You can get on the train,and have not knift")
 15 else:
 16     print("You should buy the ticket")

while

while 条件:
(tab键)*****

例子:

  1 num = 0;                                                                                                                                                       
  2 
  3 while num <= 10:
  4     print(num)
  5     num += 1

三角形


i = 1

while i <= 9:

    j = 1
    while j <= i:
        print("*",end = "") # print默认带有换行符,end=""标识不换行
        j += 1
    print("")
    i += 1
#结果
ubuntu@ubuntu-Lenovo:/work/python$ python3 triangle.py 
*
**
***
****
*****
******
*******
********
*********

如果打印代码换成 print("*",end = " "),结果为:
ubuntu@ubuntu-Lenovo:/work/python$ python3 triangle.py 
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * *

99乘法表

i = 1

while i <= 9:

    j = 1
    while j <= i:
        print("%d*%d=%d"%(j, i, i*j),end="\t")
        #注意 print("%d*%d=%d"(这里不能加,逗号)%(j, i, i*j),end="\t"),\t是tab键
        j += 1
    print("")
    i += 1
结果:
ubuntu@ubuntu-Lenovo:/work/python$ python3 99_multiplication_table.py 
1*1=1
1*2=2   2*2=4
1*3=3   2*3=6   3*3=9
1*4=4   2*4=8   3*4=12  4*4=16
1*5=5   2*5=10  3*5=15  4*5=20  5*5=25
1*6=6   2*6=12  3*6=18  4*6=24  5*6=30  6*6=36
1*7=7   2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49
1*8=8   2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64
1*9=9   2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linux顿悟吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值