Data Science - Python

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What command is used to output text from both the Python shell and within a Python module?

print()

difference of sets

produces a new set consisting of elements that are present only in one of those sets use '-' symbol use difference() a={1, 2, 4.6, 'f', 's'} b={3, 'a', 3.3} print(a-b) print("set a - b = ", a.difference(b)) *all elements present in a, but not common elements of a and b

collection and mapping types

range type and function set type dict type

All of these range types are correct except ______.

range(20,40,'-2') ??

All of these range types are correct except ___.

range(20,40,-1.2)

REPL

read, evaluate, print, loop through it again

float

numbers that have decimal points. It's a fraction/binary fraction. not as accurate as real floating-point numbers ex: 4.024, 5.0, -3.45

list

nums = [25,12,36,95,14] names = ['navin','kiran','john'] values = [9.5, 'navin', 23] mil = [nums, names] *mutable values*

inserting at index in list

nums = [25,12,36,95,14] nums.insert(2,77) *insert 77 at index 2

removing items in list

nums = [25,12,36,95,14] nums.remove(14) output: [25,12,36,95]

append list

nums = [25,12,36,95,14] nums.append(5) adds element to end of list

extend list

nums.extend([29,12,14,45]) *adds multiple values to list

What is the output of the following code? a = 0 if a: print(""""a's value"""") else: print(""""Sorry nothing will get printed"""")

""""Sorry nothing will get printed""""

Values in bytearray should be integers between _________.

0-255

bool addition

5 + True = 6 29 + False = 29

print to terminal

>> print('hello world')

check python version in terminal

>> python

run files from command line

>> python file_name.py prints contents to cmd

If b is a frozen set, what happens to b.add(3)?

Error as frozen sets cannot be modified

The two main versions of Python include ___________.

Python 2.x and 3.x

Which of the following attributes shows the characteristics of Python?

Ubiquity

Which of the following attributes exhibits Python's characteristics?

Ubiquity (the fact of appearing everywhere or of being very common)

Code written in Python 3 is backward compatible with Python 2.

false

What is the output of bool(0)?

false

The bool class is a subset of ______.

int

Is x, y = 5, 6 a valid statement?

true

UTF-8

'Unicode Transformation Format' the rule thing that states : if it's ascii, the char gets 1 byte, if it's arabic (ex) it often takes up 2 bytes, chinese could take up 3 bytes, and emojis now are utf characters that take up bytes

exponent

** 2 ** 5 '2 to the power of 5'

Python v2 vs. Python v3

- major difference was in the way that strings worked

flow division

// 50 // 3 returns the dividend as a whole number rather than a float

What is the output of the following code? count = 0 while count < 2: print (count, " is less than 2") count = count + 2 else: print (count, " is not less than 2")

0 is less than 2; 2 is not less than 2

booleans

True and False in python cmd, they must be capitalized

a.difference(b) highlights the ________.

a.intersection(b) - a.union(b) ?

create sets

a={1, 's', 7.8} *curly braces or b=set([1, 'b', 3.9]} *create empty set c=set() dir(a) *returns bunch of methods

Which statements will result in slice of tuple?

a_tuple[::2] a_tuple[:]

add elements to set

add() or update() add(): allows you to add a single element to set myset.add(4) update(): adding more than one element to set myset.update([2, 'abc', 4])

When using the Python shell and code block, what triggers the interpreter to begin evaluating a block of code?

blank line

Which statement creates the bytes literal when run?

bytes_literal = b'Copyright \xc2\xa9'

delete data from dictionary

del mydic{'mac'}

delete multipl values in list

del nums[2:] *deletes all elements starting at the second index

add element to dictionary

dic['rameath']=234000

Dictionary could be copied to another dictionary using which of following syntax?

dict_a = dict_b

fetch dict data

dic{'john'} output: 15000

whitespace

everything has to be aligned in python or else it will throw an error

.py

extension for python files

data types

int float basic math functions bool

What characteristics describe the python programming language ?

interpreted and open source

length of string

len() s = 'abcd' len(s) output: 4

find length of set

len() number of elements in set mySet={1, 's', 3.5} len(mySet) output: 3

clear list

listName.clear()

Which datatype is represented by int in Python 3?

long

access elements of set

loop through since not indexed a={1, 's', 7.8} for x in a: print(x) output: 1 s 7.8

sequence types

str bytes bytearray list tuple slicing

In what format does the input function read the user input?

string

str class

string is an immutable instance of str class so we could say string is an immutable object of str class. once created the immutable string object, it cannot be changed

sum of items in list

sum(nums)

while loop

sum=0 i=0 while i<10: sum += i print sum i++ *this loop calculates the sum of 0 through 9 (including 9) and places it in variable sum

union of sets

the concatenation of two or more sets into a single set. two ways to do so: pipeline concatenation() pipeline: a={1, 2, 4.6, 'f', 's'} b={3, 'a', 3.3} print(a | b) concatenation() with union(): a={1, 2, 4.6, 'f', 's'} b={3, 'a', 3.3} print("Set a U b = ", a.union(b))

my python version

Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32

read file as bytes

filename = '/users/etc/file/path.png' f = open(filename, 'rb') f.read() **rb stands for read as bytes

find max element in list

max(nums) *retrieves largest element in list

tuples

a collection of objects separated by commas. immutable , can store any type of data ex: b = (123, 12.23, "demo") access elements like a list with index: b[1] b[1]=83 *does not work bc it can't be changed slicing and other functions works like lists: b[:1] *slicing

sets

a data structure consisting of unordered unique elements of any datatype. they are not indexed. can be used when order doesn't matter

find minimum element in list

min(nums) *retrieves smallest value in list

slicing

extracting certain elements from lists, strings, tuples. list[start:end:step] ex: mylist = [0,1,2,3,4,5,6,7,8,9] mylist[1:5] *gets index 1-4 mylist[:5] *gets index 0-4 mylist[3:] *gets index 3-end mylist[-7:-2] *gets index 3-7 mylist[1:-2] *gets index 1-7 url = "https://heythere.com" url[8:15] or url[8:-4] output: "heythere" *step is optional and skips values (1 is default) mylist[2:-1:2] *starts index 2, ends index 8, gets every other element output: [2,4,6,8] negative step runs reverse mylist[-1:2:-1] output: [9,8,7,6,5,4,3] url[::-1] output: "moc.erehtyeh//:sptth" mylist[::-1] output: [9,8,7,6,5,4,3,2,1,0] *start is inclusive *end is exclusive

module

file containing python definitions and statements. Can define functions, classes, and variables. must be imported: import math #math module

fetch all keys from dictionary

mydic.keys()

What is the output of the following code? for x in range(1,100, 10): print(x)

1 11 21 31 41 51 61 71 81 91

byte

1 byte is the size of ascii letters for english/european languages (other languages take up 2 bytes like arabic)

challenge: 1. Namespaces 1 PYTHON-NAMESPACES write the function definition for the function 'Assign' to assign the different types of variables in its parameters to new variables. PARAMETERS: 1. an INT in the variable 'i' 2. a FLOAT in the variable 'f' 3. a STRING in the variable 's' 4. a BOOLEAN in the variable 'b' New variables to be assigned with: 1. an INT in the variable 'w' 2. a FLOAT in the variable 'x' 3. a STRING in the variable 'y' 4. a BOOLEAN in the variable 'z' assign the parameter variables RESPECTIVELY and print these in the following order: 1. w 2. x 3. y 4. z 5. Display all the objects defined in the current namespace by using the 'dir' function INPUT FORMAT FOR CUSTOM TESTING: # in the first line, value for 'i' #in the second line, value for 'f' #in the third line, value for 's' #in the fourth line, value for 'b' SAMPLE TEST CASE 1: SAMPLE INPUT: stdin parameter function _________________________________________________________ 10 i 3.14 f One s true b SAMPLE OUTPUT 10 3.14 One True ['b', 'f', 'i', 's', 'w', 'x', 'y', 'z']

code: def Assign(i, f, s, b); w=i x=f y=s z=b print(w) print(x) print(y) print(z) print(dir()) if _ _name_ _ == '_ _main_ _': i int(input().strip()) f = float(input().strip()) s = input() b = input().strip() Assign(i, f, s, b)

Challenge: 1. Print GREETING QUOTE Mr. Greet is the name of the digital notice board placed at the entrance of the seminar hall. Its purpose is to welcome each and every participants of the seminar by showing a welcoming quote with their name on it. It is based on teh function 'Greet' which takes a single parameter 'Name' as a string that are teh names of the participants as Input one by one. Write the function definition for 'Greet' which will generate the welcoming quote as below: For example, the 'Name' is "Harry" then the welcoming quote will be: OUTPUT: "Welcome Harry. It is our pleasure inviting you. Have a wonderful day." NOTE: 'Name' must be of String data type INPUT FORMAT FOR CUSTOM TESTING: it's a single line that contains a name. SAMPLE TEST CASE 1: SAMPLE INPUT: stdin function ____________________________________ Karthik -> name SAMPLE OUTPUT: Welcome Karthik. It is our pleasure inviting you. Have a wonderful day.

code: def Greet(Name): print('Welcome ' + Name + '.\nIt is our pleasure inviting you.\nHave a wonderful day.') if _ _name_ _ == '_ _main_ _': #no spaces between _ Name = input() Greet(Name)

range type

for lists or tuples a = list(range(6)) *we want the range from 6 output: 0,1,2,3,4,5 >>> b=tuple(range(6)) >>> b (0, 1, 2, 3, 4, 5) *useful with loops/conditionals, or a set of numbers d=list(range(1, 10)) *range starting from 1, ending at 10. Prints 1-9 f=list(range(0,11,2) *prints 0-10 but every other number (evens) *works very similarly to searching by index like above just dif syntax

converting to booleans

if converting numbers to bools, 0 replies back False while all other numbers return True bool(-324.32) -> True bool(456) -> True bool(0) -> False trivial values -> false non-trivial values -> true int(True) -> 1 int(False) -> 0

converting types

int('3') -> returns 3 int(5.4) -> 5 *can't convert complex numbers (like 3a)

removing elements from set

remove(): removes an element from the set specified as the parameter. throws error if element not present. myset.remove('aaa') myset.remove(2.4) discard(): used when you want to remove an element when you are not sure if it's actually present or not. myset.discard('b') myset.discard(4) pop() : remove random element from set myset.pop()

pop

removes the last element that was added to list num = [25,12,36,95,14] num.pop(1) *removes 14

negative index

retrieves elements from lists, strings, tuples starting at the end of them. mylist = [0,1,2,3,4,5,6,7,8,9] mylist[-7:-2] *gets index 3-7 mylist[1:-2] *gets index 1-7 mylist[:-2] *index 0-7

rounding numbers

round(3.5 + 4.2) = 8 round(7.6 + 8.7, 1) = 16.3

converting into bytes

s = 'こんにちは' bytes(s, encoding='utf-8') output: b'\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\ *the bytes that make up the japanese*

frozen set

set where values cannot be modified (immutable). cannot add or remove values frozenset() a={1, 2, 4.6, 'f', 's'} b=frozenset(a)

nums.sort()

sorts items in a list, smallest to largest for numeric values

bytearray provides an mutable sequence, making it modifiable.

true

dict

unordered collection of objects by key and value. mutable dic = {'john':15000,'mac':20000}

Which action must be avoided to prevent the previously-defined names from getting overwritten?

using the wildcard import

The default decode option available in the byte data type is ________

utf-8

integer

whole number that doesn't contain a decimal ex: 4, 5, 3, 19, 4958, -3, -234

Which describes bytearrays?

without an argument, an array of size 0 is created; contains a sequence of integers 0-255

Equivalent operation for function pow(x, y) is __________.

x**y

Which of the following will not yield in declaring x as the datatype of float?

x=int(y) ? i think this one is wrong

What is the output of max('Infinity')?

y

mutable data

you can change it

immutable data

you can't change it ex: strings, byte strings (location of a char on utf/ascii list?)

convert encoding to string

you can't. but need to specify first? s = 'こんにちは' b = bytes(s, encoding='utf-8') str(b, encoding='utf-8') output: 'こんにちは'

Empty dictionary is represented as ________.

{ }


Set pelajaran terkait

HAZMAT Familiarization and Safety in Transportation

View Set

5 Questions & Answers for Disease Test

View Set

Quick Quiz 1-6, lecture 1-10, DSM 1-6, lab midterm review, chapters 11-15, lab, 16-21

View Set