Python

2.变量和数据类型

2020-02-29  本文已影响0人  小哲1998

一、实验目的

二、知识要点

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

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

2.Python中的变量
>>> 'XiaoZhe'
'XiaoZhe' 
>>> 'XiaoZhe\'s blog' 
"XiaoZhe's blog" 

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

3.Python中的单行多元素赋值
>>> 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获取关键字
Python关键字

四、实验结果

1.求 N 个数字的平均值
# 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))
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()),例:

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

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

# 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")
Please enter the fahrenheit: 25
The  25 °F is  -3.89 °C

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

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

>>> print("{:.2f}".format(3.1415926));
3.14

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

上一篇下一篇

猜你喜欢

热点阅读