[python3]basis

0.Python中使用缩进来表示一个函数。所以初学者注意缩进。

1.变量

#变量, 变量在使用之前必须赋值。 大小写不同则是两个不同的变量
ab = 1
AB = 2
Ab = 3
print(ab)  #1
print(AB)  #2
print(Ab)  #3

2.print

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

print('auther'+'='+'zsy')   #auther=zsy
print('abcd'*5)             #abcdabcdabcdabcdabcd
print(3)                    #3



print("I ");print("love");print("you") 
'''
输出如下:
I
love
you
''' 

print('abc',end = '@163.com ')
print('123')
#输出 abc@163.com 123

print('abc',end = '@163.com ')
print()                          #作用添加换行,类似于/n
print('123')
'''      
输出:
abc@163.com 
123
'''

print('abc',end = ' ')
#print()默认是打印完字符串会自动添加一个换行符,end=" "参数告诉print()用空格代替换行


str = 'FishC'
for i in str:
    print(i,end=' ') #F i s h C

3.input,random

import random
print('-------Game(猜数字)------')

score = 0
i = 1
while i<= 10:
    secret = random.randint(1, 10)
    print('You have 10 chance, this is ',i)

    tmp = input('Please input the number: ')
    guess = int(tmp)

    if guess == secret :
        print('Bingo,you are right')
        score += 1
        print('score=', score)
        print('------ next -------')
    else:
        print('You are wrong,')
        print('------ next -------')
    i += 1

print('Game over')
print('The total score=',score)
print('------ next -------')

4.python有多少内置函数

BIF(Built in functions)内置函数,一般不作为变量命名

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

如果像知道内置函数的具体意义,可以使用help,例如:

>>> help(input)

 

4.数值类型

#数值类型与类型转换
#字符串
a = 'dujekj3'
print(type(a))        #<class 'str'>

#整型
a0 = 3
print(type(a0))       # <class 'int'>

#浮点型
b1=1.2
b2 = 0.0034
print(type(b2))       #<class 'float'>

#bool布尔类型  ,运算时可以将True看成1,False看成0
print(True + True)    #2
print(True + False)   #1
print(True * False)   #0
#print(True / False)  #ZeroDivisionError: division by zero
print(type(True))     #<class 'bool'>

#e记法
a1 = 0.0000025        #2.5e-06
print(a1)

a2 = 1.5e10           #15000000000.0
print(a2)

a3 = 15e9             #15000000000.0
print(a3)

#类型转化
a = '520'
a1 = int(a)          #520
a2 = float(a)        #520.0
  

b = 5.99
b1 = int(b)          #5  直接砍掉小数点后边的
b2 = str(b)
print(b2)            #'5.99'  这个在idle上可以显示'' 在pycham上没显示''

#对这块有疑问,为什么只有e15到e19后边输出为'5e19'的模式,其他都是后边加0的
c = str(15e9)        #'15000000000.0'
c1 = str(5e19)       #'5e+19'
c2 = str(5e9)        #'5000000000.0'
c3 = str(4e13)       #'40000000000000.0'
c4 = str(3e15)       #'3000000000000000.0'
print(c)
print(c1)
print(c2)
print(c3)
print(c4)
#isinstance 函数来确定数据类型

a = 'hello'
c1 = isinstance(a,str)  #True
c2 = isinstance(12,int) #True
c3 = isinstance(12,float) #False
print(c)

#取得一个变量的类型,视频中介绍可以使用 type() 和 isinstance(),你更倾向于使用哪个?
#答:无所谓,但既然python帮助文档建议我们使用isinstance(),那就这个吧。

s = "123abc"
s.isalnum()  # 所有字符都是数字或者字母,为真返回 Ture,否则返回 False.
s.isalpha()  # 所有字符都是字母,为真返回 Ture,否则返回 False.
s.isdigit()  # 所有字符都是数字,为真返回 Ture,否则返回 False.

s.isspace()  # 所有字符都是空白字符,为真返回 Ture,否则返回 False.

s.islower()  # 所有字符都是小写,为真返回 Ture,否则返回 False.
s.isupper()  # 所有字符都是大写,为真返回 Ture,否则返回 False.
s.istitle()  # 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写.


#举例如下:
s = "Today Is Firday"
print(s.istitle())      #True

9.

#导入模块
import random

a = random.randint(1,10)  #1--10的整数型数字
b = random.random()       #0.07015513696818643
print(a)  #a--1
print(a)  #a--2
print(random.randint(1,10)) #a--3
#a--1,a--2是相同的数字,a--3是另一个数字

 

5.操作符

>>> a = 9
>>> a += 3
>>> a
12
>>> a -= 3
>>> a
9
>>> a * 2
18

>>> 3 ** 2       # **是幂运算
9
>>> 3 ** 3
27

>>> a / 2   #python3  中 /除基本上和算术的一样
4.5
>>> a // 2   #python3  中  //表示取商
4
>>> a % 2  # % 取余数
1

>>> 5%2**2*2
2

>>> 3.0 // 2.0
1.0

 

6

'''
爱因斯坦曾出过这样一道有趣的数学题:有一个长阶梯,若每步上2阶,最后剩1阶;若每步上3阶,最后剩2阶;若每步上5阶,最后剩4阶;若每步上6阶,最后剩5阶;只有每步上7阶,最后刚好一阶也不剩。
题目:请编程求解该阶梯至少有多少阶?

--这是一个整除问题,可以看出,这个数字加上1,能被2.3.5.6整除,而且这个数能被7整除
加上1能被2.3.5.6整除的数又30 60 90 120 150...
30.60...减去1能被7整除的有120,减去1=119,能被7整除 ,所以这个数最小是119
'''
#1
x = 7  #台阶数
i = 1
flag = 0

while i <= 100:
    if(x%2 ==1) and (x%3 ==2) and (x%5 ==4) and (x%6 ==5):
        flag = 1
    else:
        x = 7 *(i+1)
    i += 1

if flag == 1:
    print('阶梯数是:', x)
else:
    print('在程序限定的范围内找不到答案!')


#2-另一种方法
i = 1
while (i%2!=1 or i%3!=2 or i%5!=4 or i%6!=5 or i%7!=0):
    i += 1
print(i)

7. assert  断言,正常就不输出,错误会抛出异常。 assert的作用是检查条件是否为真。

>>> assert 4 > 2
>>> assert 2 > 4
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert 2 > 4
AssertionError

 

8.

# range

for i in range(5):
    print(i)   # 0 1 2 3 4

for i in range(1,9):
    print(i)   # 1 2 3 4 5 6 7 8

for i in range(1,9,2):
    print(i)   # 1 3 5 7

9.运算

small = x if (x < y and x < z) else (y if y < z else z)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值