4、python用户交互与运算符

时间:2021-08-13
本文章向大家介绍4、python用户交互与运算符,主要包括4、python用户交互与运算符使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

什么是用户交互

  简单来说,就是input和print两个函数,一个接受用户输入,一个向屏幕输出内容

# 输出单个字符串
print('hello world')            # hello world
# 输出字符列表
print('aaa', 'bbbb', 'ccc')     # aaa bbbb ccc

格式化字符串

  我们经常会输出具有某种固定格式的内容,比如:'亲爱的xxx你好!你xxx月的话费是xxx,余额是xxx‘,我们需要做的就是将xxx替换为具体的内容。

  简单常用的方式 %
print('亲爱的%s你好!你%s月的话费是%d,余额是%d' % ('tony', 12, 103, 11))  # 亲爱的tony你好!你12月的话费是103,余额是11

name = '李四'
age = 18
a = "姓名:%s,年龄:%s" % (name, age)
print(a)  # 姓名:李四,年龄:18   字典形式
b = "%(name)s,%(age)s" % {'name': '张三', 'age': 18}
print(b)  # 张三,18

  format方法
name = '李四'
age = 18
# 替换字段用大括号进行标记
a1 = "hello, {}. you are {}?".format(name, age)
print(a1)  # hello, 李四. you are 18?

# 通过索引来以其他顺序引用变量
a2 = "hello, {1}. you are {0}?".format(age, name)
print(a2)  # hello, 李四. you are 18?

# 通过参数来以其他顺序引用变量
a3 = "hello, {name}. you are {age1}?".format(age1=age, name=name)
print(a3)  # hello, 李四. you are 18?

# 从字典中读取数据时还可以使用 **
data = {"name": "张三", "age": 18}
a4 = "hello, {name}. you are {age}?".format(**data)
print(a4)  # hello, 李四. you are 18?

基本运算符

  没什么可说,和其他语言相差不大

  //:取除数

  %:取余数

  python由于不显式地声明变量的数据类型,所以 3/2=1.5 而不是等于1,想要等于1只能通过//计算

解压赋值

nums = [1, 2, 3, 4, 5, 6, 7]
# 需求:把nums中的每一个数单独赋值给变量
# 当然,可以一个一个赋值,但是太low了
a, b, c, d, e, f, g = nums
print(a, b, c, d, e, f, g)  # 1 2 3 4 5 6 7

  但是,如果只想要头尾两个值,可以用*_

nums = [1, 2, 3, 4, 5, 6, 7]

a, b, *_ = nums
print(a, b)     # 1 2
a, *_, b = nums
print(a, b)     # 1 7
*_, a, b = nums
print(a, b)     # 6,7

  ps:字符串、字典、元组、集合类型都支持解压赋值

逻辑运算

  优先级:非(not)>与(and)>或(or)

成员运算符

  in / not in

print('lili' not in ['jack','tom','robin'])     # True

  PS:可用于元组、字符串、列表、字典(key)

身份运算符

  is / is not

  ==运算符在python中判断的是值是否相等,is是判断内存地址是否相等

原文地址:https://www.cnblogs.com/longzh/p/15139241.html