0% found this document useful (0 votes)
19 views

Python

This document provides an overview of Python basics including collections, data structures, functions, and comprehensions. It demonstrates list comprehensions to generate new lists, dictionary comprehensions to generate new dictionaries, and functions with parameters and documentation strings. Functions are defined and called to show parameter passing and returning values. Lists are indexed, sliced, and have methods like append and remove applied.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python

This document provides an overview of Python basics including collections, data structures, functions, and comprehensions. It demonstrates list comprehensions to generate new lists, dictionary comprehensions to generate new dictionaries, and functions with parameters and documentation strings. Functions are defined and called to show parameter passing and returning values. Lists are indexed, sliced, and have methods like append and remove applied.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

PYTHON BASICS

Comprehensions Functions

C O L L E C T I O N S
>>> list_1 = [1, 2, 3, "a", "b"]

>>> list_2 = [True, [1, 2, 3]]


# Function_1

C h e a t S h e e t
>>> numbers = [4, 2, 1, 3] List Comprehensions
>>> def say_hi(name):
# Syntax
... print(f'Merhaba {name}')
list = [expression for item in iterable if condition]
Indexing & Slicing >>> squares = [x**2 for x in range(1, 11)] # Calling function

C O L L E C T I O N S
>>> print(squares) >>> say_hi('Miuul')
>>> list_1[3] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Merhaba Miuul
Data Structres 'a'
>>> evens = [f"{x}: even" for x in range(1,10) if x % 2 == 0] # Function_2
>>> txt_1 = 'Hello World!' >>> print(evens)
'Hello World!' >>>list_2[-1] ['2: even', '4: even', '6: even', '8: even']
>>> def summer(num_1, num_2):
[1, 2, 3] ... """
>>> txt_2 = "HELLO WORLD!" >>> even_odd = [f"{x}: even" if x%2 == 0 else f"{x}: odd" ... Sum of two numbers
# Integer (int) 'HELLO WORLD!' >>>list_1[0:4] for x in range(1,5)] ... Args:
>>> x = 2 [2, 3, 'a'] ... num_1: int, float
>>> long_txt = """

C O L L E C T I O N S
>>> print(even_odd) ... num_22: int, float
# Float Hello World, ['1: odd', '2: even', '3: odd', '4: even']
>>> x = 2.3 Welcome DSMLBC! ... Returns:
""" ... int, float
# Complex List Methods
'Hello World, \n Welcome DSMLBC!' ... """
>>> x = 2j + 1 Dictionary Comprehensions
... Return num_1 + num_2
>>> list_1 + list_2
Indexing & Slicing [1, 2, 3, 'a', 'b', True, [1, 2, 3]] # Syntax
Operations # Calling function
dict = {key_exp: value_exp for item in iterable if condition}
>>> summer(3, 4)
>>> txt_1[0] >>> list_1.append('c')
>>> dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 7
# Exponent [1, 2, 3, 'a', 'b', 'c']

C O L L E C T I O N S
'H'
>>> 2**3
8 >>> {k: v ** 2 for (k, v) in dictionary.items()} # Function_3
>>> txt_1[-1] >>> list_2.remove('True') {'a': 1, 'b': 4, 'c': 9, 'd': 16}
'!' >>> def find_volume(length=1, width=1, depth=1):
[[1, 2, 3]]
# Modulus / Remainder ... print(f'Length = {length}')
>>> 22%8 >>> {k.upper(): v for (k, v) in dictionary.items()}
>>> txt_1[1:4] ... print(f'Width = {width}')
6 'ell' >>> len(list_1) {'A': 1, 'B': 2, 'C': 3, 'D': 4}
... print(f'Depth = {depth}')
5
>>> {k.upper(): v*2 for (k, v) in dictionary.items()} ... volume = length * width * depth
# Integer Division >>> txt_1[:5]
>>> 22//8 {'A': 2, 'B': 4, 'C': 6, 'D': 8}
'Hello' >>> numbers.sort()
2 # Calling function
[1, 2, 3, 4]

C O L L E C T I O N S
>>> find_volume(1, 2, 3)
# Division String Methods Length = 1
>>> 22/8 >>> list_2.insert(1, False)
Width = 2
2.75 [True, False, [1, 2, 3]]
>>> len(txt_1) Loops Depth = 3

Lists
12 6
# Multiplication >>> numbers.pop()
>>> 3*3 >>> txt_1.upper() [4, 2, 1]
9 >>> find_volume(2, depth=3, width=4)
'HELLO WORLD!'
For Loop Length = 2
Numbers

# Subtraction >>> txt_2.lower() Width = 4

C O L L E C T I O N S
>>> 5-2 'hello world!' # Syntax Depth = 3
3 for <variable> in <list>: 24
>>> txt_1.replace("World", "Era") <code block> ... return volume
# Addition 'Hello Era!' >>> tuple = ("john", "mark", 1, 2)
>>> 2+2 >>> students = ["John", "Mark", "Venessa"]
4 >>> txt_1.split() >>> tuple[0] >>> for student in students: Local & Global Variables
['Hello', 'World!'] 'john' ... print(student)
John
>>> ' Hello World! '.strip() Mark >>> list_store = [1, 2] # Global variable
>>> tuple[1:3]
Strings

'Hello World!' Venessa

Tuples
('mark', 1)

C O L L E C T I O N S
>>> a = 2 >>> 'hello world!'.capitalize() >>> for index, student in enumerate(students):
... print(index, student) >>> def add_element(a, b):
>>> b = 7 'Hello world!' >> len(tuple)
... c=a*b
4 0 John
1 Mark ... list_store.append(c)
>>> a == b 2 Venessa
... print(list_store)
False
While Loop
>>> dict_1 = {"REG" : "Regression", >>> add_element(1, 9)
"LOG" : "Logistic Regression", >>> set_1 = {1, 2, 2, 3, 3, 3}
>>> a != b "CART": "Classification and Reg"}
# Syntax [1, 2, 9]

C O L L E C T I O N S
{1, 2, 3} while <condition>:
True
>>> dict_2 = {"REG": ["RMSE", 10]
<code to execute while the condition is true>
"LOG": ["MSE", 20] >>> set_2 = set([3, 4, 4, 5, 5, 5, 6]) Built-in Functions
>>> a > b "CART": ["SSE", 30]} {3, 4, 5, 6} >>> i = 1
>>> while i < 5:
False ... print(i) # lambda
Key - Value Methods ... if i==3: >>> summer = lambda a, b: a + b
Set Methods ... break
>>> a >= b >>> summer(3, 5)
>>> dict_1.keys() ... i+=1
False dict_keys(['REG', 'LOG', 'CART']) 1 8

C O L L E C T I O N S
2
>>> dict_1.values() >>> set_1.difference(set_2) 3 # map
>>> a < b dict_values(['Regression', 'Logistic Regression', {1, 2}
'Classification and Reg']) >>> while i < 5: >>> salaries = [1000, 2000, 3000, 4000, 5000]
True
>>> set_2.difference(set_1) ... i+=1 >>> list(map(lambda x: x * 20 / 100 + x, salaries))
>>> dict_1.items() {4, 5, 6} ... if i==3: [1200.0, 2400.0, 3600.0, 4800.0, 6000.0]
>>> a <= b dict_items([('REG', 'Regression'), ... continue
('LOG', 'Logistic Regression'), ... print(i)
True ('CART', 'Classification and Reg')]) >>> set_1.symmetric_difference(set_2)
2 # filter
{1, 2, 4, 5, 6} 4 >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> dict_1["REG"] 5

C O L L E C T I O N S
>>> (a > 1) & (b < 10) >>> list(filter(lambda x: x % 2 == 0, numbers))
'Regression' >>> set_1.intersection(set_2)
True {3} [2, 4, 6, 8, 10]
>>> dict_2["CART"][1]

>>> (a > 3) | (b > 5)


30
>>> set_1.union(set_2) Conditions # reduce
{1, 2, 3, 4, 5, 6} >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
True
>>> reduce(lambda a, b: a + b, numbers)
Dictionary Methods >>> set_1.isdisjoint(set_2) 55
Dictionaries

>>> a is b False >>> number = 3.14


>>> dict_1 = {"REG": "Regression",
False >>> if number > 0:

C O L L E C T I O N S
"LOG": "Logistic Regression", # zip
>>> set_1.issubset(set_2) ... print(f"{number} is positive.")
Boolean

"CART": "Classification and Reg"} False ... elif number < 0: >>> students = ["John", "Mark", "Venessa"]
>>> a is not b ... print(f"{number} is negative.") >>> departments = ["mathematics", "statistics", "physics"]
True >>> dict_2 = {"REG": ["RMSE", 10] >>> set_1.issuperset(set_2) ... else: >>> list(zip(students, departments))
Set

"LOG": ["MSE", 20] ... print(f"{number} is zero!") [('John', 'mathematics'), ('Mark', 'statistics'), ('Venessa', 'physics')]
False 3.14 is positive.
"CART":["SSE", 30]}

You might also like