Python基础之输出格式和If判断
格式化输出的三种方式
一、占位符
#占位符
name = 'nick'
age = 19
print('my name is %s my age is %s' % (name, age))
age = 19
print('my name is %d' % age)
my name is nick my age is 19
my age is 19
二、format格式化
name = 'nick'
age = 19
print("Hello, {}.You are {}.".format(age, name))
print("Hello, {1}. You are {0}-{0}".format(age, name))
print("Hello, {name}. You are {age}-{age}.".format(age = age, name = name))
Hello,nick. You are 19.
Hello,nick. You are 19-19
Hello,nick. You are 19-19.
三、f-String格式化
name = "nick"
age = 19
print(f'Hello, {name}. You are {age}.')
pint(F'Hello, {name}. You are {age}.')
print(f'{age*2}')
salary = 6.66666
print(f'{salary:.2f}')
Hello, nick. You are 19.
Hello, nick. You are 19.
38
6.67
横向输出是在print中加一个参数end=' '
流程控制之if判断
一、语法
# if
cls = 'human'
gender = 'female'
age = 19
if cls == 'human' and gender == 'female' and age > 16 and age a < 22:
print('开始表白')
print('end....')
# if...else
cls = 'human'
gender = 'female'
age = 38
if cla == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
else:
print('阿姨好')
# if...elif...else
cls = 'human'
gender = 'female'
age = 28
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
elif cls == 'human' and gender == 'female' and age > 22 and age < 30:
print('考虑下')
else:
print('阿姨好')
开始表白
end…..
阿姨好
考虑下
二、if的嵌套
cls = 'human'
gender = 'female'
age = 19
is_successful = False
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
if is_successful:
print('那我们一起走吧。。。')
else:
print('我逗你玩呢')
else:
print('阿姨好')
开始表白
我逗你玩呢
练习
练习一:成绩评判
- 如果 成绩>=90,打印"优秀"
- 如果 成绩>=80 并且 成绩<90,打印"良好"
- 如果 成绩>=70 并且 成绩<80,打印"普通"
- 其他情况:打印"差"
# 成绩评判
score = input("your score: ")
score = int(score)
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 70:
print('普通')
else:
print('差')
your score: 80
良好
练习二:模拟登录注册
#模拟登录注册
user_from_db = 'nick'
pwd_from_db = 123
user_from_inp = input('username:')
pwd_from_inp = input('password: ')
if user_from_inp == user_from_db and pwd_from_inp == pwd_from_db:
print('login successful')
else:
print('username or password error')
username: nick
password: 123
username or password error