Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Codefinity Notebook - cPython

Personal Notes - on Codefinity Python course - Notebook own notes

Uploaded by

Elias
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Codefinity Notebook - cPython

Personal Notes - on Codefinity Python course - Notebook own notes

Uploaded by

Elias
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

What I’ve learned:

Python IS case senstive

Math operations: + , / , - , *, Power print(10**3)


print(‘string’) print(10//3) = 3 [integer division, “just gv me as”] print(10%3) = 1 [modular]
variable1 += variable2 [this will add/set var2 into var1]

Variables can’t start with a number (Variables are the things you name strings/integers)
Variables are case sensitive

if : else:
[Indentation marks end of if/else] [only in VBA do you need endif endelse nextfor]
((str;; int, float, complex; list, tuple, range;; set;; bool;; dictionary;; bytes, binary))

FLOATS are decimal numbers


int_num = 11 real_num = 16.83
print(int_num, float(int_num)) >>>> 11 11.0
print(real_num, int(real_num)) >>>> 16.83 16

list( ) <<< makes a set into a list, it list-ifies a group of strings


or you can just define one by starting with [ ]

‘for’-loops can work on strings, in which case it goes through each character
‘for’-loops in lists, obviously goes through each element

for i in range(10, 20):


print (i**2)

string[ ] index negative-index


string.split()[ ] phrase[23:37:-1] [start:stop:step] every 3rd letter, or reverse
“string.index(5)” <<<???
len(string)
count( )
.join
list.apend( ) << adds item to list
.extend( ) << adds a list to another list
.sort( ) << alphabetizes the items inside a list
list.pop(2) << removes item 2 from list
Intermediate Course – Python Data Structures
1) LISTS – (Nested, Indexing, Append(), Insert(), Remove())
2) DICTIONARY – (Del keyword, Pop(), PopItem(), Clear(), comprehensions)
3) TUPLES – (Concatenation, updating, challenges)
4) SETS – (Add(), update(), remove(), discard(), clear(), challenges)

List.append(‘str’)
List.insert(0, ‘str’)
del List[0]
List.remove('call Max') <<< finds the string matching what you want to delete

NOTE: you can only append one item at a time, to a list.

fruits = ['Raspberry', 'Pomegranate', 'Peach', 'Pear']


fruits.append('Mango')
fruits.append('Banana')
print(fruits)
string = "I can manage everything"

manage = string.index('manage')
everything = string.index('everything')

print("The index of the word manage is", manage)


print("The index of the word everything is", everything)

string = "It is cool to have a burning desire for studying"

burning = string.index('burning')
desire = string.index('desire')
studying = string.index('studying')

print("The index of the word burning is", burning)


print("The index of the word desire is", desire)
print("The index of the word studying is", studying)

string1 = "Rome is the capital of France"


string2 = "Brasilia is located in Europe"
string3 = "Monkeys eat earphones"

# Make required replacements


new_string1 = ___.replace(___, '___')
new_string2 = string2.___(___)
new_string3 = ___

# Print the first corrected string


print(___)
+= called unary operators
https://careerkarma.com/blog/python-operator/

Tuples are basically Lists, but you can’t modify/edit them (they’re super efficient for memory/storage)

Tuples are created with Parentheses


You can change a List into a Tuple tuple(list_name)
print(type(tuple_name)) >>>> <class, ‘tuple’>

CONFUSING!!!:
dictionary = {“sf to la”: 500, “la to lv”: 400, “lv to nyc”: 3500}
for citypair, distancekm in dictionary.items():
distancekm[citypair] = dictionary / 0.621
total = sum(dictionary.values())
average = total / 3

sentence = “learning python is fun and engaging. mastering it opens opportunities.”


variable = sentence.split()[ ] <<< this splits by spaces, and indexes the words, from 0.
second_word = sentence.split()[1] >>> python
third_word = sentence.split()[2] >>> is
fourth_word = sentence.split()[3] >>> fun

as you can see, [ ] opens the characters/letters (as in start:stop)


as you can see, within the [ ] , up to data_str.index( ) <<< searches for ‘string’, and outputs Index #!!!

True understanding will come from rewriting comments of line-code into plain-english
.count(‘string’)
.count(‘t’) <<<< counts occurences of “t” in total

.join
len( )

THEORETICAL ASSIGNMENT:
SPLIT AND INDEX AND REVERSE in multiple combinations
Step 3
for example: take a string
first half of sentence, reverse it, second half of sentence skip every 3 letters
take result of that, then skip every two words (not letters)
take result of that, and reverse word order
take result of that, remove last word
take result of that, reverse letter order (not words) ……

lazy_index = sentence.split('lazy') <<<< outputs the whole sentence with “lazy” blotted out

lazy_index = (sentence.split()).index('lazy')
lazy_index = sentence.split().index('lazy') both seem to work

HOW TO MAKE A LIST( )


how to define a new variable inside the list, and reference the items, manipulate the items
even_numbers is a LIST
odd_numbers is a LIST, but they’re empty

go through each item inside the “numbers” LIST


if even, grab the “even_numbers” LIST and append(item that we’re on).
if odd, grab the “odd_numbers_transformed” and append (item * 3 + 1)
print

By default, the print() function outputs each result on a new line. By employing the end=' ' argument, we ensure that
multiple print() outputs are separated by a space. We'll be using this technique throughout this section.
i=1
while i < 10: # Condition
print(i, end = ' ')
i=i+1
Lists work just like Slicing and Indexing
starts at 0, and the outer boundary is exclusive (not included)

Consider a two-dimensional list named countries_2d that contains 3 main elements (which are lists). Each of these lists
has 2 items. So, countries_2d[1] fetches the second list in the main list (keep in mind, Python indexing begins at 0).
Moreover, countries_2d[1][0] retrieves the first item within that second list.

# Two-dimensional list
countries_2d = [['USA', 9629091], ['Canada', 9984670], ['Germany', 357114]]
# Pull elements
print(countries_2d[1])
print(countries_2d[1][0])

>>
['Canada', 9984670]
Canada

Let's dive into the primary methods associated with tuples.

len(t) - gives the number of elements in the tuple t;


t * n - produces n repetitions of the tuple t;
t.count(x) - counts how often x appears in the tuple t;

you've probably noticed

As you've probably noticed, dictionaries have unique characteristics that set them apart from lists and tuples. They also
come with their own set of methods. Let's dive in.

len(d) - returns the number of key:value pairs in the dictionary d.


d.copy() - creates a copy of the dictionary d.
d.items() - provides all the key, value pairs from the dictionary d.
d.keys() - lists all the keys in the dictionary d.
d.values() - provides all the values from the dictionary d.
Wondering how to add new entries to a dictionary? Dictionaries don't utilize list methods like .append() or .extend(), and
they don't support concatenation like strings. Instead, since dictionaries organize data in key-value pairs, you simply
assign values using keys:

d[k] = e - assigns the value e to the key k. If the key k already exists in the dictionary, its associated value will be updated.
!!!!!!!!!!

What the fffffqqqqq???


You don’t need a variable to start a for loop?
# List of dictionaries representing books
books = [
{"title": "Book A", "author": "Author A", "pages": 250},
{"title": "Book B", "author": "Author B", "pages": 350},
{"title": "Book C", "author": "Author C", "pages": 150},
{"title": "Book D", "author": "Author D", "pages": 450}
]
# Use for loop to iterate over list and print title and author if pages > 300
for i in books:
if i["pages"] > 300:
print("Title: ", i["title"] , ", Author: ", i["author"])
DEFINING FUNCTIONS

IF/ELSE WITHIN AND INSIDE FUNCTIONS


FUNTIONS WITHOUT RETURNS (just doing tasks in the background).
IMPORTANT!!!!
IMPORTANT USE OF DICTIONARIES AND REFERENCING THEM INSIDE FUNCTIONS:

# Data
dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154),
'Germany': (357114, 83783942), 'Brazil': (8515767, 212559417),
'India': (3166391, 1380004385)}

# Defining a function
def function_giveinfo(x, n):
print('Country:', n)
print('Area:', x[n][0], 'sq km')
print('Population:', round(x[n][1]/1000000, 2), 'MM')

# Testing the function


function_giveinfo(dict, 'USA')
function_giveinfo(dict, 'Brazil')
string = "My goal is to achieve way beyond what I expected"
# Extract the very last symbol using negative indexation
symbol1 = string[-1]
# Extract the very last symbol using len() function
symbol2 = string[len(string)-1] <<<<<<<<<<<<<< notice -1 is necessary

# Print symbols
print("This symbol was retrieved using negative indexation:", symbol1)
print("This symbol was retrieved using len() function:", symbol2)

You might also like