用python实现一个简单的计算器(while循环),格式化输出

目录

一.能够进行+,-,*,/运算的简单计算器

二.使用单层while循环实现9*9乘法表

三.str中方法的使用

四.格式化输出


一.能够进行+,-,*,/运算的简单计算器

使用while循环和if 条件语句控制计算器,在输出需要使用到占位符:%s

while True:
    p = input('是否继续使用计算器?(yes/no)')
    if p == 'yes':
        a = float(input('输入数字1:'))
        b = float(input('输入数字2:'))
        c = str(input('输入运算法则:'))
        if c == '+':
            z = a + b
            print('%s与%s的和为%s' % (a, b, z))
        elif c == '-':
            z = a - b
            print('%s与%s的差为%s' % (a, b, z))
        elif c == '*':
            z = a * b
            print('%s与%s的乘积为%s' % (a, b, z))
        elif c == '/':
            z = a / b
            print('%s与%s的商为%s' % (a, b, z))
    elif p == 'no':
        break
    else:
        print('错误输入')

#执行结果
是否继续使用计算器?(yes/no)yes
输入数字1:8
请输入数字2:8
输入运算法则:*
8.0与8.0的乘积为64.0
是否继续使用计算器?(yes/no)i
错误输入

二.使用单层while循环实现9*9乘法表

i = 1
j = 1
while i < 10:
    if j <= i:
        print(i, '*', j, '=', i * j, end='\t')
        j += 1
    else:
        print()
        j = 1
        i += 1

#执行结果
1 * 1 = 1	
2 * 1 = 2	2 * 2 = 4	
3 * 1 = 3	3 * 2 = 6	3 * 3 = 9	
4 * 1 = 4	4 * 2 = 8	4 * 3 = 12	4 * 4 = 16	
5 * 1 = 5	5 * 2 = 10	5 * 3 = 15	5 * 4 = 20	5 * 5 = 25	
6 * 1 = 6	6 * 2 = 12	6 * 3 = 18	6 * 4 = 24	6 * 5 = 30	6 * 6 = 36	
7 * 1 = 7	7 * 2 = 14	7 * 3 = 21	7 * 4 = 28	7 * 5 = 35	7 * 6 = 42	7 * 7 = 49	
8 * 1 = 8	8 * 2 = 16	8 * 3 = 24	8 * 4 = 32	8 * 5 = 40	8 * 6 = 48	8 * 7 = 56	8 * 8 = 64	
9 * 1 = 9	9 * 2 = 18	9 * 3 = 27	9 * 4 = 36	9 * 5 = 45	9 * 6 = 54	9 * 7 = 63	9 * 8 = 72	9 * 9 = 81	

进程已结束,退出代码0

三.str中方法的使用

center(self, width, fillchar=' ', /)          居中对齐            ##返回一个居中长度为width的字符串,使用指定的填充字符填充(默认为空格)  

Return a centered string of length width.  

Padding is done using the specified fill character (default is a space). 

str_data = 'nihao,python'
str_var = str_data.center(20, '*')
print(str_var)

#执行结果
****nihao,python****

进程已结束,退出代码0

expandtabs(self, /, tabsize=8)           设置 ‘\t’ 的空间              ##返回一个副本,其中所有制表符都可以使用空格展开,如果没有给出tabsize,则默认制表符的大小为8个字符     相当于自己设置制表符的字符数。

Return a copy where all tab characters are expanded using spaces.  

If tabsize is not given, a tab size of 8 characters is assumed. 

tabsize默认值是8.tabsize值为0-7等效与tabsize=8,tabsize每增加1,原字符串中‘\t’的空间会增加一个空格。

str_data = 'nihao\t,hello'
str_var = str_data.expandtabs(tabsize=8)
str_var1 = str_data.expandtabs(tabsize=9)
str_var2 = str_data.expandtabs(tabsize=10)
print(str_data)
print(str_var1)
print(str_var2)

##执行结果
nihao	,hello
nihao    ,hello
nihao     ,hello

进程已结束,退出代码0

join(self, iterable, /)                       ## 连接任意数量的字符串,调用其方法的字符串被插入到每个给定的字符串之间。结果以新字符串的形式返回。

Concatenate any number of strings.

The string whose method is called is inserted in between each given string.

The result is returned as a new string.

Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

tuple_data = ('1', '8', '9', '110')
str_data = 'nihao,python'
str_var = str_data.join(tuple_data)
print(str_var

#执行结果
1nihao,python8nihao,python9nihao,python110

进程已结束,退出代码0

ljust(self, width, fillchar=' ', /)              左对齐                                   ##返回一个长度为width的左对齐的字符串,使用指定的填充字符填充(默认为空格)

| Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space). 

str_data = 'nihao,python'
str_var = str_data.ljust(15, '=')
print(str_var,  len(str_data))

#执行结果
nihao,python=== 12

进程已结束,退出代码0

partition(self, sep, /)                    ##使用给定的分隔符将字符串分成三部分。这将在字符串中搜索分隔符,如果找到分隔符,则返回一个3的元组,其中包含分隔符之前的部分,分隔符本身以及分隔符之后的部分。如果没有找到分隔符,则返回一个包含原始字符串和两个空字符串的3元组。 

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found,

returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing the original string and two empty strings. 

str_data = 'nihao,python,hello,yy'
str_var = str_data.partition(',')
print(str_var,  len(str_data))

#执行结果
('nihao', ',', 'python,hello,yy') 21




str_data = 'nihao,python,hello,yy'
str_var = str_data.partition('=')
print(str_var,  len(str_data))

#执行结果
('nihao,python,hello,yy', '', '') 21

replace(self, old, new, count=-1, /)                      ##返回一个副本,其中所有出现的子字符串old都被new替换。替换的最大次数。-1(默认值)表示替换所有匹配项。如果给出了可选参数count,则只替换第一次出现的count.

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace.

-1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.  

str_data = 'nihao,python,hello,yy,nihao,nihao'
str_var = str_data.replace('nihao', 'shiji', 2)
print(str_data)
print(str_var)

#执行结果
nihao,python,hello,yy,nihao,nihao

shiji,python,hello,yy,shiji,nihao

rjust(self, width, fillchar=' ', /)                 右对齐       ##返回一个长度为width右对齐的字符串,使用指定填充字符填充(默认使用空格)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space). 

str_data = 'nihao,python,hello,yy,nihao,nihao'
str_var = str_data.rjust(50, '#')
print(str_var)

#执行结果
#################nihao,python,hello,yy,nihao,nihao

split(self, /, sep=None, maxsplit=-1)                          ## 返回字符串中的列表,使用sep作为分隔符分隔字符串。用来分割字符产的字符。None(默认值)表示根据任何空格分隔,并丢弃结果中的空字符串。

Return a list of the words in the string, using sep as the delimiter string.

sep

The delimiter according which to split the string.

None (the default value) means split according to any whitespace,

and discard empty strings from the result.

maxsplit          最大分隔次数

Maximum number of splits to do.                  最大分隔次数

-1 (the default value) means no limit.            -1表示无限制 

按指定分隔符分割字符串,返回一个列表包含所有的字符串。

str_data = "1,2,0"
str_var = str_data.split(',')
print(str_var)

#执行结果
['1', '2', '0']

进程已结束,退出代码0


strip(self, chars=None, /)                      删除字符串左右两侧的空格                     ##返回删除前导和尾随空格的字符串文本,如果给出的chars不是默认值,则删除chars中的字符

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead. 

str_data = '    nihao\t,hello     '
str_var = str_data.strip()
print(str_data)
print(str_var)

#执行结果
  nihao	,hello     
nihao	,hello

进程已结束,退出代码0

四.格式化输出

python中的格式化:

使用format方法

语法:

f/F"{你要展示内容}{你要展示的内容}..."

指定宽度和对齐方式,以及填充字符

{name:填充字符对齐方式宽度},使用*填充对齐方式宽度,之间不使用任何分隔符。

{name:*^20}: ^居中对齐

{name:*<20}: <向左对齐

{name:*>20}: >向右对齐

例:格式化输出:
    姓名       年龄        性别        家庭住址
    xxx       xxxx
   list_data = [{name: xxx, age: xxx, gender: xxx, address}, .....]
  包含居中对齐,向左对齐, 向右对齐

1.使用F/f' ' 格式化输出:

list_data = [{'name': 'xiaohong', 'age': 18, 'gender': '男', 'address': '陕西省西安市'}]
print(F'我的名字叫{list_data[0].get("name"):*^10}, 我的年龄是{list_data[0].get("age"):*<6}, '
      F'我的性别是{list_data[0].get("gender"):*^5}, 我的家庭住址 
      {list_data[0].get("address"):*>20}.')



###    将名字居中对齐(使用*填充,宽度10),年龄向左对齐(使用*填充,宽度6),性别居中对齐(使用*填充,宽度5),家庭住址向右对齐(使用*填充,宽度20)
#执行结果
我的名字叫*xiaohong*, 我的年龄是18****, 我的性别是**男**, 我的家庭住址是**************陕西省西安市.

2.使用str.format输出:‘{0}{1}对应format(参数1,参数2)’  可以将format中的元素按元组处理,前面的0,1,2代表元组中的下标进行访问。

list_data = [{"name": 'xiaohong', 'age': 18, 'gender': '男', 'address': '陕西省西安市'}]
print('我的名字叫{0:*^10}, 我的年龄是{1:*<6}, '
      '我的性别是{2:*^5}, 我的家庭住址是{3:*>20}.'.format(list_data[0].get('name'),
                                              list_data[0].get('age'),
                                              list_data[0].get('gender'),
                                              list_data[0].get('address')))


#执行结果
我的名字叫*xiaohong*, 我的年龄是18****, 我的性别是**男**, 我的家庭住址是**************陕西省西安市.

进程已结束,退出代码0

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shadow_58

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值