print("hello")
print(a)
print("hello"+a)
- variable
- string with functions
- number with functions
- boolean
- input("enter a name: ")
int(input("enter a num: "))
float(input("enter a num: "))
- list_mutable
# format
friend = ["mary", "mick", "bob", "helen", "hery"]
friend2 = ["jack", "rose"]
# print
print(friend)
print(friend[0])
print(friend[0:])
print(friend[:3])
print(friend[0:2])
print(friend[0:3:1])
# function
friend.append("jack")
friend.extend(friend2)
friend.insert(2, "jim")
friend.remove("mary")
friend.clear()
-
tuple_unmuatable
# format
coordinate = (0.1, 0.5)
# print
print(coordinate[0])
print(coordinate.index(0.5)
- function
def say_hi(name, age):
print("hello "+ name + " you are "+ str(age))
say_hi("yujing",30) # call function, no return value
def cube(num):
return num*num*num # return value
result=cube(3) # call function
print(result)
- if statement (True or False)
def max_num(num1, num2, num3):
if num1>=num2 and num1>=num3:
return num1
elif num2>=num1 and num2>=num3:
return num2
else:
return num3
print(max_num(333, 33, 3))
num1 = float(input("enter the first number "))
op = input("enter the operator ")
num2 = float(input("enter the second number "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
else:
print("invalid operator")
- dictionary key:value
convertMonth = {"jan":"janurary", "Feb":"Feberary", "Mar":"March", "Apr":"April", "May":"May"}
print(convertMonth)
print(convertMonth["jan"])
print(convertMonth.get("jan"))
print(convertMonth.get("luv", "invalid month"))
- while loop
i = 1
while i<=10:
print(i)
i += 1
print("done the loop")
secret_word = "giraffe"
guess_word = ""
guess_count = 0
guess_limit = 3
out_of_guess = False
while guess_word != secret_word and not out_of_guess:
if guess_count < guess_limit:
guess_word = input("Enter guess word ")
guess_count += 1
else:
out_of_guess = True
if out_of_guess:
print("out of guess, you lost!")
else:
print("you win!")
- for loop
friends = ["jim", "mary", "jack", "john"]
for index in range(len(friends)):
if index == 0:
print("the first iteration. and it is " + friends[index])
else:
print("it is not the first iteration.")
# range(10) 0,1,2,3,4,5,6,7,8,9
# range(3, 10) 3,4,5,6,7,8,9
# len(friends) 4
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result *= base_num
return result
print(raise_to_power(2, 4))
# translator vowers to G/g
def translator(phrase):
translation = "" # 存放new string
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation += "G"
else:
translation += "g"
else:
translation += letter
return translation
print(translator(input("Enter a phrase: ")))
- 2D lists & nested loops
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
for row in number_grid:
for col in row:
print(col)
- comments
# this a comment
# print("hello, python")
- try except
# error treatment
try: # normal code block
answer = 10 / 0
result = int(input("Enter a number: "))
print(result)
except ValueError as err: # specific error
print(err)
except ZeroDivisionError: # specific error
print("divided by zero.")
except: # error
print("there is an error in program.")
- read & write
# read file
students = open("students_record", "r") # open file
print(students.readable()) # 判断是否是可读模式
print(students.read()) # 读取其中内容
print(students.readlines()) # 读取其中内容,以list输出
print(students.readlines()[1]) # 读取某一行的内容
for student in students.readlines(): # 按行读取其中内容
print(student)
students.close() # close file
# append
students = open("students_record", "a") # append content on file
students.write("tobby - 49")
students.write("\namy - 66\n") # 需要添加"\n"以换行
students.close()
# write
students = open("students_record", "w") # overwite on exist file or create a new file
students.write("tobby - 49")
students.close()
- module & pip?
- 类和对象
class question:
def __init__(self, prompt, answer): # 初始化对象
self.prompt=prompt
self.answer=answer
# 建立多项选择实验
from template import question
questions=[
question("what's the color of banana?\na.red\nb.yellow\nc.green\n", "b"), # 实例化对象a
question("what's the color of apple?\na.red\nb.yellow\nc.green\n", "a") # 实例化对象b
]
score=0
for question in questions: # 遍历list
answer=input(question.prompt)
if question.answer==answer:
score+=1
print("you get "+str(score)+"/"+str(len(questions))+" correction")
- 对象函数
class student:
def __init__(self, name, gpa, score): # 初始化对象
self.name=name
self.gpa=gpa
self.score=score
def honor(self):
if(self.gpa>=3.5):
return True
else:
return False
from template import student
student1=student("Mary", 3.1, 80)
student2=student("Jack", 3.9, 92)
if (student1.honor()):
print(student1.name+" has an honor.")
else:
print(student1.name+" doesn't have an honor.")
- 类继承
class chef: # 基类
def make_salad(self):
print("the chef can makes salad.")
def make_stake(self):
print("the chef can makes stake.")
def make_special_dish(self):
print("the chef can makes bbq.")
from template import chef
class chinesechef(chef): # 派生类 chinesechef继承了chef的属性
def make_special_dish(self): # 方法重写。overwrite基类的方法
print("the chef can makes fried_rice.")
def make_orange_chicken(self):
print("the chef can makes orange_chicken")
from test2 import chinesechef
from template import chef
chef1=chef()
chef2=chinesechef()
chef1.make_salad()
chef1.make_special_dish()
chef2.make_salad()
chef2.make_special_dish()
chef2.make_orange_chicken()
- python interpreter