版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_Cui_LS/article/details/83114590
表达式
表达式 包含 “值” 和 “操作符”,并且总是可以求值为单个值。
所有使用表达式的地方,都可以使用一个值。
###数学操作符
- ** 指数
- % 取模/取余数
- // 整除/商数取整
- / 除法
- ‘*’ 乘法
- ‘-’ 减法
- ‘+’ 加法
优先级同数学中类似。可以用括号来改变通常的优先级。
>>> 2+3*6
20
>>> (2+3)*6
30
>>> 23 // 7
3
>>> 23 /7
3.2857142857142856
>>>
整型、浮点型 和 字符串数据类型
- 整型 如: -1,89,12,等
- 浮点型 如: 1.25, -1.0, 2.1 等
- 字符串 如: ‘123’, ‘a’, 'abc’等等
这里的字符串不同于 java 语言中的字符串, 使用的是 ‘’ 单引号
字符串的连接和复制
- 字符串的连接使用 + 号 进行拼接。 + 号的两侧,如果有一边是字符串,那么另一边也必须是,否则会报错。
- 字符串 * int(数字) 则是复制的效果。
>>> '123' * 3
'123123123'
>>> '123' * -3
''
>>> '123' * 0
''
变量中保存值
变量, 可以想象成一个盒子, 它可以存放任意类型的值。
变量可以进行赋值。
>>> hello = 123
>>> 123 + hello
246
变量名
变量起名遵循以下规则:
- 只能是一个词
- 只能包含字母、数字和下划线。 (在java中也可使用 $ 符号)
- 不能以数字开头。
其他:
- 大体上和 java 比较类似。 但在java中可以使用 $ 符号。
- 变量名区分大小写。 意味着, spam、SPAM、Spam 等都属于不同的变量。
在命名上。 可以使用驼峰命名法。
第一个小程序
#This program says hello and asks for my name
print('hello world ~!')
print('what is your name ? ') # ask for their name
myName = input()
print('It is good to meet you ,'+myName)
print('The length of your name is : ')
print(len(myName))
print('what is your age ? ') #ask for their age
myAge = input()
print('You will be '+str(int(myAge) + 1) +' in a year.')
程序解析
注释
#This program says hello and asks for my name
Python会忽略注释。
java中有三种注释 //单行注释, /* 内容 */ 多行注释 以及文档注释
python 中的注释 #
print() 函数
将括号内的字符串显示到屏幕上。
input() 函数
阻塞,等待用户输入内容。并返回一个字符串。
len() 函数
可以向len() 函数传递一个字符串(或者包含字符串的变量), 返回一个整型值。 为 字符串的字符个数。
>>> len('helloworld')
10
>>> len('')
0
>>> len('ni zhidao ma shijie')
19
str()、int()、float 函数
>>> print('I am '+ str(29) +' years old')
I am 29 years old
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0
>>> float('10')
10.0
>>> int('10.25')
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
int('10.25')
ValueError: invalid literal for int() with base 10: '10.25'
通过str()、int() 和 float() 可以进行类型转换。
input() 函数返回的都是字符串, 在实际情况下,有时候需要我们进行转换
>>> spam = input()
101
>>> spam
'101'
>>> spam / 2
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
spam / 2
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> int(spam)/2
50.5
文本和数字的相等判断
数字的字符串值 与整型值和浮点型值 完全不同。 但整型值可以与浮点值相等。
>>> 23 == '23'
False
>>> 23 == 23.000
True