>Numbers
>String
str = "string can connect with . " . "like this"
>Lists
a = [1,3,8]
b= [34,45,56]
c= a+b;
c is [1,3,8 ,34,45,56]
a[0] is 1
a[-1] is 8
> a.append(66); a is [1,2,8,66]
> a.pop(); removes and return 66 last one
now a is a is [1,2,8]
> a.remove(66); remove and return first occurance of supplied value.
> a.del(66); only remove
> a.del(a[4]); only remove
> listChars = ['php','python','js'];
> multilist = [listChars, a, 'helo',5]; ok to do
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words) return True
nums = [1, 2, 3]
print(not 4 in nums) gives True
print(4 not in nums) gives True
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print(words)
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r')) gives 2
There are a few more useful functions and methods for lists.
max(list): Returns the list item with the maximum value
min(list): Returns the list item with minimum value
list.count(obj): Returns a count of how many times an item occurs in a list
list.remove(obj): Removes an object from a list
list.reverse(): Reverses objects in a list
numbers = list(range(10))
print(numbers)
gives [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers = list(range(3, 8))
print(numbers)
print(range(20) == range(0, 20)) is True
-------------------------
- comment
# this is comment. it atart with hatch
--------------
> input command
inputname = input("input your name");
inputage = input("input your age");
--------------------------
String formatting
fnum = 3.142546
print(' Name is {0} and age is {1}', format(name, age))
print(' float num is {0:.3f} ', format(fnum)) 3.142
nums = [4, 5, 6]
msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"
print("Hello ME".replace("ME", "world"))
#prints "Hello world"
print("This is a sentence.".startswith("This"))
# prints "True"
print("This is a sentence.".endswith("sentence."))
# prints "True"
print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."
print("AN ALL CAPS SENTENCE".lower())
#prints "an all caps sentence"
print("spam, eggs, ham".split(", "))
#prints "['spam', 'eggs', 'ham']"
------
print( f' fnum 1 is {fnum}'); #3.142546
print( f' fnum 1 is {fnum:.4f}'); #3.1425
------------
if condition :
#tab do something
elif condition2 :
#tab do something
else :
#tab do something
--------------------
Function
def add(x, y):
return x + y
def do_twice(func, x, y):
return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
----------------
Modules
#importing module
> import random
import random
for i in range(5):
value = random.randint(1, 6)
print(value)
> from math import pi
from math import pi, sqrt
from math import sqrt as square_root
from math import pi
print(pi)
--------------
try:
variable = 10
print(variable + "hello")
print(variable / 2)
except ZeroDivisionError:
print("Divided by zero")
except (ValueError, TypeError):
print("Error occurred")
variable = 10
print(variable + "hello")
print(variable / 2)
except ZeroDivisionError:
print("Divided by zero")
except (ValueError, TypeError):
print("Error occurred")
> try
> except
> finally
try:
print("Hello")
print(1 / 0)
except ZeroDivisionError:
print("Divided by zero")
finally:
print("This code will run no matter what")
------------------
Dictionaries
Just like lists, dictionary keys can be assigned to different values.
squares = {1: 1, 2: 4, 3: "error", 4: 16,}
nums = {
1: "one",
2: "two",
3: "three",
}
print(1 in nums) gives True
print("three" in nums) gives False
print(4 not in nums) gives True
pairs = {1: "apple",
"orange": [2, 3, 4],
True: False,
None: "True",
}
print(pairs.get("orange")) gives [2, 3, 4]
print(pairs.get(7)) gives None
print(pairs.get(12345, "not in dictionary")) gives not in dictionary
----------------
Tuples
Tuples are very similar to lists, except that they are immutable (they cannot be changed).
words = ("spam", "eggs", "sausages",)
create a list, dictionary, and tuple:
# list
list =
["one", "two"
]
# dictionary
dict =
{1:"one", 2:"two"
}
# tuple
tp =
(
"one", "two"
)
list =
# dictionary
dict =
# tuple
tp =
---------------
List Slices
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[2:6]) gives [4, 9, 16, 25]
print(squares[:7]) gives [0, 1, 4, 9, 16, 25, 36]
print(squares[7:]) gives [49, 64, 81]
List slices can also have a third number, representing the step
print(squares[2:8:3]) gives [4,25]
print(squares[1:-1]) gives [1, 4, 9, 16, 25, 36, 49, 64]
print(squares[7:5:-1]) gives [49,36]
----------------------
cubes = [i**3 for i in range(5)] gives [0, 1, 8, 27, 64]
print(cubes)
----------------
List Function
nums = [55, 44, 33, 22, 11]
if all([i > 5 for i in nums]):
print("All larger than 5")
if any([i % 2 == 0 for i in nums]):
print("At least one is even")
for v in enumerate(nums):
print(v)
-------------
> pypl
Python Package Installer