第三章 Python基础

3.1变量、值和类型

 

 

prompt_text = "Enter a number:"
user_in = input(prompt_text)
user_num = int(user_in)

for i in range(1,10):
    print(i, " times ", user_num, " is ", i*user_num)

even = (user_num % 2) == 0

if even:
    print(user_num, " is even")   #是偶数
else:
    print(user_num, " is odd")    #是奇数


 

 

 

 

 

prompt_text = "Enter a number:"
user_in = input(prompt_text)
user_num = int(user_in)


for i in range(1,10):
    print(i, " times ", user_num, " is ", i*user_num)

even = (user_num % 2) == 0

if even:
    print(user_num, " is even")   #是偶数
else:
    print(user_num, " is odd")    #是奇数

print(prompt_text)
print(type(prompt_text))
print(user_in)
print(type(user_in))
print(user_num)
print(type(user_num))


 

 

 

 

3.2在结构体中存储值

Python中最简单的结构体是sequence(线性结构),分为lists(列表)和tuples(元组)两类。他们是相似的

3.1.1列表,相当于C语言中的数组(Python中字符串也可以用单引号和双引号括起,双引号兼容单引号但单引号不兼容双引号)

 

>>> list_3 = [3,2,1]
>>> list_3.append(0)
>>> list_3
[3, 2, 1, 0]
>>> list_3.index(2)
1
>>> len(list_3)
4
>>> list_2 = [["A","b","c"],["d","e","f"],["g","h","i"],["j","k","l"]]
>>> list_2
[['A', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]
>>> list_2[2][0]
'g'
>>> list_2[:3]
[['A', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> list_1 = [1,2,3,4]
>>> list_1[1]
2
>>> list_1[:3]
[1, 2, 3]
>>> list_1[1:]
[2, 3, 4]
>>> 


一下为列表的操作方法:

 

 

元组的使用方法和列表类似,但改变元组的值得时候需要为整个元组赋一个新值,而不能像列表一样只改变其一个元素的值

 

>>> tuple_1 = (1,2,3,4)
>>> tuple_1[1]
2
>>> tuple_1 = (1,99,3,4)
>>> tuple_
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    tuple_
NameError: name 'tuple_' is not defined
>>> tuple_1
(1, 99, 3, 4)
>>> tuple_1[:3]
(1, 99, 3)
>>> tuple_1.index(2)
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    tuple_1.index(2)
ValueError: tuple.index(x): x not in tuple
>>> tuple_1.index(99)
1
>>> tuple_2.sort()
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    tuple_2.sort()
NameError: name 'tuple_2' is not defined
>>> 

 

 

 

 

 

3.2.1字典和集合中的非序列元素

知识测试:

 

3.3控制程序流程

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值