Python100Days-day2语言元素

数据类型
1.整型,在python3中只有int这一种,支持二进制0b开头,八进制0o开头,16进制0x开头
2.浮点型,数学写法和科学计数法
3.字符串型,字符串是以单引号或双引号括起来的任意文本
4.布尔型,Ture和False两种值
5.复数型,和数学上唯一不同是i换成了j,不常用
变量命名

硬性规则:
    变量名由字母(广义的Unicode字符,不包括特殊字符)、数字和下划线构成,数字不能开头。
    大小写敏感(大写的a和小写的A是两个不同的变量)。
    不要跟关键字(有特殊含义的单词,后面会讲到)和系统保留字(如函数、模块等的名字)冲突。
PEP 8要求:
    用小写字母拼写,多个单词用下划线连接。
    受保护的实例属性用单个下划线开头(后面会讲到)。
    私有的实例属性用两个下划线开头(后面会讲到)。

变量的使用
1.type()函数可以进行类型检查

a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>
print(type(d)) # <class 'str'>
print(type(e)) # <class 'bool'>

运行结果是
<class ‘int’>
<class ‘float’>
<class ‘complex’>
<class ‘str’>
<class ‘bool’>
2.类型转换函数
int(),float(),str(),chr(),ord()

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 = %f' % (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))

运行结果是
a = 2
b = 3
2 + 3 = 5
2 - 3 = -1
2 * 3 = 6
2 / 3 = 0.666667
2 // 3 = 0
2 % 3 = 2
2 ** 3 = 8 #a**b就是a的b次方
运算符
按优先级从高到低列出
在这里插入图片描述

练习1: 华氏温度转换为摄氏温度

"""
Convert Fahrenheit to Celsius
Powered by RainGiving
"""
f=float(input('Please enter Fahrenheit temperature:'))
c=(f-32)/1.8
print('%.1fF = %.1f℃'%(f,c))

练习2:输入圆的半径计算计算周长和面积

"""
Enter radius to calculate the circumference and area of the circle
Powered by RainGiving
"""
import math
r=float(input('Please enter the radius of the circle\n'))
c=2*r*math.pi
s=r**2*math.pi
print('circumference=%.1f,area=%.1f'%(c,s))

练习3:输入年份判断是不是闰年

"""
Enter year to determine leap year
Powered by RainGiving
"""
year=int(input('Please enter the year\n'))
#勿忘类型转换
is_leap=(year%4==0 and year%100!=0) or\
        year%400==0
#一行代码太长不利于阅读,用 \ 可以拆开
        
print(is_leap)
发布了18 篇原创文章 · 获赞 0 · 访问量 306

猜你喜欢

转载自blog.csdn.net/RainGiving/article/details/103985693
今日推荐