Python基础 — 变量和运算符

序言:这一章我们将学习变量以及常见的类型,我们将以案例和代码相结合的方式进行梳理,但是其中所有的案例和知识点 都是Python3 版本。

变量和运算符

1.1 初步介绍

​ 在程序设计中,变量是一种存储数据的载体。计算机中的变量是实际存在的数据或者说是存储器中存储数据的一块内存空间,变量的值可以被读取和修改,这是所有计算和控制的基础。计算机能处理的数据有很多种类型,除了数值之外还可以处理文本、图形、音频、视频等各种各样的数据,那么不同的数据就需要定义不同的存储类型。 Python中的数据类型很多,而且也允许我们自定义新的数据类型(这一点在后面会讲到),我们先介绍几种常用的数据类型。

​ 此外Python还支持多种运算符,下表大致按照优先级从高到低的顺序列出了所有的运算符,我们会陆续使用到它们。

运算符 描述
[] [:] 下标,切片
** 指数
~ + - 按位取反, 正负号
* / % // 乘,除,模,整除
+ - 加,减
>> << 右移,左移
& 按位与
^ | 按位异或,按位或
<= < > >= 小于等于,小于,大于,大于等于
== != 等于,不等于
is is not 身份运算符
in not in 成员运算符
not or and 逻辑运算符
= += -= *= /= %= //= **= &= | = ^= >>= <<=

1.2 使用案例

1、变量的初步使用

"""
变量的初步实验
version:0.1
author:coke
"""
a = 555
b = 112
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b)
print(a**b)

输出结果

 
 

2、使用input() 函数获取键盘输入,将输入值进行计算

"""
使用input()函数获取键盘输入
使用int()进行类型转换
用占位符格式化输出的字符串
version: 0.1
Author: coke
"""
a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' %(a,b,(a + b)))
print('%d - %d = %d' %(a,b,(a - b)))
print('%d * %d = %d' %(a,b,(a * b)))
print('%d / %d = %d' %(a,b,(a / b)))
print('%d // %d = %d' %(a,b,(a // b)))
print('%d %% %d = %d' %(a,b,(a % b)))
print('%d ** %d = %d' %(a,b,(a ** b)))

输出结果

 
 

3、使用type() 检查变量的类型

"""
使用type检查变量的类型
version: 1
authot: coke
"""
a = 110
b = 13.78   
c = 2 + 7j
d = 'hello world'
e = True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

输出结果

1.3 知识点梳理

①、上面的案例代码中会有部分的类型转换,下面我们说说常用的转换方式

  • int():将一个数值或字符串转换成整数,可以指定进制。
  • float():将一个字符串转换成浮点数。
  • str():将指定的对象转换成字符串形式,可以指定编码。
  • chr():将整数转换成该编码对应的字符串(一个字符)。
  • ord():将字符串(一个字符)转换成对应的编码(整数)。

②、input(): input() 函数接受一个标准输入数据,返回为 string 类型

>>>a = input("input:")
input:123                  # 输入整数

③、type():type() 函数的主要作用是检查变量的类型

>>> type(a)
<type 'int'>

1.4 练习

**1、输入年份判断是不是闰年 **

"""
输入年份判断是否是闰年
version: 0.1
author: coke
"""
year = int(input("请输入年份:"))
is_leap = '是' if (year % 4 == 0  and year % 100 != 0 or year % 400 == 0 ) else '否'
print("是否为闰年:%s"%is_leap)

 
**2、输入半径计算圆的周长和面积 **

# -*- coding = utf-8 -*-
"""
输入半径计算圆的周长和面积
version: 0.1
author: coke
"""
import math
r = float(input("输入圆的半径:"))
length = 2 * math.pi * r
area = math.pi * r * r
print("圆的周长为:%.1f"%length)
print("圆的面积为:%.1f"%area)
原文地址:https://www.cnblogs.com/dwlovelife/p/11529295.html