python if条件判断、datetime

1、if简单判断

  if 条件:

    语句块

  else:

    语句块

  if 1>2:

    print('假的')

  else:

    print(''真的")

2、多重if elif

   if 条件1:

      语句块

   elif 条件2:

      语句块

   else:

      语句块

    if  a==2:

      print(‘a=2')

    elif a==3:

      print('a=3')

    else:

      print('a=0')

3、and 并且

score=input('请输入你的分数:')
score=int(score)#强制类型转换
if score<=100 and score>=90:
  print('优秀')
elif score<90 and score>=80:
  print('良好')
elif score<80 and score>=60:
  print('及格')
elif score<60 and score>=0:
  print('不及格')
else:
  print('请输入正确数字')

4、or 或者

sex=input('请输入你的性别:')
if sex=='男' or sex=='女':
  print('性别合法')
else:
  print('性别不合法')

5、datetime 

   先使用import导入datetime模块

    import datetime

   设置一个用户名(与datetime拼接使用)

    user='xxx'

   表示日期和时间的类

    today=datetime.datetime.today()

  将datetime转为字符串类型

    today=str(today)

欢迎xx登录,今天的日期是xxx 举例:

写法1:msg='欢迎'+user+'登录'+'今天的日期是'+today(拼接字符串的方式)

    print(msg)

写法2:msg='欢迎%s登录,今天的日期是%s'%(user,today)

    print(msg)

%s占位符 前面几个%s 后面括号写几个变量
%s表示string类型(其他也可用) %d 整数 %f 小数 保留几位小数,在f前加 %.2f
保留两位小数还可以用round(score,2)保留小数后几位(四舍五入舍0)
\n 换行

猜你喜欢

转载自www.cnblogs.com/miyuki/p/9123938.html