Chapter 1
操作符 | 含义 | 例子 |
---|---|---|
** | 指数 | 2**3=8 |
% | 取余数 | 22%8=6 |
// | 商数取整 | 22//8=2 |
+ | 加法/字符串连接 | a+b=ab |
* | 乘法/字符串复制 | a*3=aaa |
== | 等于 | 2==2.0(=true) |
= | 赋值 |
变量名规则
- 只能是一个词
- 只能包含字母、数字和下划线
- 不能以数字开头
练习 1
print('hello world')
print('what is your name?')
myname=input()
print('It is good to meet you,'+myname)
print('The length of your name is:')
print(len(myname))
myage=input()
print('You will be '+ str(int(myage) + 1) + ' in a year.')
>>>
hello world
what is your name?
Mary
It is good to meet you,Mary
The length of your name is:
4
20
You will be 21 in a year.
练习2
>>> spam=input()
100
>>> spam #保留的是字符串
'100'
>>> spam=int(spam)
>>> spam #值
100
>>> b=str(5.0) #值转化为字符串
>>> b
'5.0'
Chapter 2
if函数
name=input()
age=input()
age=int(age)
if name=='Bob':
print('hi,Bob.')
elif age<12:
print('You are not Bob.')
elif age>200:
print('Wrong password') #注意顺序,可能会导致结果不一样
elif age>100:
print('unbelievable')
else:
print('formal')
>>>
Psc
150
unbelievable
while循环
(break函数,continue函数–只能在while和for循环内使用)
while True:
print('Who are you?')
name=input()
if name!='Psc':
continue #跳回循环开始处
print('Hi,Psc.What is the password?')
password=input()
if password=='cute':
break #跳出循环
print('Psc is cute.')
>>>
Who are you?
Hou
Who are you?
Psc
Hi,Psc.What is the password?
cue
Who are you?
Psc
Hi,Psc.What is the password?
cute
Psc is cute.
“类真”和“类假”的值
name=''
while not name: #0和''被认为是Flase,其他值为True
print('Enter your name:')
name=input()
print('How many ghost will you have?')
numofghost=int(input())
if numofghost: #numofghost!=0
print('Be sure to have enough courage to meet them.')
else:
print('done')
>>>
Enter your name:
Psc
How many ghost will you have?
5
Be sure to have enough courage to meet them.
for函数,range函数
#2+...+100=?
sum=0
for i in range(0,101,2): #range(初始值,终止值(不被包含),步长)
sum=sum+i
print(sum)
#等价的while循环
sum=0
i=0
while i<101:
sum=sum+i
i=i+2
print(sum)
>>>
2550
2550
导入模块
import random #常用的还有sys,os,math
for i in range(3):
print(random.randint(1,10)) #在random模块中调用randint函数
import random
from random import randint
for i in range(3):
print(randint(1,10)) #在random模块中调用randint函数
import sys
while True:
print('Type exit to exit')
response=input()
if response=='exit':
sys.exit() #终止程序或退出
print('You typed '+response +' . ')
>>>
10
6
2
9
3
10
Type exit to exit
psc
You typed psc .
Type exit to exit
exit