python学习一

2020-03-15  本文已影响0人  多啦A梦的时光机_648d

打开pycharm,输入下内容,设计一个猜字小游戏:

print('-----------第一课-----------')
temp = input('猜猜我心里想的数字是:')    ## 定义变量,不用声明,直接赋值
guess = int(temp)    ##转换为数值型
if guess == 8:    ##if...else...条件分支,双等号表示判断是否相等
    print('恭喜你,猜对了')    ##print前面的空格为tab键缩进
    print('猜对了也没奖励')
else:
    print('猜错了,我的数字是8')
    print('游戏结束')

总结一下语法

python严格控制缩进,tab键表示缩进;
=表示赋值,==表示判断是否相等;
直接定义变量,不需事先声明;
int表示整型的内置函数(BIF),input及print都是BIF,可以用help(BIF)查看内置函数。

变量

注意变量不能一以数字开头

first= '909'   赋值为字符型(str)
second = '4740'
thrid = '45'
print(first+second+thrid)
909474045

这里要注意在python中,处理str和number是不同的,例如:

first= '909'   ##赋值为字符型(str)
second = '4740'
thrid = 45 ##赋值为整型的数字(number)
print(first+second+thrid)
TypeError: can only concatenate str (not "int") to str   ##无否连接整形和字符型

处理:

first= '909'   ##赋值为字符型(str)
second = '4740'
thrid = 45 ##赋值为整型的数字(number)
print(first+second+str(thrid))  ##利用str()内置函数将整型(int)转换为字符型(str)
909474045

字符串

有的符合具有多种特殊含义,在使用时需要进行转义

print('Let\'s go')  ##转义字符\

或者单双引号一起使用

print("Let's go")
print('C:\now')  ##这里的\n被当成了换行符
C:
ow
## 所以需要对\进行转义
print('C:\\now') 
C:\now
## 如果有很多\n,一个个手动添加会非常麻烦,这里就可以用到原始字符串r,例如:
a= r'C:\now\new\test'
C:\now\new\test
## 这里test的后面是不可以加\的,否则会出现语法错误,例如:
    a= r'C:\now\new\test\'
                         ^
SyntaxError: EOL while scanning string literal
## 如果非要在后面加上\,可以先不加\,最后加一个\到最后,例如:
a= r'C:\now\new\test'
print(a)
b = print(a+'\\')   ##这里第一个\是对第二个\进行转义。
C:\now\new\test
C:\now\new\test\

长字符串

当你想输入一个多行的数据的时候,就需要用到三重引号字符串("""内容"""或者'''内容'''),例如:

str = """ When publishing work that uses OrthoFinder please cite:
 Emms D.M. & Kelly S. (2015), Genome Biology 16:157

 If you use the species tree in your work then please also cite:
 Emms D.M. & Kelly S. (2017), MBE 34(12): 3267-3278
 Emms D.M. & Kelly S. (2018), bioRxiv https://doi.org/10.1101/267914
"""
print(str)
上一篇 下一篇

猜你喜欢

热点阅读