码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础加固2—变量和数据类型

时间:2018-04-11 23:06:38      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:AC   cal   format   pac   完全   返回   均值   3.4   双引号   

知识点

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

关键字和标识符

每一种编程语言都有它们自己的语法规则,就像我们所说的外语。

下列的标识符是 Python3 的关键字,并且不能用于通常的标识符。关键字必须完全按照下面拼写:

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass
这些内容可以在 Python3 解释器中得到:

技术分享图片

在 Python 中 我们不需要为变量指定数据类型。所以你可以直接写出 abc = 1 ,这样变量 abc 就是整数类型。如果你写出 abc = 1.0 ,那么变量 abc 就是浮点类型。

技术分享图片

通过上面的例子你应该理解了如何在 Python 中定义变量,也就是只需要输入变量名和值就行了。Python 也能操作字符串,它们用单引号或双引号括起来,就像下面这样。

从键盘读取输入

通常情况下,Python 的代码中是不需要从键盘读取输入的。不过我们还是可以在 Python 中使用函数 input() 来做到这一点,input() 有一个用于打印在屏幕上的可选字符串参数,返回用户输入的字符串。

我们来写一个程序,它将会从键盘读取一个数字并且检查这个数字是否小于 100。这个程序名称是 /home/shiyanlou/testhundred.py

#!/usr/bin/env python3
number = int(input("Enter an integer: "))
if number <= 100:
    print("Your number is smaller than equal to 100")
else:
    print("Your number is greater than 100")

如果 number 小于 100,输出“Your number is smaller than 100”,如果大于 100,输出“Your number is greater than 100”。

程序运行起来就像这样: 

$ ./testhundred.py
Enter an integer: 13
Your number is smaller than 100
$ ./testhundred.py
Enter an integer: 123
Your number is greater than 100

下一个程序,来计算投资:

#!/usr/bin/env python3
amount = float(input("Enter amount: "))  # 输入数额
inrate = float(input("Enter Interest rate: "))  # 输入利率
period = int(input("Enter period: "))  # 输入期限
value = 0
year = 1
while year <= period:
    value = amount + (inrate * amount)
    print("Year {} Rs. {:.2f}".format(year, value))
    amount = value
    year = year + 1
运行程序:

$ cd /home/shiyanlou
$ chmod +x investment.py
$ ./investment.py
Enter amount: 10000
Enter Interest rate: 0.14
Enter period: 5
Year 1 Rs. 11400.00
Year 2 Rs. 12996.00
Year 3 Rs. 14815.44
Year 4 Rs. 16889.60
Year 5 Rs. 19254.15

while year <= period: 的意思是,当 year 的值小于等于 period 的值时,下面的语句将会一直循环执行下去,直到 year 大于 period 时停止循环。

Year {} Rs. {:.2f}".format(year, value) 称为字符串格式化,大括号和其中的字符会被替换成传入 str.format() 的参数,也即 year 和 value。其中 {:.2f} 的意思是替换为 2 位精度的浮点数。

代码示例

本部分包括下面的几个实例:

  1. 求 N 个数字的平均值
  2. 华氏温度到摄氏温度转换程序

下面的程序用来求 N 个数字的平均值。请将程序代码写入到文件 /home/shiyanlou/averagen.py 中,程序中将需要输入 10 个数字,最后计算 10 个 数字的平均值。

代码内容,请理解每一行代码含义:

#!/usr/bin/env python3
N = 10
sum = 0
count = 0
print("please input 10 number:")
while count < N:
    number = float(input())
    sum = sum + number
    count = count + 1
average = sum / N
print("N = {}, Sum = {}".format(N, sum))
print("Average = {:.2f}".format(average))
运行程序过程,需要输入 10 个数字:

$ cd /home/shiyanlou
$ chmod +x averagen.py
$ ./averagen.py
1.2
3.4
3.5
33.2
2
4
6
2.4
4
5.5
N = 10, Sum = 65.2
Average = 6.52

在下面的程序里,我们使用公式 C = (F - 32) / 1.8 将华氏温度转为摄氏温度。

#!/usr/bin/env python3
fahrenheit = 0
print("Fahrenheit Celsius")
while fahrenheit <= 250:
    celsius = (fahrenheit - 32) / 1.8 # 转换为摄氏度
    print("{:5d} {:7.2f}".format(fahrenheit , celsius))
    fahrenheit = fahrenheit + 25
{:5d} 的意思是替换为 5 个字符宽度的整数,宽度不足则使用空格填充。

运行程序:

$ cd /home/shiyanlou
$ chmod +x temperature.py
$ ./temperature.py
Fahrenheit Celsius
    0  -17.78
   25   -3.89
   50   10.00
   75   23.89
  100   37.78
  125   51.67
  150   65.56
  175   79.44
  200   93.33
  225  107.22
  250  121.11
你甚至可以在一行内将多个值赋值给多个变量,进入到 python3 交互式界面:

>>> a , b = 45, 54
>>> a
45
>>> b
54
这个技巧用来交换两个数的值非常方便。

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

要明白这是怎么工作的,你需要学习元组(tuple)这个数据类型。我们是用逗号创建元组。在赋值语句的右边我们创建了一个元组,我们称这为元组封装(tuple packing),赋值语句的左边我们则做的是元组拆封 (tuple unpacking)。

下面是另一个元组拆封的例子:

>>> data = ("shiyanlou", "China", "Python")
>>> name, country, language = data
>>> name
‘shiyanlou‘
>>> country
‘China‘
>>> language
‘Python‘

 


 

Python基础加固2—变量和数据类型

标签:AC   cal   format   pac   完全   返回   均值   3.4   双引号   

原文地址:https://www.cnblogs.com/hackerbird/p/8799156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!