More Python notes that need to be organized by me


other things you can do with listprint (list(range(100)))gives you a range to the number in a listyou can start where you want, like –
print (list(range(5,100)))
would start at 5

sentence =’  ‘sentence.join([‘hi’, ‘my’, ‘name’, ‘is’, ‘jojo’])
or even easier
new_Sentence = ‘  ‘.join9[‘list’, ‘of’, ‘things’]print(new_sentence)0

basket = [1,2,3]a,b,c = [1,2,3]the variables will be assigned in the order they were declaredso a = 1 b = 2  c =3list unpacking
a,b,c, *other = [1,2,3,4,5,6,7,8,9]
the asterisk will take everything not explicitly declared

None is a special data type that exist in python, the absence of value, like null.a = none or weapons = none if they are in a video game and i wanted to show they had no weapons
Dictionariesmaybe also called hashtable or map in other languages.  A data structure like listlist are easily order, a dictionary will look like –
dictionary =  {‘a’ : 1,’b’ : 2}key value pairs, a string for us to grab the value.  print(dictionary[‘b’])

List are ordered, dictionary are unordered, they can not be accessed via indexing because they are not indexed.
They are containers around data, you can have a dictionary with a key pair and the pair is a list, that is ordered, same with list.
when do you use a  list or a dictionary.  maybe if you want a line of people in a shop, it needs to be ordered so list. 
dictionary hold more information as well, list hold the index and that value, the dictionary holds more information a key, and then of course the key pair.Dictionary keys need to be immutable, they can not change.a string can not change, a list can be changed so the keypair can not be a keyso for example
[100]:True
will not work
what if we had another string
‘123’: ‘hello’123’: [1,2,3],
if you do the same key, it will override the other one, so the value is the 1,2,3not the hello since it was overwritten.
Now an example of a program error
user = { ‘basket’ : [1,2,3], ‘greet’: ‘hello’print(user[‘age’])
that will generate an error so you can use .get method on the object to check, and if it does not exist it will return none
user = { ‘basket’ : [1,2,3], ‘greet’: ‘hello’print(user.get(‘age’))
you can add a comma to the get command to give a default value instead of none
print(user.get(‘age’, 55))
less common way to create dictionary
user2= dict( name= ‘ johnson’)
another way to find something in a dictionary
‘basket’ in user and you will get bool of if it exist or not
‘age’ in (user.keys())’hello’ in (user.values())print(user.items())
easy way to grab items from dictionary
print(user.clear())clears the dictionary
What are tuplesthey are like list but immutable
they look like this
my_tuple = (1,2,3,4,5)print(my_tuple[1]) = ‘z’print(5 in my_tuple)  
returns true
if you do not need to change the list, it makes things easier and more efficient, it also makes it more predictable, you can not sort or run reverse, they are slightly more performant
This section finished up by showing some methods that can be used on setssuch as is subset or is supersetsubset means is this in this larger set, and returns a boolthe superset is the opposite, does this large set contain this smaller set for example.


Conditional statements next.  
if condition:  print(‘this will print if condition is true’)also I am using a text note editor that is not a code editor, but inside the condition statement, it should indent because it is part of that code block.
if there is no indent, then it will run the code because it is under the if statement but it is outside of the code block due to the indentation
there is also the keyword else
if condition:    do this
else:    do this, only runs if the condition evals to flase

if condition    code to run
elif alternative condition    code to runelse    catch all that for if the if and the else if (elif) false as well

Now to control the flow even more, we can add operatives to the condtion expression
if condition and other_condition        code to run if both conditions are met

if condition or other_condition        code will run if one of these conditions are met

other languages usually do && for and and || for or, but this is Python.
and now it is important to note that since there is no brackets to end code, and no brackets or organize code blocks, you have to worry about white space.  Some people prefer tabs, some prefer spaces (usually 4).  It does not matter, it just needs to have a distinction between the hierarchies of code (the if statement has children)
Truthy Vs Falsy
python will convert strings and ints for you if you are using them in a conditional statement.   A string with something in it, will convert to a true value and an int that is positive 1 or more will also be true.  
All values are considered “truthy” except for the following, which are “falsy”:

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] – an empty list
  • {} – an empty dict
  • () – an empty tuple
  • ” – an empty str
  • b” – an empty bytes
  • set() – an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

A “truthy” value will satisfy the check performed by if or while statements. We use “truthy” and “falsy” to differentiate from the bool values True and False.Ternary Operator or a conditional expression, evaluates to something depends if the condition is true or not
condition_if_true if condition else condition_if_else

is_friend = Truean examplecan_message = “message allowed’ if is_friend else “not allowed to message”notice how it is now a one liner
Short Circuitingis_Friend = Trueis_User = True
print(is_Friend and is_User)//returns true because both are trueif is_Friend or is_User:    print(‘best friends forever’)

the or is more efficient, since it only cares that one is true, it will not continue evaluating, it never checks the other condition if the first condition has already met needed condition
Same works with and but backwards, because if one thing is false it does not need to check the other condition to see if it is also false. 

Logical Operators>  greater than
<  less than
==  equal already taken for assignment so double == instead, javascript uses === to also compare typing
and
or
>= greater or equal
<= Less than or equal to
!= does not equal to
not is the opposite, if condition was true it is now false
print(not(True)) will give you False 

instead of == for comparison there is another word.  Equal checks for equalityis checks to see if the value of memory where the data is store is the same.’1′ is ‘1’ that is true[]is []is not because it creates a different memory location for each of the empty data structures.

LoopsAllows us to run lines of codes over and over.  
Keyword is For
for item in ‘Zero To Mastery’:    do something

the item is a variable, a variable is created for each item that is in the in part    so in this example since it is a string, it will print each item seperately, or character separately.
For loops allows us to loop through anything with a collection of objects.  
Nested loops, loops inside of loops so your loop loops through a loop.  
Iterable means it’s an object or a collection that you can go throughAn iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. Familiar examples of iterables include lists, tuples, and strings – any such sequence can be iterated over in a for-loop.
The Jurassic Park book had chapters that were the Dragon Curve through out different iterations. 

Dictionaries have three ways to go through them easily
For item in user.items():    print(item)

for item in user.values():    print(item)

For item in user.keys():    print(item)

Those three items are very common, items values and keys.
If you wanted to print seperately the items.
for item in user.items():    key, value = item;
print(key,value)
for key, value in user.items():print (key,value)
for item in 50:    print(item)
will give an error because it is not iterable, it is not a collection of items it is an int. 


Leave a Reply

Test Your email address will not be published. Required fields are marked *