3.1 输入与输出
3.1.1 打印
print("Hello Python!2020-12-2")
Hello Python!2020-12-2
name="sunny"
print("Hello %s, nice to meet you!" %name)
Hello sunny, nice to meet you!
age=22
print("You are %d!" %age)
You are 22!
#不知道变量的类型,用%r占位
n=100
print("You print is %r." %n)
You print is 100.
n="abc"
print("You print is %r." %n)
You print is 'abc'.
age=22
name="Catherine"
print("%s is %d years old." %(name,age))
Catherine is 22 years old.
age=22
name=“Catherine”
print(“student info: %s %d” %(name,age))
3.1.2 input输入
n=input("Enter any content:")
print("You input is %r." %n)
Enter any content:Sunny
You input is 'Sunny'.
3.1.3 引号与注释
1.不区分单引号和双引号,但不能交叉使用
print("Hello")
print('Hello')
Hello
Hello
print("你说:'早上你好'")
print('我说:"今天天气不错"')
你说:'早上你好'
我说:"今天天气不错"
注释
单行注释
# 打印Hello World
print("Hello World")
Hello World
多行注释
""" 多行注释1 """
'''多行注释2'''
print("hahh")
hahh
"""hanggg"""
print("hahh")
hahh
3.2分支与循环
if语句
a=2
b=3
if(a>b):
print("a max!")
else:
print("b max!")
b max!
student="sunny"
if(student=="sunny"):
print("sunny, you are on duty today!")
else:
print("Please call sunny on duty.")
sunny, you are on duty today!
hi="hello world"
if "hello" in hi:
print("Contain")
else:
print("Not contain.")
Contain
a=True
if a:
print("a is True.")
else:
print("a is not True.")
a is True.
results=72
if results>=90:
print("优秀")
elif results>=70:
print("良好")
elif results>=60:
print("及格")
else:
print("不及格")
良好
for语句
for i in "hello world":
print(i)
h
e
l
l
o
w
o
r
l
d
fruits=['banana','apple','mango']
for fruit in fruits:
print(fruit)
banana
apple
mango
for i in range(5):
print(i)
0
1
2
3
4
for i in range(1,10,2):
print(i)
1
3
5
7
9
3.3 数据与字典
3.3.1 数组
lists=[1,2,3,'a',5]
lists
[1, 2, 3, 'a', 5]
lists[0]
1
lists[4]
5
lists[4]='b'
lists[4]
'b'
lists.append('c')
lists
[1, 2, 3, 'a', 'b', 'c']
3.3.2 字典
dicts={"username":"sunny","password":"123456"}
dicts.keys()
dict_keys(['username', 'password'])
dicts.values()
dict_values(['sunny', '123456'])
dicts.items()
dict_items([('username', 'sunny'), ('password', '123456')])
for k,v in dicts.items():
print("dicts keys is %r " %k)
print("dicts values is %r " %v)
dicts keys is 'username'
dicts values is 'sunny'
dicts keys is 'password'
dicts values is '123456'
keys=["b","a","c","e","d"]
values=["2","1","3","5","4"]
for key,value in zip(keys,values):
print(key,value)
b 2
a 1
c 3
e 5
d 4
3.4 函数、类、方法
3.4.1 函数
def add(a,b):
print(a+b)
add(3,5)
8
def add1(a,b):
return a+b
add(3,5)
8
def add(a=1,b=2):
return a+b
add()
3
add(3,5)
8
3.4.2 类和方法
class A:
def add(self,a,b):
return a+b
count=A()
print(count.add(3,5))
8
class B:
def __init__(self,a,b):
self.a=int(a)
self.b=int(b)
def add(self):
return self.a+self.b
count=B("4",3)
print(count.add())
7
class C:
def add(self,a,b):
return a+b
class D(C):
#D继承C
def sub(self,a,b):
return a-b
print(D().add(4,5))
9
3.5 模组
3.5.1 引用模块
import time
print(time.ctime())
Thu Dec 3 23:13:42 2020
from time import ctime
print(ctime())
Thu Dec 3 23:14:14 2020
from time import *
print(ctime())
print("休眠2s")
sleep(2)
print(ctime())
Thu Dec 3 23:15:33 2020
休眠2s
Thu Dec 3 23:15:35 2020
import time
help(time)
Help on built-in module time:
NAME
time - This module provides various functions to manipulate time values.
DESCRIPTION
There are two standard representations of time. One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).
The other representation is a tuple of 9 integers giving local time.
The tuple items are:
year (including century, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
CLASSES
builtins.tuple(builtins.object)
struct_time
class struct_time(builtins.tuple)
| struct_time(iterable=(), /)
|
| The time value as returned by gmtime(), localtime(), and strptime(), and
| accepted by asctime(), mktime() and strftime(). May be considered as a
| sequence of 9 integers.
|
| Note that several fields' values are not the same as those defined by
| the C language standard for struct tm. For example, the value of the
| field tm_year is the actual year, not year - 1900. See individual
| fields' descriptions for details.
|
| Method resolution order:
| struct_time
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| tm_gmtoff
| offset from UTC in seconds
|
| tm_hour
| hours, range [0, 23]
|
| tm_isdst
| 1 if summer time is in effect, 0 if not, and -1 if unknown
|
| tm_mday
| day of month, range [1, 31]
|
| tm_min
| minutes, range [0, 59]
|
| tm_mon
| month of year, range [1, 12]
|
| tm_sec
| seconds, range [0, 61])
|
| tm_wday
| day of week, range [0, 6], Monday is 0
|
| tm_yday
| day of year, range [1, 366]
|
| tm_year
| year, for example, 1993
|
| tm_zone
| abbreviation of timezone name
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| n_fields = 11
|
| n_sequence_fields = 9
|
| n_unnamed_fields = 0
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
FUNCTIONS
asctime(...)
asctime([tuple]) -> string
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used.
ctime(...)
ctime(seconds) -> string
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used.
get_clock_info(...)
get_clock_info(name: str) -> dict
Get information of the specified clock.
gmtime(...)
gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
GMT). When 'seconds' is not passed in, convert the current time instead.
If the platform supports the tm_gmtoff and tm_zone, they are available as
attributes only.
localtime(...)
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead.
mktime(...)
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
Note that mktime(gmtime(0)) will not generally return zero for most
time zones; instead the returned value will either be equal to that
of the timezone or altzone attributes on the time module.
monotonic(...)
monotonic() -> float
Monotonic clock, cannot go backward.
monotonic_ns(...)
monotonic_ns() -> int
Monotonic clock, cannot go backward, as nanoseconds.
perf_counter(...)
perf_counter() -> float
Performance counter for benchmarking.
perf_counter_ns(...)
perf_counter_ns() -> int
Performance counter for benchmarking as nanoseconds.
process_time(...)
process_time() -> float
Process time for profiling: sum of the kernel and user-space CPU time.
process_time_ns(...)
process_time() -> int
Process time for profiling as nanoseconds:
sum of the kernel and user-space CPU time.
sleep(...)
sleep(seconds)
Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
strftime(...)
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
strptime(...)
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
thread_time(...)
thread_time() -> float
Thread time for profiling: sum of the kernel and user-space CPU time.
thread_time_ns(...)
thread_time() -> int
Thread time for profiling as nanoseconds:
sum of the kernel and user-space CPU time.
time(...)
time() -> floating point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
time_ns(...)
time_ns() -> int
Return the current time in nanoseconds since the Epoch.
DATA
altzone = -32400
daylight = 0
timezone = -28800
tzname = ('中国标准时间', '中国夏令时')
FILE
(built-in)
3.6 异常
open("abc.txt",'r')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-66-570f867ea6b6> in <module>
----> 1 open("abc.txt",'r')
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
try:
open("abc.txt",'r')
except FileNotFoundError:
print("异常了")
异常了
print(aa)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-68-54933412a1fe> in <module>
----> 1 print(aa)
NameError: name 'aa' is not defined
try:
print(aa)
except NameError:
print("NameError")
NameError
try:
open("abc.txt",'r')
except Exception:
print("异常了")
异常了
try:
open("abc.txt",'r')
except Exception as msg:
print(msg)
[Errno 2] No such file or directory: 'abc.txt'
try:
aa="异常测试"
print(aa)
except Exception as msg:
print(msg)
else:
#没有异常执行else后面的语句
print("没有异常")
异常测试
没有异常
try:
aa="异常测试"
print(bb)
except Exception as msg:
print(msg)
finally:
#没有异常执行else后面的语句
print("无论有没有异常,都会走到这")
name 'bb' is not defined
无论有没有异常,都会走到这
try:
aa="正常测试"
print(aa)
except Exception as msg:
print(msg)
finally:
#没有异常执行else后面的语句
print("无论有没有异常,都会走到这")
正常测试
无论有没有异常,都会走到这
from random import randint
#生成一个1-9之间的随机整数
number=randint(1,9)
number
1
if(number%2==0):
raise NameError("%d is even(整数)" %number)
else:
raise NameError("%d is odd(奇数)" %number)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-80-f6b6ce7a62bd> in <module>
2 raise NameError("%d is even(整数)" %number)
3 else:
----> 4 raise NameError("%d is odd(奇数)" %number)
NameError: 1 is odd(奇数)