2.变量和数据类型

在本文中将给出Python中的变量和数据类型的一些解释

一、实验目的

  • python 关键字
  • 变量的定义与赋值
  • input() 函数
  • 字符串的格式化

二、知识要点

1. Python常用的关键词可通过在Python控制台中依次输入help()->keywords来获取

Python3关键字及含义见链接:Python保留字

2.Python中的变量
  • 通过使用代码直接赋值来赋予变量类型,例如,我们输入abc = 1则变量abc就是整型,如果输入abc = 1.0那么变量abc就是浮点型,在Python中我们只需要输入变量名以及值即可完成变量的定义与赋值
  • 通过使用双引号、单引号来对字符串进行操作,例如:
1
2
3
4
>>> 'XiaoZhe'
'XiaoZhe'
>>> 'XiaoZhe\'s blog'
"XiaoZhe's blog"

代码中的\''的转义字符,目的是为了在控制台中输出' 符号。

  • 可以通过函数input()来读取键盘输入
3.Python中的单行多元素赋值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> a , b = 45, 54
>>> a
45
>>> b
54

>>> a, b = b , a
>>> a
54
>>> b
45

>>> data = ( "China", "Python")
>>> country, language = data
>>> country
'China'
>>> language
'Python'

三、实验内容

1.使用Pycharm获取关键字
  • 通过在编辑器中输入help()并点击运行,在控制台中输入keywords就可以得到所有关键字了

Python关键字

  • 我们也可以在控制台输入modules, symbols 或者 topics来分别获取模块运算符文档

四、实验结果

1.求 N 个数字的平均值

输入一个整数N,在接下来你将输入N个数,程序将计算这N个数的平均值

  • 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
# Calculate the average of N numbers
# Define a variable N and get the value from the keyboard
print("Please enter an integer N, the program will enter N integers and calculate their average")
N = int(input("Enter an integer: "))
count = 1
sum_my = 0
while count <= N:
print("Please enter the ", count, " number: ", end=' ')
number = float(input())
sum_my = sum_my + number
count = count + 1
average_my = sum_my / N
print("The average of N number is:", "{:.2f}".format(average_my))
  • 结果
1
2
3
4
5
6
7
8
9
Enter an integer: 5
Please enter the 1 number: 1
Please enter the 2 number: 2
Please enter the 3 number: 3
Please enter the 4 number: 4
Please enter the 5 number: 5
The average of N number is: 3.00

Process finished with exit code 0
  • 函数说明:

print()函数
输出信息,不同类型的变量用,连接,即:print("string",int),也可以在函数中添加函数,如print("{:.2f}.format(value)")->打印value保留两位小数的值,如果需要输出后不换行,添加参数end=' 'print("不换行",end=' ')

input()函数
从键盘读取信息,参数中添加字符串可输出至控制台,即:input("请输入字符: "),由于input()函数默认读取的是字符型,如果需要整型需要进行转码即:int(input()),例:

1
2
3
4
>>> s = int(input("请输入数字:"))
请输入字符:2
>>> s
2
2.华氏温度到摄氏温度转换程序

使用公式 C = (F - 32) / 1.8 将华氏温度转为摄氏温度。

  • 代码:
1
2
3
4
# Enter a Fahrenheit temperature F and convert it to Celsius C. The formula is: C = (F-32) / 1.8
fahrenheit = int(input("Please enter the fahrenheit: "))
celsius = (fahrenheit - 32) / 1.8
print("The ", fahrenheit, "°F is ", "{:.2f}".format(celsius), "°C")
  • 结果:
1
2
Please enter the fahrenheit: 25
The 25 °F is -3.89 °C
  • 函数说明:

format()函数
通常使用规范为"文本{变量}".format(变量限制),例如下面几个例子

1
2
3
4
5
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

>>> print("{:.2f}".format(3.1415926));
3.14
  • 其他说明

对于format()函数中格式化数字的部分详见链接:format()函数格式化数字


下一篇:3.运算符和表达式
上一篇:1.开始Python之旅
目 录:Python学习

本文标题:2.变量和数据类型

文章作者:小哲

发布时间:2020年02月29日 - 16:46

最后更新:2020年03月30日 - 11:02

原始链接: 点击复制原始链接

许可协议: 协议-转载请保留原文链接及作者