You are on page 1of 10

Python

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

# here print is a function


print(‘hello world’)

- Comments can be used to :


1) Explain assumptions
2) Explain problems you’re trying to solve
3) Explain important decisions
4) Explain important details
- Code tells you how while comments tell why
III. Number IV. String

- 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

2. Float ‘I am learning python3’.


Numbers with decimal point
 All white space i.e. spaces and tabs, within the
3.14, 4.29, 324.53, 93.2E-4 etc. quote, are preserved as they are
- Double quotes (“ ”)
- E notation indicates the power of 10 it means 1) Strings in double quotes work exactly the same
way as strings in single quotes
93.2E-4 = 93.2* 10^-4 2) Example

“What’s your name ?”

- Triple quotes (’’’ / “ “ “)


1) Multi – line strings can be specified using
triple quotes.
2) Single quotes and double quotes can be used
within the triple quotes
3) Example

‘‘‘ This is a multi – line string. This is the first


line.
This is the second line.
“what’s your name ?,” He asked. I said “Thon,
Py Thon.”
’’’

- Strings are immutable


1) Once a string is created, it cannot be changed
2) There is no separate char datatype in python
3) The single quoted and double quoted strings
are same
4) Strings are also objects and have methods
which do everything from checking part of a
string to stripping spaces!
5) The strings that you use in program are all
objects of the class str. Some useful methods of
this class are demonstrated in the next
example. For a complete list of such methods
6) Example
#this is a string object
name = ‘Chandrakant’

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.

The find method is used to locate the position


of the given substring within the string; find
returns -1 if it is unsuccessful in finding the
substring. The str class also has a neat method
to join the items of a sequence with the string
acting as a delimiter between each item of the
sequence and returns a bigger string generated
from this
V. Format method VI. Escape Sequences

- 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’

print(‘{0} is {1} years old and teaches more than


If it is entered in the above way, python will get
20 programming languages’.format(name, age)) confused with the starting and ending point of the
print(‘is {0} awesome ?’.format(name)) string. So in order to specify that single quotes
does not indicate the end of the string escape
output :
$ python format_mthd.py sequences are used
Programming Hub is 2 years old and teaches more - Type
than 20 programming languages 1. \’ single quote
Is Programming Hub awesome ?
txt = ‘it\’s alright’
Explanation : print(txt)
A string can use certain specifications and
output:
subsequently, the format method can be called to it’s alright
substitute those specifications with corresponding
arguments to the format method. 2. \backslash
Observe the first usage where we use {0} and this txt = ‘this will insert one \\ (backslash)’
corresponds to the variable name which is the first print(txt)
argument to the format method. Similarly, the
output:
second specification is {1} corresponding to age this will insert one \ (backslash).
which is the second argument to the format
method. Note that Python starts counting from 0 3. \n new line
which means that first position is at index 0,
second position is at index 1, and so on. txt = ‘hello\nworld!’
print(txt)
- String concatenation can also be used to get the
output:
same output but it is more error – prone so avoid hello
using string concatenation world!

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!

7. \ooo octal value


txt = "\110\145\154\154\157"
print(txt)

output : Hello

8. \xhh hex value


txt = "\x48\x65\x6c\x6c\x6f"
print(txt)

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

myName = ‘Achmad Adyatma Ardi’


IX. Identifier Manning X. Datatype

- 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)

#slice the characters from position 2 to


position 5 (not included)
myString = “Hello, World!”
print(myString[2:5])

#strings are immutable (generates error)


myName[2] = ‘o’
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

- (3) Python list


 List is an ordered sequence of items. It is one
of the most used datatype in Python and is very
flexible. All the items in a list do not need to be
of the same type
 Declaring a list is pretty straight forward. Items
separated by commas are enclosed within
brackets [ ]
 We can use the slicing operator [ ] to extract an
item or a range of items from a list. The index
starts from 0 in Python
 Lists are mutable, meaning the value of
elements of a list can be altered
 Example
myList = [1, 2.2, ‘Python’]
print(type(myList))

print(myList[2])
print(myList[0:1])
print(myList[1:])

#lists are mutable


a = [1, 2, 3]
a[2] = 4
print(a)

output :

<class 'list'>
Python
[1]
[2.2, 'Python']
[1, 2, 4]

- (4) Python tuple


 Tuple is an ordered sequence of items same as
a list. The only difference is that tuples are
immutable. Tuples once created cannot be
modified
 Tuples are used to write – protect data and are
usually faster than lists as they cannot change
dynamically
 It is defined within parentheses ( ) where items
are separated by commas
 We can use the slicing operator [ ] to extract
items but we cannot change its value
 Example
my_tupples = (5, 'Achmad', 1+3j)
print(type(my_tupples))

#t[0] = 5
print("my_tupples [0] = is ", my_tupples[0])

#t[1] = 'Achmad'
print("my_tupples [1] = is ", my_tupples[1])

#t[0:1] = '5, Achmad'


print("my_tupples [0:1] = is ",
my_tupples[0:3])

# 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

- (5) Python set


 Set is an unordered collection of unique items.
Set is defined by values separated by comma
inside braces { }.
 Items in a set are not ordered
 We can perform set operations like union,
intersection on two sets.
 Sets have unique values. They eliminate
duplicates
 Since, set are unordered collection, indexing
has no meaning. Hence, the slicing operator [ ]
does not work
 Example
my_sets = {5, 2, 3, 1, 4}

#printing set variable


print("my_sets = ", my_sets)

#data type
print(type(my_sets))

#sets eliminate duplicates


my_sets2 = {1, 2, 2, 3, 3, 3}
print(my_sets2)

#performs operations
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
print(x.union(y))

#indexing and slicing both are doesn't work


slice_set = {1, 2, 3}
print(slice_set[1])
print(slice_set[0:4])

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

- (6) Python dictionary


 Dictionary is an unordered collection of key –
value pairs
 It is generally used when we have a huge
amount of data
 Dictionaries are optimized for retrieving data.
we must know the key to retrieve the value
 In python, dictionaries are defined within
brackets “{ }” with each item being a pair in
the form key : value. Key and value can be of
any type
 We use key to retrieve the respective value.
But not the other way around
 Example
my_dict = {
"brand" : "Ford",
"electric" : False,
"year" : 1964,
"year" : 2020,
"colors" : ["red", "white", "blue"]
}

#dictionary data type


print(type(my_dict))

#retrieve data from dictionary items


print(my_dict["brand"])
print(my_dict["electric"])
print(my_dict["year"])
print(my_dict["colors"])

#duplicates not allowed (year has 2 keys)


print(my_dict["year"])

#dictionary length (duplicate not included)


print(len(my_dict))

output :

<class 'dict'>
Ford
False
2020
['red', 'white', 'blue']
2020
4

- Conversion between data types


a. We can convert between different data types
by using different type conversion functions
like int( ), float( ), str( ), etc
b. Conversion from float to int will truncate the
value (make it closer to zero)
c. Conversion to and from string must contain
compatible values
d. We can even convert one sequence to another
e. To convert to dictionary, each element must be
a pair

Example
#convert integer to float
int_to_float = float(5)
print("int_to_float (5): ",int_to_float)

#convert float to integer


float_to_int_1 = int(10.6)
float_to_int_2 = int(-10.6)
print("float_to_int1 (10.6): ",float_to_int_1)
print("float_to_int2 (-10.6):
",float_to_int_2)

#convert string to float


str_to_float = float("2.5")
print("str_to_float ('2.5'): ",str_to_float)

#convert int to string


int_to_str = str(25)
print("int_to_str (25) : ",int_to_str)

#convert doesn't compatible (generates error)


'''str_to_int = int('1p')
print("str_to_int ('lp'): ", str_to_int)'''

#convert one sequence to another


#1) convert list to set
list_to_set = set([1, 2, 3])
print("list_to_set ([1, 2, 3]): ",
list_to_set)

#2) convert set to tuple


set_to_tuple = tuple({5, 6, 7})
print("set_to_tuple ({5, 6, 7}): ",
set_to_tuple)

#3) convert string to list


str_to_list = list('Hello World!')
print("str_to_list :", str_to_list)

#to convert to dictionary, each element must


be a pair
#1) list to dictionary
list_to_dict = dict([[1, 2],[3, 4]])
print("list_to_dict [[1, 2],[3, 4]] :",
list_to_dict)

#2) tuple to dictionary


tuple_to_dict = dict([(3, 26), (4,44)])
print("tuple_to_dict [[1, 2],[3, 4]] :",
tuple_to_dict)
#3) create dictionary from 2 variables (zip)
(not paired variables haven't affect)
var1_keys = [1, 2, 3]
var2_value = ["Achmad", "Qonita", "Laiba"]
par_var = dict(zip(var1_keys, var2_value))
print("the result is :", par_var)

#3) to create dictionary each element must be


pair (best way)
dict_pair = dict([[1, 2],["Achmad",
"Qonita"]])
print("paired dictionary :", dict_pair)

dict_not_pair = dict([[1, 2, 3],["Achmad",


"Qonita"]])
print("not paired dictionary :",
dict_not_pair)

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

You might also like