python学习(1.2)

Chapter 1

操作符含义例子
**指数2**3=8
%取余数22%8=6
//商数取整22//8=2
+加法/字符串连接a+b=ab
*乘法/字符串复制a*3=aaa
==等于2==2.0(=true)
=赋值

变量名规则

  1. 只能是一个词
  2. 只能包含字母、数字和下划线
  3. 不能以数字开头

练习 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值