Professional Documents
Culture Documents
Python Basic
I. Comments II. Literal constants
- Comments are any text to the right of the #symbol - An example of a literal constant is a number like
and is mainly useful as notes for the reader of the 10, 3.14, or a string like ‘Hello world’ or
program “Hello!!!! World”
- Example - It is called a literal because it is literal, you use its
value literally. The number 10 always represents
print(‘hello world’) # here print is a function itself and nothing else, it is a constant because its
value cannot be changed. Hence, all these are
or referred to as literal constants
- There are two types of numbers : - A string is a sequence of characters. They are
1. Integer basically a bunch of words
Numbers without decimal point - Single quotes (‘ ’)
You can specify strings using single quotes
2, 4, 26, 4234 etc. Example
if name.startswith(‘Chan’) :
print(‘Yes, the string starts with
“Chan”.’)
if ‘a’ in name :
print(‘Yes, it contains the string “a”.’)
if name.find(‘and’) != -1 :
print(‘Yes, it contains the string
“and”.’)
delimiter = ‘_*_’
mylist = [‘Brazil’, ‘Russia’, ‘India’,
‘China’]
print(delimiter.join(mylist))
output :
Yes, the string starts with “Chan”
Yes, it contains the string “a”
Yes, it contains the string “and”
Brazil_*_Russia_*_Indian_*_China
Explanation :
Here, we see a lot of the string methods in
action. The startswith method is used to find
out whether the string starts with the given
string. The in operator is used to check if a
given string is a part of the string.
- Sometimes strings need to be constructed using - Espace sequences allows us to use those symbols
other information, format() method is used to do which assigned for a specific task
so. - Suppose we have a string in which a single quote
Example is used in between the string like
age = 2 ‘What’s your name’
name = ‘Programming Hub’
4. \r carriage return
txt = ‘hello\nworld!’
print(txt)
output:
world!
5. \t tab
txt = ‘hello\tworld!’
print(txt)
output:
hello world!
6. \b backspace
txt = ‘hello \bworld!’
print(txt)
output:
helloworld!
output : Hello
output : Hello
VII. Raw String VIII. Variables
- In python, strings prefixed with r or R, such as - Using just literal constants can soon become
r‘…’ and r“…” boring, we need some way of storing any
- It treat backslashes \ as literal characters. information and manipulate them as well
- Raw strings are useful when handling strings that - This is where variables come into the picture.
use a lot of backslashes, such as windows paths - Variables are exactly what the name implies, their
and regular expression patterns value can vary, i.e., you can store anything using a
- Example variable
- Variables are just parts of your computer’s
txt = r ‘It\’s good enough’ memory where you store some information
print(txt)
- Unlike literal constants, you need some method of
output : accessing these variables and hence you give them
It\’s good enough names
- Example
- An identifier is a name given to entities like class, - Every value in Python has a datatype. Since
functions, variables, etc. It helps to differentiate everything is an object in Python programming,
one entity from another data types are actually classes and variables are
- The rules are : instance (object) of these classes. These are
1. Identifiers can be a combination of letters in various data types in Python. Some of the
lowercase (A to Z) or digits (0 to 9) or an important types are listed below :
underscore (_). - (1) Python numbers
Include : (1) integers, (2) float, and (3)
myClass, var_1 and print_this_to_screen complex
(valid) We can use the type() function to know which
class a variable or a value belongs to
2. An identifier cannot start with a digit Similarly, the isinstance() function is used to
check if an object belongs to a particular class
1variable (invalid), variable1 (valid) Integer number can be of any length, it is only
limited by the memory available
3. Keywords cannot be used as identifiers Float number is accurate up to 15 decimal
places. Integer and float are separated by
global, var (invalid) decimal points. 1 is an integer, 1.0 is a float
Complex numbers are written in the form, x +
4. We cannot use special symbols like !, @, #, $, yj, where x is the real part and y is the
% etc. in out identifier imaginary part. j is supposed to be the square
root of minus one (√-1)
myName@, !myName (invalid) Example
5. An identifier can be of any length integerNumber = 5
print(type(integerNumber))
- Things to remember
floatNumber = 2.0
1. Python is a case – sensitive language. It means, print(type(floatNumber))
Variable and variable are not the same
2. Always give the identifiers a name that makes complexNumber = 1 + 2j
sense. While c = 10 is a valid name, writing print(isinstance(complexNumber, complex))
count = 10 would make more sense
output :
3. Multiple words can be separated using an <class 'int'>
underscore, like <class 'float'>
True
This_is_a_long_variable = “….”
- (2) Python strings
String is a sequence of Unicode characters. We
can use single quotes or double quotes to
represent strings. Multi line strings can be
denoted using triple quotes, ‘‘‘ or “ “ “
You can return a range of characters by using
slice syntax
Specify the start index and the end index,
separated by a colon, to return a part of the
string
Example
myName = “Achmad Adyatma Ardi”
print(type(myName))
print(myName)
output :
<class ‘str’>
Achmad Adyatma Ardi
llo
Traceback (most recent call last):
File "E:\profWork\dataEngineer_course\file\
learn_python.py", line 9, in <module>
myName[2] = 'o'
TypeError: 'str' object does not support item
assignment
print(myList[2])
print(myList[0:1])
print(myList[1:])
output :
<class 'list'>
Python
[1]
[2.2, 'Python']
[1, 2, 4]
#t[0] = 5
print("my_tupples [0] = is ", my_tupples[0])
#t[1] = 'Achmad'
print("my_tupples [1] = is ", my_tupples[1])
# generates error
# tupples are immutable
my_tupples [0] = 1
print(my_tupples)
output :
<class 'tuple'>
my_tupples [0] = is 5
my_tupples [1] = is Achmad
my_tupples [0:1] = is (5, 'Achmad', (1+3j))
Traceback (most recent call last):
File "E:\profWork\dataEngineer_course\file\
learn_python.py", line 15, in <module>
my_tupples [0] = 1
TypeError: 'tuple' object does not support
item assignment
#data type
print(type(my_sets))
#performs operations
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
print(x.union(y))
output :
my_sets = {1, 2, 3, 4, 5}
<class 'set'>
{1, 2, 3}
{'google', 'apple', 'microsoft', 'banana',
'cherry'}
Traceback (most recent call last):
File "E:\profWork\dataEngineer_course\file\
learn_python.py", line 20, in <module>
print(slice_set[1])
TypeError: 'set' object is not subscriptable
https://www.programiz.com/python-
programming/variables-datatypes
output :
<class 'dict'>
Ford
False
2020
['red', 'white', 'blue']
2020
4
Example
#convert integer to float
int_to_float = float(5)
print("int_to_float (5): ",int_to_float)
output :
int_to_float (5): 5.0
float_to_int1 (10.6): 10
float_to_int2 (-10.6): -10
str_to_float ('2.5'): 2.5
int_to_str (25) : 25
Traceback (most recent call last):
File "E:\profWork\dataEngineer_course\file\
learn_python.py", line 20, in <module>
str_to_int = int('1p')
ValueError: invalid literal for int() with
base 10: '1p'
list_to_set ([1, 2, 3]): {1, 2, 3}
set_to_tuple ({5, 6, 7}): (5, 6, 7)
str_to_list : ['H', 'e', 'l', 'l', 'o', ' ',
'W', 'o', 'r', 'l', 'd', '!']
list_to_dict [[1, 2],[3, 4]] : {1: 2, 3: 4}
tuple_to_dict [[1, 2],[3, 4]] : {3: 26, 4: 44}
the result is : {1: 'Achmad', 2: 'Qonita', 3:
'Laiba'}
paired dictionary : {1: 2, 'Achmad': 'Qonita'}
Traceback (most recent call last):
File "E:\profWork\dataEngineer_course\file\
learn_python.py", line 55, in <module>
dict_not_pair = dict([[1, 2, 3],["Achmad",
"Qonita"]])
ValueError: dictionary update sequence element
#0 has length 3; 2 is required
Object How to write Python programs
Indentation