Untitled
unknown
plain_text
2 years ago
8.6 kB
13
Indexable
Learn Python
basics
controlflow
condition
if_else_statement.py
# Simple if statement
def simple_if_statement():
biscuits = 17
if biscuits >= 5:
print("It's time for tea!")
# Simple if-else statement
def simple_if_else_statement():
today = "work"
if today == "holiday":
print("Lucky you!")
else:
print("Keep your chin up, then.")
# Ternary operator
def ternary_operator():
sun = True
print("It’s a day now!" if sun else "It’s a night for sure!")
# Nested if-else
def nested_if_else():
x = 123
if x < 100:
print('x < 100')
else:
if x == 100:
print('x = 100')
else:
print('x > 100')
print('This will be printed only because x >= 100')
def elif_statement():
light = "red" # there can be any other color
if light == "green":
print("You can go!")
elif light == "yellow":
print("Get ready!")
elif light == "red":
print("Just wait.")
else:
print("No such traffic light color, do whatever you want")
#############################################################################
ternary_operator()
function
global_local_scopes.py
phrase = "Let it be"
def global_printer():
print(phrase) # we can use phrase because it's a global variable
global_printer() # Let it be is printed
print(phrase) # we can also print it directly
phrase = "Hey Jude"
global_printer() # Hey Jude is now printed because we changed the value of phrase
def printer():
local_phrase = "Yesterday"
print(local_phrase) # local_phrase is a local variable
printer() # Yesterday is printed as expected
# print(local_phrase) # NameError is raised
###################################################
x = "global"
def outer():
x = "outer local"
def inner():
x = "inner local"
def func():
x = "func local"
print(x)
func()
inner()
print(x)
outer() # "func local"
###################################################
# Khong the thay doi gia tri cua mot bien toan cuc o ben trong mot function ma khong dung tu khoa global
x = 1
def print_global():
print(x)
print_global() # 1
# def modify_global():
# print(x)
# x = x + 1
#
#
# modify_global() # UnboundLocalError: local variable 'x' referenced before assignment
def global_func():
global x
print(x)
x = x + 1
global_func() # 1
global_func() # 2
global_func() # 3
###################################################
iteration
for_loop.py
# In Python, the process of repetitive execution of the same block of code is called an iteration.
# There are two types of iteration:
# Definite iteration, where the number of repetitions is stated in advance.
# Indefinite iteration, where a code block executes as long as the condition stated in advance is true.
def for_loop_syntax():
oceans = ['Atlantic', 'Pacific', 'Indian', 'Southern', 'Arctic']
for ocean in oceans:
print(ocean)
for char in 'magic':
print(char)
def range_function():
for i in range(5):
print(i)
for i in range(5, 45, 10):
print(i)
for _ in range(10):
print("Hello")
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
if my_list[i] % 2 != 0:
my_list[i] *= 2
for i in my_list:
print(i)
def nested_loop():
names = ['Rose', 'Daniel']
surnames = ['Miller', 'Smith']
for name in names:
for surname in surnames:
print(name, surname)
##########################
range_function()
loop_control.py
def break_example():
pets = ['dog', 'cat', 'parrot']
for pet in pets:
print(pet)
if pet == 'cat':
break
count = 0
while True:
print("I am Infinite Loop")
count += 1
if count == 13:
break
def continue_example():
pets = ['dog', 'cat', 'parrot']
for pet in pets:
if pet == 'dog':
continue
print(pet)
def pass_example():
while True:
pass
while_loop.py
# The while loop requires the introduction of extra variables, iteration takes up more time.
# Thus, the while loop is quite slow and not that popular.
def while_loop():
number = 0
while number < 5:
print(number)
number += 1
print('Now, the number is equal to 5')
datatype
operation
boolean_operations.py
a = True and True # True
b = True and False # False
b = True or False # True
c = False or False # False
to_be = True # to_be is True
not_to_be = not to_be # not_to_be is False
# The precedence of boolean operations: not -> and -> or
print(False and False or not False)
# Values of non-boolean types, such as integers or strings, are called truthy or falsy.
# The following values are evaluated to False in Python:
# constants defined to be false: None and False,
# zero of any numeric type: 0, 0.0,
# empty sequences and containers: "", [], {}.
print(0.0 or False) # False
print("False" and True) # True
print("" or False) # False
print(True and None) # None
# The operators or and and return one of their operands, not necessarily of the boolean type
# not always returns a boolean value.
print(False or 5 and 100) # 100
# and returns the first value if it evaluates to False, otherwise it returns the second value.
# or returns the first value if it evaluates to True, otherwise it returns the second value.
print(False or '')
print(not (False or {}))
comparison.py
"""
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity
in membership
not in negated membership.
"""
a = 5
b = -10
c = 15
calculated_result = a == b + c # True
result = 10 < (100 * 100) <= 10000 # True, the multiplication is evaluated once
a = 1
b = 2
c = 3
e = 4
f = 5
g = 6
print(b + c <= e or f + g >= e == f == 5) # False
print((b + c <= e or f + g >= e) == (f == 5)) # True
integer_arithmetic.py
def basic_operations():
print(10 + 10) # 20
print(100 - 10) # 90
print(10 * 10) # 100
print(77 / 10) # 7.7
print(77 // 10) # 7
print(23 % 3) # 2
print(-11 // 5) # -3
print(-11 % 5) # 4
print(11 // -5) # -3
print(11 % -5) # -4
print(10 ** 2) # 100
basic_operations()
__init__.py
SPEED_OF_LIGHT = 299792458
from basics.datatype import *
# String
def string_type():
print("hello")
print("world")
# Numerical types
def numerical_types():
print(11) # int - signed integers
print(11.1) # float - floating-point numbers
print(SPEED_OF_LIGHT)
# Boolean type
def boolean_type():
is_open = True
is_close = False
# Printing types
def printing_types():
print(type('hello')) # <class 'str'>
print(type("world")) # <class 'str'>
print(type(100)) # <class 'int'>
print(type(-50)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(-0.5)) # <class 'float'>
main.py
moduleandpackage
importmodule
module_loading.py
import math
import test
from super_module import super_function
# from module_name import * : load toan bo ten duoc dinh nghia trong module
test.test_function()
print(test.test_variable)
super_function()
print(math.pi)
print(['red', 'green', 'yellow'])
super_module.py
def super_function():
print("Super module")
test.py
test_variable = 123456789
def test_function():
print("import module")
pep8.py
print("Hello World")
print("Hello")
x = 1
y = 3
x, y = y, x
x = x * 2 - 1
# Indention
def long_function_name1(var_one, var_two, var_three,
var_four):
print(var_one)
def long_function_name2(
var_one, var_two, var_three,
var_four):
print(var_one)
my_list = [
1, 2, 3,
4, 5, 6
]
# Line break
income = (1 + 2
+ 3 * (3 - 2)
- 4)
simple_programs.py
# help(len)
#
# user_name = input()
# print(type(user_name)) # String
# print("Hello, " + user_name)
#
# user_name = input("Please, enter your name: ")
# print("Hello, " + user_name)
#
# num = int(input("What's your favorite number: "))
# print(num * 10)
first_name = "Han"
last_name = "Bui"
print(first_name + last_name) # HanBui
print(first_name, last_name) # Han Bui
x = "Hello" # str
x = 1 # intEditor is loading...
Leave a Comment