print('Hello wrold!')
import random
print('猜猜我现在心里想的数字是那个?')
result = random.randint(0, 20)
while True:
# 下面两个语句用于显示自己产生的随机数
# print('生成的数字是')
# print(result)
a = int(input('请输入你猜的数字:\n'))
if a == result:
print('你猜对了')
print('但是没有奖励哦')
break
else:
print('你猜错了哈哈哈')
# 基本的数学运算符程序
print('9 + 3\t\t= ',9+3)
print('9 - 3\t\t= ',9-3)
print('9 * 3\t\t= ',9*3)
print('9 // 4\t\t = ',9//4) # 真除法
print('9 / 4\t\t = ',9/4) # 取整除法
print('9 % 3\t\t= ',9%3)
print('9 ** 3\t\t= ',9**3)
print('(2+3) * 2 \t\t= ',(2+3)*2)
# 字符串的乘法
print('\'-\' * 10\t= ','*'*10)
from fractions import Fraction
# 格式如下
# 前一位数是分子,后一位书是分母
y = Fraction(2,4)
# 自动约分
print("2/4 =",y)
input('Please enter an integer:')
print('Please enter an other integer')
integer1 = int(input('integer1 = '))
print('The integer of that you entered is ',integer1)
str1 = input('Please enter an str\nstr1 = ')
print('The string of you entered is ','\'',str1,'\'')
float1 = float(input('Please enter a floating-point number: '))
print('The floating-point number you entered is ',float1)
# 先输入字符串变量
price_str = input('Please enter the price of Apple/kg:')
weight_str = input('Please enter the weight of Apple/kg:')
# 将字符串转换为浮点数类型
price = float(price_str)
weight = float(weight_str)
money = price * weight
# 格式化输出
print('Apple %.1f per kilogram and you want to buy %.1f kilograms apple, you need to pay for %.1f RMB.'%(price, weight, money))
# string's format
name = 'Xiaoming'
print('Name is %s'%name)
# floatint-point number's format
float1 = float(input('请输入一个数字:'))
print('The number of you entered is %02.1f' % float1)
# Percent's format
scale = 0.25
print('%.2f%%' % scale * 100)
import keyword
print(keyword.kwlist)
import random
# 石头 1 剪刀 2 布 3
print('这是一个猜拳游戏,石头(1) 剪刀(2) 布(3)')
player = int(input('请输入你要出的拳:\t '))
computer = random.randint(1,3)
print('电脑出的拳是:\t\t',computer)
# 比较胜负
if player == computer:
print('双方平局')
elif (computer-player == 1 or (computer == 3 and player == 1)):
print('玩家胜利')
else:
print('电脑胜利')
while
i = 0
while i < 5:
print('Hello Python')
i=i+1
死循环
i = 0
while i < 5:
print('Hello Python')
# i=i+1
0 - 100求和
i = 0
Sum = 0
while i <= 100:
Sum += i
i = i+1
print('The sum from 0 to 100 is',Sum)
0-100偶数求和(if 和 while的嵌套)
# 偶数求和
i = 0
Sum = 0
while i <= 100:
if i%2==0:
Sum += i
i = i+1
print('The sum of even number from 0 to 100 is',Sum)
两种方式实现打印小星星(循环嵌套初体验)
# 打印小星星
# 利用循环嵌套实现
# rows = 1
# while rows <= 4:
# num = 0
# while num < rows:
# # 输出一行不会换行
# print('*',end='')
# num += 1
# # 此处再实现换行操作
# print('')
# rows += 1
# 利用字符串的乘法实现
rows = 0
while rows < 5:
print('*'*(rows+1))
rows += 1
循环嵌套实现99乘法表
# 利用循环嵌套实现99乘法表
rows = 1
cols = 1
while rows <= 9:
cols = 1
while cols <= rows:
# 不换行,普通方法
# print(cols,end=' * ')
# print(rows,end=' = ')
# print(rows*cols,end='\t')
# 格式化的方法
print('%d * %d = %d\t'%(cols,rows,cols*rows),end='')
cols += 1
print('')
rows += 1
for i in range(1,10):
for j in range(1,i+1):
print("%sx%s=%s" % (j,i,j*i),end="\t")
print()
print("你想对誰说一句话,请留下Ta的名字:")
a=input()
print(a)
print("接下来请输入你想说的一句话:")
b=input()
print("你想说的话是"+b)
print("那么接下来就是见证奇迹的时刻了")
print(a+"你知道吗,有一句话藏在我心里很久了,今天我必须要说给你听,那就是"+b+"\n")
# The first function
def text1():
print('Hello World1!')
print('Hello World2!')
# The second function
def text2():
text1()
print('Hello World3!')
# Nested Function
text2()
name_list=["张三","李四"]
print(name_list)
for s in name_list:
print(s)
print(name_list[1])
# list.sort() # 升序排序 # list.sort(reverse=True) # 降序排序 # list.clear() # 清除数据 # list.pop(x) # 弹出第x个元素,无参数则默认最后一个元素弹出 # list.count(数据) # 返回数据出现的次数 # list.index(数据) # 获取数据第一次出现的索引(即下标) # list.remove(数据) # 删除第一个出现的指定数据 # list.append(数据) # 末尾追加 # list.insert(self,index,object) # index后面插入一个对象 # list.extend(self,iterable) # 在当前列表的末尾插入一个新的列表 # del list[index] # 从内存中删除数据 # list.reverse() # 列表的翻转(逆序)
info_tuple=('许嵩',18,1.80)
# print(type(info_tuple))
print(info_tuple[0])
# The init of empty tuple
empty_tuple=()
# single tuple
single_tuple=(5)
print(type(single_tuple))
# 以上类型为 int类型
# # single tuple
# # plus ','
# single_tuple=(5,)
# print(type(single_tuple))
# # The above type is tuple
# methods
# be like to list
# tuple.count()
# tuple.index()
name=('许嵩',18,1.80)
print('%s,aged %d, %.2f high' %name)
# List to tuple and Tuple to list
# tuple(list)
# list(tuple)
# 字典中的键集合
# dictionary.keys()
# 值集合
# dictionary.values()
# 所有键值元组列表
# Items()
# Key:Value(key must be only)
# 键值对之间用 , 分隔
# 列表是有序的对象集合
# 字典是无序的对象集合
xiaoming = {
'name':'小明',
'age':'18',
#'gender':True,
'height':'1.75',
'weight':'50'
}
# 1.统计键值对的数目
print(len(xiaoming))
# 2.合并字典
temp_dic={
'爱好':"睡觉",
'喜欢':'玩'
}
# 如果有同样的键,那么会覆盖原来字典里面的键的值
xiaoming.update(temp_dic)
# 3.clear()清空所有的键值对
# xiaoming.clear()
# 4.for 遍历输出
# k为键
for k in xiaoming:
print('%s-%s\n'%(k,xiaoming[k]))
# # 1.取值
# print(xiaoming['age'])
# # 2.增加/修改
# xiaoming['age'] = 19
# # 3.删除
# xiaoming.pop('age')
print(xiaoming)
# 使用键值对,存储描述一个物体的相关信息
# 将 多个字典 放在一个列表里面,再进行遍历
card_list=[
{'name':'I love Vae',
'qq':'10128513777',
'phone':'123123123'
},
{'name':'lisi',
'qq':'26731595557',
'phone':'12343556787'
}
]
for k in card_list:
print(k)
str1 = "Hello Python"
str2 = 'My favourite singer is "Vae"'
length = str1.__len__()
print(length)
print(str1)
print(str2)
for char in str2:
print(char)
# methods
# len(str) calculate length of str
# count(data) calculate the times of the data
# if use index if the Substring isn't exist,there will be error
# index(data) return index of the data
str_boy="Gou yi Zhou"
length_girl=str_boy.__len__()
for s in str_boy:
print(s)
# Jude space
str_space = " \t\n\r"
print(str_space)
# Jude digit
# But can't use in float-point number
# str_num = "1"
str_num = "\u00b2"
print(str_num)
print(str_num.isdecimal()) # 纯数字
print(str_num.isdigit()) # 数字加Unicode编码
print(str_num.isnumeric()) # 数字加Unicode加中文数字
字符串的方法
str_1 = "Hello world!"
# 1.string.startswith(str) check the string's start
print(str_1.startswith("He"))
# 2.string.endswith(str) check the string's end
print(str_1.endswith("ld!"))
# 3.string.find("str") find "str" in string
# if "str" not here this function will return -1
# return str's index
print(str_1.find("llo"))
print(str_1.find("abd"))
# 4.replace string
# return another string but can't change the old string
print(str_1.replace("world","python"))
print(str_1)
# Example:The lecture from internet
# Demand :Order output and center the output of the following
poem = ["登鹳雀楼",
"王之涣",
"白日依山尽",
"黄河入海流",
"欲穷千里目",
"更上一层楼"
]
for poem_str in poem:
print("|%s|" % poem_str.center(10))
for poem_str in poem:
print("|%s|" % poem_str.ljust(10))
for poem_str in poem:
print("|%s|" % poem_str.rjust(10))
# str_1 = "\t\nHello \t\n\tWorld!"
# Example:The lecture from internet
# Demand :Order output and center the output of the following
poem = ["\t\t\n\n登鹳雀楼\t\t",
"王之涣\n\n",
"白日依山尽",
"黄河入海流",
"欲穷千里目",
"更上一层楼"
]
for poem_str in poem:
print("|%s|" % poem_str.strip.center(10))
for poem_str in poem:
print("|%s|" % poem_str.ljust(10))
for poem_str in poem:
print("|%s|" % poem_str.rjust(10))
poem = "登鹳雀楼\t 王之涣\t 白日依山尽\t 黄河入海流\t 欲穷千里目\n\t更上一层楼\n\t"
# 1.去掉所有空白字符
# 2.将字符串连接为一个大的字符串
print(poem)
# 1.拆分字符串
# 大字符串拆分为多个列表
poem_list=poem.split()
print(poem_list)
# 2.拼接
result = " ".join(poem_list) # 接受列表返回以恶搞字符串
print(result)
# 字符串[开始索引:结束索引:步长] # 用于间隔切片
# 顺序和倒叙索引从右到左是 -1
# 想要获取最后的字符 则结束索引为0
num_str = "0123456789"
print("截取2-6索引的字符串")
num_str_1 = num_str[2:6]
print(num_str_1,'\n')
print("截取2到末尾索引的字符串")
num_str_1 = num_str[2:]
print(num_str_1,'\n')
print("截取0-6索引的字符串")
num_str_1 = num_str[0:6]
print(num_str_1,'\n')
print("截取0-6索引的字符串")
num_str_1 = num_str[:6]
print(num_str_1,'\n')
print("截取全部的字符串")
num_str_1 = num_str[:]
print(num_str_1,'\n')
print("截取全部的字符串,2为步长")
num_str_1=num_str[::2]
print(num_str_1,'\n')
print("截取从索引1开始的字符串,2为步长")
num_str_1=num_str[1::2]
print(num_str_1,'\n')
print("取最后的那个字符")
num_str_1=num_str[-1]
print(num_str_1,'\n')
print("截取从2索引开始的字符串,到倒数第二个字符为止")
num_str_1=num_str[2:-1]
print(num_str_1,'\n')
print("截取从右向左第二个开始的字符串,到该字符串的最后端")
num_str_1=num_str[-2:]
print(num_str_1,'\n')
print("截取从头开始的字符串,-1为步长")
num_str_1=num_str[0::-1]
print(num_str_1,'\n')
print("截取全部的字符串,-1为步长,即从右向左截取") # 即逆序
num_str_1=num_str[::-1]
print(num_str_1,'\n')
# max
# len
# del
# min
# slice 切片
# 字典无法进行切片
str = "abcdefg"
print(str)
print(len(str),"\n")
print(max(str),"\n")
print(min(str),"\n")
list_1 = [1,2,3,4,5,6]
list_1[1::2]
print(list_1[1::2])
# 列表的乘法
list_1 = [1,2]
list_1 = list_1*2
print(list_1)
# 字典同样无法做乘法
list_1 = [1,2]
list_1+=[3,4]
# 使用+号后会生成一个新的列表
# 而字符串的append(追加元素),extend(追加列表)函数则会把内容整合到原来的那个列表里去
print(list_1)
名片管理系统
主程序
import cards_tool
# 功能实现
# 1.欢迎界面
# 2.功能
while True:
cards_tool.show_menu()
a = input("请输入你要选择的功能:")
print("你输入的操作代码是:", a)
if a in ["1", "2", "3"]:
# 新增名片
if a=="1":
cards_tool.new_card()
# pass
# 显示全部
elif a =="2":
cards_tool.show_all()
# pass
# 查询名片
elif a=="3":
cards_tool.search_card()
# pass
# pass仅仅是个占位符,保证程序的正确
# pass
# 如果输入0则退出系统
elif a == "0":
print("欢迎再次使用【名片管理系统】")
break
# pass关键字不会执行任何的操作
# pass
# 输入的内容错误,让用户重新选择
else:
print("您输入的格式不正确,请重新输入!")
工具程序
def show_menu():
"""显示菜单"""
print("*" * 50)
print("欢迎使用名片管理系统 V1.0")
print("")
print("1.新增名片")
print("2.显示全部")
print("3.搜索名片")
print("")
print("0.退出系统")
print("*" * 50)
# 使用字典的特性来保存一个物体的全部信息
card_list = []
def new_card():
'''新增名片'''
print("-" * 50)
print("\t\t新增名片")
print("-" * 50)
# 1. 提示用户输入名片的详细信息
name_str = input("请输入姓名:")
phone_str = input("请输入电话:")
qq_str = input("请输入QQ:")
email_str = input("请输入邮箱:")
# 2. 使用用户输入的信息来建立一个名片字典
card_temp = {"name": name_str,
"phone": phone_str,
"qq": qq_str,
"email": email_str
}
# 3. 将名片字典添加到列表中
card_list.append(card_temp)
# print(card_list) 调试语句 可忽略
# 4.
print("添加 %s 的名片成功" % name_str)
def show_all():
"""显示所有的名片"""
print("-" * 50)
print("\t\t显示所有的名片")
print("-" * 50)
# 判断是否有名片记录
if len(card_list) == 0:
print("没有名片记录,请使用新建功能添加")
# return 可以返回一个函数的执行结果
# return 下方的代码不会被执行
# 返回到调用函数的位置去
# 不返回任何的结果
return
# 打印表头
for name in ["姓名", "电话", "qq", "邮箱"]:
print(name, end="\t\t\t")
print()
print("=" * 50)
for card_temp in card_list:
print("%s\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t" % (
card_temp["name"], card_temp["phone"], card_temp["qq"], card_temp["email"]))
print("=" * 50)
def search_card():
"""搜索名片"""
print("-" * 50)
print("\t\t搜索名片")
print("-" * 50)
# 1. 提示用户输入要搜索的姓名
find_name = input("请输入要搜索的姓名:")
# 2. 遍历名片列表,查询要搜索的姓名,如果没有,需要提示用户
for card_temp in card_list:
if card_temp["name"] == find_name:
print("找到了")
print("姓名\t\t\t电话\t\t\tQQ\t\t\temail")
print("=" * 50)
print("%s\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t" % (
card_temp["name"],
card_temp["phone"],
card_temp["qq"],
card_temp["email"]))
print("=" * 50)
deal_card(card_temp)
break
else:
print("抱歉,没找到")
def deal_card(card_temp):
"""
处理名片的信息
:param card_temp: 字典中的东西
:return:
"""
# 1.提示用户进行什么操作
# print(card_temp)
action_str = input("请选择你要进行的操作 "
"[1] 修改 [2] 删除 "
"[0] 返回上一级菜单")
if action_str == "1":
# 修改操作
card_temp["name"] = input_card_info(card_temp["name"], "name:")
card_temp["phone"] = input_card_info(card_temp["phone"], "phone:")
card_temp["qq"] = input_card_info(card_temp["qq"], "qq:")
card_temp["email"] = input_card_info(card_temp["email"], "email")
print("修改名片")
elif action_str == "2":
# 删除操作
card_list.remove(card_temp)
print("删除名片成功!")
elif action_str == "0":
return
def input_card_info(card_temp, tip_message):
"""
输入名片信息
:param card_temp: 字典中的原有的值
:param tip_message: 输入的值
:return:
"""
# 1.提示用户输入信息内容
result_str = input(tip_message)
# 2. 针对用户的输入进行判断,如果用户输入了内容,直接就返回结果
if len(result_str) > 0:
return result_str
# 3.如果没有输入内容,返回字典中原有的值
else:
return card_temp
递归求阶乘
def factorial(number):
if number <=1:
return 1
else:
return number * factorial(number - 1)
# range函数生成从0 到 里面的数的值 - 1
for i in range(11):
print("%2d! = %d"% (i,factorial(i)))