Sei sulla pagina 1di 11

3-basic-python

October 8, 2018

1 Basic Python
1.1 Print Statements and Comment
In [1]: print("Hello World!")

# this is a comment line


# anything starts with # will be ignored

def a():
"""
comment
input:
output:
"""
return

Hello World!

test

In [171]: x = 10
x

Out[171]: 10

1.2 Variables
1.2.1 Integer, Float, and String
In [172]: people = 100 # integer
people

Out[172]: 100

In [173]: temperature = 36.0 # float


temperature

1
Out[173]: 36.0

In [174]: room_name = "Room 1" # string


room_name

Out[174]: 'Room 1'

1.2.2 List
In [2]: matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[0])

matrix2 = list(matrix)
matrix2[0][0] = 3
print(matrix)

[1, 2, 3]
[[3, 2, 3], [4, 5, 6]]

In [176]: fruits = [] # empty list


fruits = ["apple", "banana"] # list with 2 elements
fruits

Out[176]: ['apple', 'banana']

In [177]: example_list = ["this is string", 10] # list with different types of elements
example_list

Out[177]: ['this is string', 10]

In [178]: # add element to a list


fruits = ["apple", "banana"]
fruits.append("orange")
fruits

Out[178]: ['apple', 'banana', 'orange']

In [179]: # accessing list elements


fruits[0]

Out[179]: 'apple'

In [180]: fruits[-2]

Out[180]: 'banana'

In [181]: fruits.index("orange")

Out[181]: 2

2
In [182]: "orange" in fruits

Out[182]: True

In [183]: "grape" in fruits

Out[183]: False

In [184]: fruits[1:3] + ["mango", "avocado"] + [fruits[-1]]

Out[184]: ['banana', 'orange', 'mango', 'avocado', 'orange']

1.2.3 Dictionary
In [185]: customer = {} # empty dictionary
customer = {"name": "John", "age": 30} # dictionary with key -> value pair
customer

Out[185]: {'age': 30, 'name': 'John'}

In [186]: # add new key,value to dictionary


customer = {"name": "John", "age": 30}
customer["email"] = "john@example.com"
customer[9] = 10
customer[7] = 16
customer

Out[186]: {7: 16, 9: 10, 'age': 30, 'email': 'john@example.com', 'name': 'John'}

In [187]: # accessing individual value using key


customer["email"]

Out[187]: 'john@example.com'

In [188]: # accessing dictionary keys and values


customer.keys()

Out[188]: [9, 'age', 7, 'name', 'email']

In [189]: customer.values()

Out[189]: [10, 30, 16, 'John', 'john@example.com']

In [190]: customer.items()

Out[190]: [(9, 10),


('age', 30),
(7, 16),
('name', 'John'),
('email', 'john@example.com')]

3
In [191]: for value in customer.values():
print(value)

10
30
16
John
john@example.com

In [192]: customer["name"] = "Budi"


customer2 = dict(customer)
customer2["name"] = "John"
list_customer = [customer, customer2]
print(list_customer)

[{9: 10, 'age': 30, 7: 16, 'name': 'Budi', 'email': 'john@example.com'}, {9: 10, 'age': 30, 'em

In [193]: list1 = [1,2]


list2 = list(list1)
list2[0] = 5
print(list2)
print(list1)

[5, 2]
[1, 2]

In [194]: print("Budi" in customer.values())


print(customer["name"] == "Budi")
print(customer)

True
True
{9: 10, 'age': 30, 7: 16, 'name': 'Budi', 'email': 'john@example.com'}

In [195]: customer["profil"] = {"alamat": "jakarta", "telp": 1}


customer["profil"].values()

Out[195]: [1, 'jakarta']

1.2.4 Tuple
In [196]: # tuple is similar to list but immutable once created
coordinate = (0, 5)
coordinate

Out[196]: (0, 5)

4
In [197]: colors = ("red", "green", "blue")
colors
Out[197]: ('red', 'green', 'blue')
In [198]: # colors[1] = "red"
In [199]: len(customer.values())
Out[199]: 6

1.2.5 Set
In [200]: unique_numbers = {1, 2, 3, 3}
unique_numbers = set([1, 2, 3, 3])
unique_numbers
Out[200]: {1, 2, 3}
In [201]: # add element to a set
unique_numbers.add(2)
unique_numbers.add(2)
unique_numbers.add(2)
unique_numbers.add(2)
unique_numbers.add(2)
unique_numbers.add(4)
unique_numbers.update([1, 5])
unique_numbers
Out[201]: {1, 2, 3, 4, 5}

1.2.6 Concat String with Number


In [202]: text = str(people) + " people"
text
Out[202]: '100 people'
In [203]: "There are %i people" % people
Out[203]: 'There are 100 people'
In [204]: "There are " + str(people) + " people"
Out[204]: 'There are 100 people'

1.2.7 Concat String


In [205]: text = "Room: " + room_name
text
Out[205]: 'Room: Room 1'
In [206]: " ".join(["There are", str(people), "people in", room_name])
Out[206]: 'There are 100 people in Room 1'

5
1.3 Basic Mathematical Operations
In [207]: 20 + 2

Out[207]: 22

In [208]: 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

Out[208]: 6.75

In [209]: from __future__ import division

10 / 3 # div

Out[209]: 3.3333333333333335

In [210]: 10.0 / float(3) # floating point division


# round(10.0 / 3, 3)

Out[210]: 3.3333333333333335

In [211]: 10 % 3 # mod

Out[211]: 1

1.3.1 Comparison
In [212]: 5 > 2

Out[212]: True

In [213]: 10 <= 100

Out[213]: True

In [214]: 5 - 95 > 0

Out[214]: False

In [215]: 7 == 7.0

Out[215]: True

In [216]: True and False

Out[216]: False

6
1.4 Function
In [217]: # function with no return statement
def print_hello_world():

def print_string():
print("halo")

print("Hello World!")
print(1)
print_string()

print_hello_world()

Hello World!
1
halo

In [218]: a = [1, 2, 3]

def kali2(n):
return n * 2

map(lambda n: n * 3, a)

Out[218]: [3, 6, 9]

In [219]: # function with return statement


def is_even(number):
return number % 2 == 0

In [220]: is_even(3)

Out[220]: False

1.5 IF Statement
In [221]: number = 99
def guess_number(guess):
if guess < number:
print("Wrong guess! try with larger number")
elif is_even(number):
print("even")
elif guess > number:
print("Wrong guess! try with smaller number")
else:
print("Correct! Congratulations!")
print(1)

7
1

In [222]: guess_number(5)
guess_number(100)
guess_number(99)

Wrong guess! try with larger number


Wrong guess! try with smaller number
Correct! Congratulations!

1.6 Looping
In [223]: range(1, 10)

Out[223]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [224]: # looping in range [0, n), n is excluded


for i in range(1, 10):
print(i)

1
2
3
4
5
6
7
8
9

In [225]: # looping in range [a, b), b is excluded


for i in range(5, -5, -1):
print(i)

5
4
3
2
1
0
-1
-2
-3
-4

8
In [226]: # looping over list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

apple
banana
orange

In [227]: # print all elements in a list


# with function enumerate to get the index of each element
print "The fruits are:"
for i, fruit in enumerate(fruits):
print(i, fruit)

The fruits are:


(0, 'apple')
(1, 'banana')
(2, 'orange')

In [228]: numbers = [] # create empty list

# loop from 0 to 9
# add number to the list if the number is even
for i in range(10):
if is_even(i):
numbers.append(i)

numbers

Out[228]: [0, 2, 4, 6, 8]

In [229]: # while loop

i = 2
numbers = []

while i < 10:


print(i)
numbers.append(i)
i = i + 1

numbers

2
3
4

9
5
6
7
8
9

Out[229]: [2, 3, 4, 5, 6, 7, 8, 9]

1.7 Class and Object


In [230]: # declaring class
class Person:

# __init__ is default initialization method for class


# this is usually used to initialize attributes
def __init__(self):
self.name = "John"
self.age = 30

p = Person()
print("Person name: %s" % p.name)
print("Person age: %i" % p.age)

Person name: John


Person age: 30

In [231]: class Person:

def __init__(self, name, age):


self.name = name
self.age = age

def get_name(self):
return self.name

def edit_age(self, new_age):


self.age = new_age

def __get_age(self):
return self.age

person = Person("John", "30")


person.get_name()
# person.__get_age()

10
Out[231]: 'John'

In [232]: person.edit_age(35)
person.age

Out[232]: 35

1.8 External Resources


1. Learn Python the Hard Way

11

Potrebbero piacerti anche