Python - Variabel & Tipe Data
Salah satu karakteristik utama python dibandingkan dengan bahasa pemrograman lain adalah variabel yang non-deklaratif (tidak perlu dideklarasikan) dan tidak bersifat strongly typed (tipe variabel dapat berubah dengan assignment baru).
Untuk operasi aritmetika, berikut operator yang disediakan dalam python:
Operator untuk integer:
+ - * / // % **
Operator untuk float:
+ - * / **
Ekspresi boolean:
- kata kunci:
True
danFalse
(perhatikan huruf besar) ==
sama dengan:5 == 5
menghasilkanTrue
!=
tidak sama dengan:5 != 5
menghasilkanFalse
>
lebih besar dari:5 > 4
menghasilkanTrue
>=
lebih besar dari atau sama dengan:5 >= 5
menghasilkanTrue
<
lebih kecil dari:5 < 6
menghasilkanTrue
<=
lebih kecil dari atau sama dengan:5 <= 5
menghasilkanTrue
Operator logika:
and
,or
, andnot
True and False
True or False
not True
x = 1
print(x)
y = "test"
print(y)
x = 1
x = "string"
print(x)
x = 1
print(type(x))
x = "string"
print(type(x))
x = 0.1
print(type(x))
x = 0.1
type(x)
x
2**3
Selanjutkan, berikut akan dibahas tipe data dasar dalam python.
Bilangan
- Integer dan float berfungsi seperti halnya dalam bahasa pemrograman lain
- Tidak memiliki operator unary increment (x++) atau decrement (x–)
- Tipe bawaan lainnya: bilangan long integer dan bilangan kompleks
x = 3
print(type(x)) # Prints "<type 'int'>"
print(x) # Prints "3"
print(x + 1) # Addition; prints "4"
print(x - 1 ) # Subtraction; prints "2"
print(x * 2 ) # Multiplication; prints "6"
print(x ** 2) # Exponentiation; prints "9"
x += 1
print(x) # Prints "4"
x *= 2
print(x) # Prints "8"
y = 2.5
print(type(y)) # Prints "<type 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
Boolean
Python mengimplementasikan semua operator yg umumnya berlaku untuk logika Boolean, tetapi menggunakan kata dalam bahasa Inggris bukan simbol (seperti &&, ||, dll).
t = True
f = False
print (type(t)) # Prints "<type 'bool'>"
print (t and f) # Logical AND; prints "False"
print (t or f) # Logical OR; prints "True"
print (not t) # Logical NOT; prints "False"
print (t != f) # Logical XOR; prints "True"
String
Contoh fungsi dan operasi untuk string:
- Mencetak (print) :
print(str1)
- Menggabungkan:
str1 + str2
hello = 'hello' # String literals can use single quotes
world = "world" # or double quotes; it does not matter.
print(hello) # Prints "hello"
print(len(hello)) # String length; prints "5"
hw = hello + ' ' + world # String concatenation
print(hw) # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
print(hw12) # prints "hello world 12"
x = 23
y = 52
name = "Alice"
str1 = f"{name}'s numbers are {x} and {y}, and their sum is {x + y}"
str1
str1 = "a: %s" % "string"
print(str1)
str2 = "b: %f, %s, %d" % (1.0, 'hello', 5)
print(str2)
str3 = "c: {}".format(3.14)
print(str3)
String mempunyai sejumlah metode/fungsi bawaan yang sangat membantu.
s = "hello"
print(s.capitalize()) # Capitalize a string; prints "Hello"
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " hello"
print(s.center(7)) # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)')) # Replace all instances of one substring with another;
# prints "he(ell)(ell)o"
print(' world '.strip()) # Strip leading and trailing whitespace; prints "world"
str1 = "Hello, World!"
print(str1)
print(str1.upper())
print(str1.lower())
str1.replace('l', 'p')
Cheatsheet Bilangan (cred @gto76)
Types
<int> = int(<float/str/bool>) # Or: math.floor(<float>)
<float> = float(<int/str/bool>) # Or: <real>e±<int>
<complex> = complex(real=0, imag=0) # Or: <real> ± <real>j
<Fraction> = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1)
<Decimal> = decimal.Decimal(<str/int>) # Or: Decimal((sign, digits, exponent))
'int(<str>)'
and'float(<str>)'
raise ValueError on malformed strings.- Decimal numbers can be represented exactly, unlike floats where
'1.1 + 2.2 != 3.3'
. - Precision of decimal operations is set with:
'decimal.getcontext().prec = <int>'
.
Basic Functions
<num> = pow(<num>, <num>) # Or: <num> ** <num>
<num> = abs(<num>) # <float> = abs(<complex>)
<num> = round(<num> [, ±ndigits]) # `round(126, -1) == 130`
Math
from math import e, pi, inf, nan, isinf, isnan
from math import cos, acos, sin, asin, tan, atan, degrees, radians
from math import log, log10, log2
Statistics
from statistics import mean, median, variance, stdev, pvariance, pstdev
Random
from random import random, randint, choice, shuffle
<float> = random()
<int> = randint(from_inclusive, to_inclusive)
<el> = choice(<list>)
shuffle(<list>)
Bin, Hex
<int> = ±0b<bin> # Or: ±0x<hex>
<int> = int('±<bin>', 2) # Or: int('±<hex>', 16)
<int> = int('±0b<bin>', 0) # Or: int('±0x<hex>', 0)
<str> = bin(<int>) # Returns '[-]0b<bin>'.
Bitwise Operators
<int> = <int> & <int> # And
<int> = <int> | <int> # Or
<int> = <int> ^ <int> # Xor (0 if both bits equal)
<int> = <int> << n_bits # Shift left (>> for right)
<int> = ~<int> # Not (also: -<int> - 1)
Cheatsheet String (cred @gto76)
<str> = <str>.strip() # Strips all whitespace characters from both ends.
<str> = <str>.strip('<chars>') # Strips all passed characters from both ends.
<list> = <str>.split() # Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False) # Splits on \n,\r,\r\n. Keeps them if 'keepends'.
<str> = <str>.join(<coll_of_strings>) # Joins elements using string as separator.
<bool> = <sub_str> in <str> # Checks if string contains a substring.
<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
<bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
<int> = <str>.find(<sub_str>) # Returns start index of first match or -1.
<int> = <str>.index(<sub_str>) # Same but raises ValueError if missing.
<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
<str> = <str>.translate(<table>) # Use `str.maketrans(<dict>)` to generate table.
<str> = chr(<int>) # Converts int to Unicode char.
<int> = ord(<str>) # Converts Unicode char to int.
- Also:
'lstrip()'
,'rstrip()'
. - Also:
'lower()'
,'upper()'
,'capitalize()'
and'title()'
.
Property Methods
+---------------+----------+----------+----------+----------+----------+
| | [ !#$%…] | [a-zA-Z] | [¼½¾] | [²³¹] | [0-9] |
+---------------+----------+----------+----------+----------+----------+
| isprintable() | yes | yes | yes | yes | yes |
| isalnum() | | yes | yes | yes | yes |
| isnumeric() | | | yes | yes | yes |
| isdigit() | | | | yes | yes |
| isdecimal() | | | | | yes |
+---------------+----------+----------+----------+----------+----------+
- Also:
'isspace()'
checks for'[ \t\n\r\f\v…]'
.