1.从用户那里获取信息
name = "Alex" print("hello" + name)
2.让python成为你的计算器
1 print(4+5) 2 print(3-2) 3 print(2*3) 4 print(1/3) 5 print(((2+3)/3+5)*5) 6 print(2**10)
3.python语法基本介绍
Python基本数据类型一般分为:数字、字符串、列表、元组、字典、集合这六种基本数据类型。浮点型、复数类型、布尔型(布尔型就是只有两个值的整型)、这几种数字类型。列表、元组、字符串都是序列。
print(7 + "8") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
#查看数据类型 print(type("a")) <class 'str'> print(type(7)) <class 'int'> print(type(4.5)) <class 'float'>
变量存储在内存中的值,这就意味着在创建变量时会在内存中开辟一个空间。基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。因此,变量可以指定不同的数据类型,这些变量可以存储整数,小数或字符。
length = 10 width = 20 area = length * width print(area)
表达式,数字和类型转换
print(7 + 8.5)
base = 3 height = 6 area = (base * height)/2 print("The area is :" + str(area))
4.定义功能
def greeting(name, department): print("Welcome, " + name) print("You are part of " + department) greeting("blake", "AI engineering")
5.返回值
def triangle_area(base, height): return base * heigth / 2 area_a = triangle_area(3, 2) area_b = triangle_area(4, 5) sum = area_a + area_b print("The sum of areas is : " + str(sum))
6.while循环
def attempt(n): x=0 while(x<n): print("Attempt" + str(x)) x += 1 print("Done") attempt(5)
#用户登录输错用户名举例 username = get_username() while not vaild_username(username): print("It's not vaild name,please try again") username = get_username()
7.无限循环以及如何打破它们
#无限循环 while x%2 ==0: x = x / 2 #方法 while x!=0 and x%2 ==0: x = x / 2
8.一些循环示例
#1-10的乘积 product = 1 for n in range(1,10): product = product * n print(product)
#特定间隔温度转换 def to_celsius(x): return (x -32)*5/9 for x in range(0,101,10): print(x,to_celsius(x))
9.嵌套循环
#乘法表 for x in range(1,10): for y in range(x,10): print(str(x)+ "*" +str(y)+ "=" +str(x*y),end=" ") print()
#比赛行程,两两对抗 teams = ["Dragons", "Wolves", "Dog", "Pandas", "Unicorns"] for home_team in teams: for away_team in teams: if home_team != away_team: print(home_team + " VS " +away_team)
10.递归
def factorial(n): if n<2: return 1 return n * factorial(n-1)