0% found this document useful (0 votes)
19 views14 pages

PYTHON

The document provides examples of Python code covering basic concepts like variables, data types, operators, conditional statements, functions, loops, lists, dictionaries, files and exceptions. It includes examples of input/output, arithmetic operations, conditional logic, defining and calling functions, for/while loops, list operations and methods, dictionary usage and reading/writing to files.

Uploaded by

huongmy2611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views14 pages

PYTHON

The document provides examples of Python code covering basic concepts like variables, data types, operators, conditional statements, functions, loops, lists, dictionaries, files and exceptions. It includes examples of input/output, arithmetic operations, conditional logic, defining and calling functions, for/while loops, list operations and methods, dictionary usage and reading/writing to files.

Uploaded by

huongmy2611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

num1 = input("enter a number: ")

num2 = input("enter another number: ")


result = float(num1) + float(num2)
print(result)
Float số ngẫu nhiên
Int là số nguyên

MAD LIBS
color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
celebrity = input("Enter a celebrity: ")

print("Roses are " + color)


print(plural_noun + " are blue")
print("I love " + celebrity)

LIST
friends = ["kiki", "lala", "hehe", "loli"]
print(friends[2])
->Python will print “hehe”

friends = ["kiki", "lala", "hehe", "loli"]


print(friends[-1])
->Python will print “loli”

friends = ["kiki", "lala", "hehe", "loli"]


print(friends[0])
->Python will print “kiki”

friends = ["kiki", "lala", "hehe", "loli"]


print(friends[-2])
->Python will print “hehe”

friends = ["kiki", "lala", "hehe", "loli"]


print(friends[-4:-1])
Print "kiki", "lala", "hehe"

LIST FUNCTIONS
EMERGE
lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "loli"]
friends.extend(lucky_numbers)
print(friends)
->Python will print ['kiki', 'lala', 'hehe', 'loli', 2, 3, 4,
5, 6, 7, 8]
THÊM VÀO 1 PHẦN TỬ
friends = ["kiki", "lala", "hehe", "loli"]
friends.append("lulu")
print(friends)
->Python will print ['kiki', 'lala', 'hehe', 'loli', 'lulu']
THẾ MỘT PHẦN TỬ VÀO MỘT VỊ TRÍ CỤ THỂ
lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "loli"]
friends.insert(1, "kelly")
print(friends)
->['kiki', 'kelly', 'lala', 'hehe', 'loli']

lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "loli"]
friends.remove("hehe")
print(friends)
->['kiki', 'lala', 'loli']

lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "loli"]
friends.clear()
print(friends)
->[]

lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "loli"]
friends.pop()
print(friends)
->['kiki', 'lala', 'hehe']
lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "loli"]
print(friends.index("lala"))
->1

lucky_numbers = [2, 3, 4, 5, 6, 7, 8]
friends = ["kiki", "lala", "hehe", "hehe", "loli"]
print(friends.count("hehe"))
->2

THỨ TỰ TĂNG DẦN


friends = ["kiki", "lala", "hehe", "hehe", "loli"]
friends.sort()
print(friends)
->['hehe', 'hehe', 'kiki', 'lala', 'loli']
ĐẢO NGƯỢC THỨ TỰ
lucky_numbers = [88, 3, 24, 82, 76, 22]
friends = ["kiki", "lala", "hehe", "hehe", "loli"]
lucky_numbers.reverse()
print(lucky_numbers)
->[22, 76, 82, 24, 3, 88]
COPY
lucky_numbers = [88, 3, 24, 82, 76, 22]
friends = ["kiki", "lala", "hehe", "hehe", "loli"]

friends2 = friends.copy()
print(friends2)
->['kiki', 'lala', 'hehe', 'hehe', 'loli']

TUPLE: similar to list but can’t change the order or


modify, add, clear, remove, it is fixed
FUNCTIONS
def say_hi(name, age):
print("Hello " + name + ", You are " + age)
say_hi("Huong", "10")
say_hi("My", "22")
->Hello Huong, You are 10
Hello My, You are 22
or
def say_hi(name, age):
print("Hello " + name + ", You are " + str(age))
say_hi("Huong", 10)
say_hi("My", 22)
->Hello Huong, You are 10
Hello My, You are 22

RETURN STATEMENT
def cube(num):
return num*num*num
result = cube(3)
print(result)
->27

IF STATEMENT
is_male = False
is_tall = False

if is_male or is_tall:
print("You are a male or tall or both")
else:
print("You are neither male nor tall")
->You are neither male nor tall
is_male = True
is_tall = False

if is_male and is_tall:


print("You are a male or tall or both")
else:
print("You are neither male nor tall")
->Python will print You neither male nor tall
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

is_male = False
is_tall = True

if is_male and is_tall:


print("You are tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
print("You are tall and not a male")
else:
print("You are neither male nor tall")
->Python will print You are tall and not a male
*********************************************************
*********
TÌM SỐ LỚN NHẤT
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(4,8,3))->Python will print 8
TÌM SỐ NHỎ NHẤT
def mi_num(num1, num2, num3):
if num1 <= num2 and num1 <= num3:
return num1
elif num2 >= num1 and num2 <= num3:
return num2
else:
return num3

print(mi_num(87, 22, 9))


->Python will print 9

== bằng
!= khác
TÌM SỐ KHÁC NUM2
def equal_num(num1, num2, num3):
if num1 != num2:
return num1
else:
return num3

print(equal_num(4, 4, 6))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
BUILDING A BETTER CALCULATOR
num1 = float(input("Enter the first number: "))
op = input("Enter 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 result")
OR
num1 = input("Enter the first number: ")
op = input("Enter operator: ")
num2 = input("Enter the second number: ")

if op == "+":
print(float(num1) + float(num2))
elif op == "-":
print(float(num1) - float(num2))
elif op == "/":
print(float(num1) / float(num2))
elif op == "*":
print(float(num1) * float(num2))
else:
print("Invalid result")

DICTIONARIES
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"Ma": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}

print(monthConversions["Nov"]
->Python will print november
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"Ma": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}

print(monthConversions["Nov"] + " is my favorite month")


->Python will print November is my favorite month

print(monthConversions.get("h", "Not a valid key"))


->Not a valid key

print(monthConversions.get("Jul"))
->July
*********************************************************
*********
WHILE LOOP
i = 1
while i <= 10:
print(i)
i += 1

print("Done with loop")

->1
2
3
4
5
6
7
8
9
10
Done with loop
i = 10
while i >= 0:
print(i)
i -= 1

print("Done with loop")


->
10
9
8
7
6
5
4
3
2
1
0
Done with loop

BUILDING A BASIC GAME


secret_word = "mixhunk"
guess = ""

while guess != secret_word:


guess = input("Enter guess: ")

print("You win!")

->
Enter guess: hh
Enter guess: jj
Enter guess: mixhunk
You win!

secret_word = "mixhunk"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and
not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count +=1
else:
out_of_guesses = True

if out_of_guesses:
print("Out of guesses, YOU LOSE")
else:
print("You win!")

secret_word = "Wie geht's"


guess = ""
guess_count = 0
guess_limit = 10
out_of_guesses = False

print(" WELLCOME TO THE MINI GAME ")


while guess != secret_word and
not(out_of_guesses):
if guess_count <= guess_limit:
guess = input("Enter secret word: ")
guess_count += 1
else:
out_of_guesses = True

if out_of_guesses == True:
print("You lose")
else:
print("You win")

FOR LOOP
for letter in "Hello":
print(letter)
->
H
e
l
l
o

days = ["monday", "tuesday", "wednesday"]


for day in days:
print(day)
->
monday
tuesday
Wednesday

for index in range(5):


print(index)
->
0
1
2
3
4

for index in range(3, 9):


print(index)
->
3
4
5
6
7
8

days = ["monday", "tuesday", "wednesday"]


for index in range(len(days)):
print(days[index])
->
monday
tuesday
wednesday
for index in range(6):
if index == 0:
print("first iteration")
else:
print("not first")
->
first iteration
not first
not first
not first
not first
not first

EXPONENT FUNCTION
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result

print(raise_to_power(3, 4))
-> 81

2D loops
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
print(number_grid[0])
-> [1, 2, 3]

print(number_grid[0][2])
->3

NESTED LOOPS
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]

for row in number_grid:


print(row)
->[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[0]

number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
for row in number_grid:
for col in row:
print(col)
->1
2
3
4
5
6
7
8
9
0
TRANSLATE A PHRASE
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
TRY EXCEPT
try:
number = int(input("Enter a number: "))
print(number)
except:
print("Invalid number")

try:
hihi = 2/0
except ZeroDivisionError as err:
print(err)
-> division by zero

try:
hihi = 26/11
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print("Divided by zero")
except ValueError:
print("I know hehee")

READING FILES
You have to create a file

hehe = open("hehe", "r")


print(hehe.readable())
hehe.close()
->True

hehe = open("hehe", "w")


print(hehe.readable())
hehe.close()
->False

hehe = open("hehe", "r")


print(hehe.read())
hehe.close()
hehe = open("hehe", "r")
print(hehe.readline()) (1)
hehe.close()
->Python will print the first line

If you put print(hehe.readline()) after (1),


Python will print the next line

hehe = open("hehe", "r")


print(hehe.readlines())
hehe.close()
->['hehehehehe\n', 'jjjj\n', 'kkkkkk']

hehe = open("hehe", "r")


for hehes in hehe.readlines():
print(hehes)
hehe.close()
-> hehehehehe

jjjj

kkkkkk

WRITING AND APPENDING FILE

hehe = open("hehe", "a")


print(hehe.write("\nHello"))
hehe.close()
->

hehe = open("hehe", "w")


print(hehe.write("\nHello"))
hehe.close()

hehe = open("hehe1", "w")


print(hehe.write("\nHello"))
hehe.close()

You might also like