You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This document will jumpstart your understanding of Python. We will give a broad overview to all the foundational aspects of the programming language. Feel free to come back to this section - after all, even the most experienced programmers have to review the basics sometimes!
6
6
7
+
1.[Data Types](#data-types)
8
+
2.[Variables](#variables)
9
+
3.[Control Flow](#control-flow)
10
+
4.[Container Types](#container-types)
11
+
5.[Functions](#functions)
12
+
6.[Credits](#credits)
13
+
7
14
## Data Types
8
15
Programming languages give us an easy way to manipulate data in the computer - but first, the computer has to understand what kind of data we're dealing with!
9
16
@@ -345,15 +352,15 @@ Lists (represented by the `list` type) simply represent an *ordered sequence of
345
352
346
353
Just as strings are a sequence of textual characters, the `list`in Python allows us to collect lots of different values altogether sequentially, enclosed in a pair of square brackets (`[]`).
347
354
348
-
### Getting Individual Values in a List with Indexes
355
+
#### Getting Individual Values in a List with Indexes
349
356
Because the data in a Python `list`isin a sequence, we can retrieve individual values in that `list` (aka an *element of the list*) if we know where it is positioned in that list.
350
357
351
358
The position of an element in a `list`is the *index* of that element. The index position of the first element is`0`, and the indices of the following elements incrementally increases by 1.
352
359
353
-
### Negative Indexes
360
+
#### Negative Indexes
354
361
Python will also let us access elements from the back of the list, using negative index values. These begin with the value of `-1`for the very last element, and decrease by one as we move further to the left.
355
362
356
-
### Getting Sublists with Slices
363
+
#### Getting Sublists with Slices
357
364
We can retrieve several items out of a `list` at once and put them in a new `list` by using a *slice*with the `:` operator.
358
365
359
366
Slices have a similar syntax to the `range()` function - you can optionally passin`start:stop:step` values when you use it, or use the default values.
One common way to do this iswith the `del` keyword. Once an element from`list`is gone, all the elements that came after it will move over an index postion to the left.
380
387
381
388
```python
@@ -384,7 +391,7 @@ del spam[2]
384
391
spam # result: ['cat', 'bat', 'elephant']
385
392
```
386
393
387
-
### Loops and Lists
394
+
#### Loops and Lists
388
395
Once we have a list, we can `for` loop if we want to do something on each of the elements. This is known as a *list traversal*.
389
396
390
397
When we use the syntax `for iterator in my_list`, our `iterator` variable will be set equal to the value of each element in `my_list`, starting from the leftmost index. In the body of the for loop, we can then do what we like with that value:
@@ -396,22 +403,22 @@ for i, supply in enumerate(supplies):
396
403
print('Index {} in supplies is: {}'.format(str(i), supply))
397
404
```
398
405
399
-
### The in and not in Operators
406
+
#### The in and not in Operators
400
407
Python strives to be as close to readable English as possible. The `in` keyword was added to the language in order to help us deterimine if a given value is present in a container data typein Python. In the context of lists, it will return `True` or `False` depending on if the given value is equal to one of the elements in the given list:
401
408
```python
402
409
'howdy'in ['hello', 'hi', 'howdy', 'heyas']
403
410
```
404
411
This is also known as checking for*membership* of the data in the list. If we want to, we can also place `not` before the `in` operator, to check if the given value "is not" a member of that list.
405
412
406
-
### Finding a Value in a List with the index Method
413
+
#### Finding a Value in a List with the index Method
407
414
Once we know a value exists in a list, wouldn't it be great to know what it's index position was?
408
415
409
416
```python
410
417
spam= ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
411
418
spam.index('Pooka')
412
419
```
413
420
414
-
### Adding Values to Lists with append and insert
421
+
#### Adding Values to Lists with append and insert
415
422
Values can be added to the end of a listwith the `append()` method:
416
423
417
424
**append()**:
@@ -431,7 +438,7 @@ spam.insert(1, 'chicken')
431
438
spam
432
439
```
433
440
434
-
### Removing Values from Lists with remove
441
+
#### Removing Values from Lists with remove
435
442
The `remove()` helps us delete a particular element from a list. It is different from using the `del` keyword, since we do not need to know the index of the element we want to delete:
436
443
437
444
```python
@@ -442,7 +449,7 @@ spam
442
449
443
450
If the value appears multiple times in the list, only the first instance of the value will be removed.
444
451
445
-
### Sorting the Values in a List with sort
452
+
#### Sorting the Values in a List with sort
446
453
The `sort()` functions are provided so we can easily order the elements of a listfrom least to greatest (if they are numerical values) orin lexicographical order (if they are strings).
447
454
448
455
Invoking the `.sort()` method on an already existing `list`object will modify the elements of that list itself.
The next kind of container data typeis the *dictionary* (represented as`dict`in Python). A dictionary is used to store an unordered collection of key-value pairs.
476
+
477
+
The fact it is*unordered* means we cannot obtain values from a `dict`. However, all the keys in a `dict` are unique - so we can get a specific value from a `dict`, if we know the corresponding key.
This function returns only the values in a dictionary:
489
+
```python
490
+
spam= {'color': 'red', 'age': 42}
491
+
492
+
for v in spam.values():
493
+
print(v)
494
+
```
495
+
496
+
keys():
497
+
This returns just the keys:
498
+
```python
499
+
for k in spam.keys():
500
+
print(k)
501
+
```
502
+
503
+
items():
504
+
This will return both the keys, and their corresponding values:
505
+
```python
506
+
spam= {'color': 'red', 'age': 42}
507
+
508
+
for k, v in spam.items():
509
+
print('Key: {} Value: {}'.format(k, str(v)))
510
+
```
511
+
512
+
#### Checking if a Key or Value Exists in a Dictionary
513
+
The `in` operator can still be used with dictionaries:
514
+
```python
515
+
spam= {'name': 'Zoey', 'age': 7}
516
+
'name'in spam.keys() # equal to 'name' in spam
517
+
```
518
+
You can omit the call to keys() when checking for a key:
519
+
```python
520
+
'color'in spam
521
+
```
522
+
But not when checking for values:
523
+
```python
524
+
'Zophie'in spam.values()
525
+
```
526
+
527
+
#### The get Method
528
+
If you try to access a value in a `dict`with a key that isn't actually in that dictionary, the Python interpreter will throw a `KeyError` exception. To avoid this, we can use the `get()` method.
529
+
530
+
With this method, we can specify both the key for the value we want from the `dict`, AND also a default value as a second parameter. Therefore, if the key isn't actually in the `dict`, the method will instead return whatever default argument we passed in:
531
+
532
+
```python
533
+
picnic_items= {'apples': 5, 'cups': 2}
534
+
'I am bringing {} cups.'.format(str(picnic_items.get('cups', 0)))
535
+
```
536
+
537
+
#### The setdefault Method
538
+
The `setdefault()` method will add a key-value pair to our dictionary, if it doesn't already already exist.
539
+
540
+
Let's consider this code. It is possible to add/update key-value pairs in a `dict` using square brackets (`[]`):
541
+
542
+
```python
543
+
spam= {'name': 'Pooka', 'age': 5}
544
+
if'color'notin spam:
545
+
spam['color'] ='black'
546
+
```
547
+
548
+
Using `setdefault` we could make the same code more succinctly:
549
+
550
+
```python
551
+
spam= {'name': 'Pooka', 'age': 5}
552
+
spam.setdefault('color', 'black')
553
+
```
554
+
555
+
Finallly, the last container data type we will discuss are sets!
556
+
### Sets
557
+
558
+
Sets are an unordered collection of elements. You can think of sets as1-sided dictionaries - specifically, if dictionaries are collections of key-value pairs, then sets are what you would have if you only had the keys!
559
+
560
+
Sets are mostly often used for membership testing, and eliminating duplicate entries. Set objects also support mathematical operations like *union*, *intersection*, *difference*, and*symmetric difference*.
561
+
562
+
#### Initializing a set
563
+
564
+
There are two ways to create sets: using curly braces `{}`and the bult-in function `set()` around a list:
565
+
566
+
```python
567
+
s= {1, 2, 3}
568
+
s=set([1, 2, 3])
569
+
```
570
+
571
+
When creating an empty set, be sure to not use the `set()` function (you will get an empty dictionary if you use `{}` instead).
572
+
573
+
```python
574
+
s= {}
575
+
type(s)
576
+
```
577
+
578
+
#### sets: unordered collections of unique elements
579
+
580
+
A set automatically remove all the duplicate values.
581
+
582
+
```python
583
+
s= {1, 2, 3, 2, 3, 4}
584
+
s
585
+
```
586
+
#### Adding Elements to a Set
587
+
588
+
Using the `add()` method we can add a single element to the set.
589
+
590
+
```python
591
+
s= {1, 2, 3}
592
+
s.add(4)
593
+
s
594
+
```
595
+
596
+
And with`update()`, multiple ones .
597
+
598
+
```python
599
+
s= {1, 2, 3}
600
+
s.update([2, 3, 4, 5, 6])
601
+
s # remember, sets automatically remove duplicates
602
+
```
603
+
604
+
#### Removing Elements From a Set
605
+
606
+
Like lists, set provide a `remove()` to help us delete elements from it.
607
+
608
+
Alternatively, you can also use the `discard()` method, which won't raise any errors if the argument passed is not actually in the `set`.
609
+
610
+
```python
611
+
s= {1, 2, 3}
612
+
s.discard(3)
613
+
s
614
+
```
615
+
616
+
```python
617
+
s.discard(3)
618
+
```
619
+
620
+
#### Set Operations:
621
+
622
+
1. `union()`or`|` will create a new set that contains all the elements from the sets provided.
623
+
624
+
```python
625
+
s1= {1, 2, 3}
626
+
s2= {3, 4, 5}
627
+
s1.union(s2) # or 's1 | s2'
628
+
```
629
+
630
+
2. `intersection`or`&` will return a set containing only the elements that are common to all of them.
631
+
632
+
```python
633
+
s1= {1, 2, 3}
634
+
s2= {2, 3, 4}
635
+
s3= {3, 4, 5}
636
+
s1.intersection(s2, s3) # or 's1 & s2 & s3'
637
+
```
638
+
639
+
3. `difference`or`-` will return only the elements that are in one of the sets.
640
+
641
+
```python
642
+
s1= {1, 2, 3}
643
+
s2= {2, 3, 4}
644
+
s1.difference(s2) # or 's1 - s2'
645
+
```
646
+
647
+
4. `symetric_difference`or`^` will returnall the elements that are *not* common between them.
648
+
649
+
```python
650
+
s1= {1, 2, 3}
651
+
s2= {2, 3, 4}
652
+
s1.symmetric_difference(s2) # or 's1 ^ s2'
653
+
```
654
+
655
+
Now that you about the most common data types in Python, you can see how we can start to store sizeable portions of data together for our programs. The last skill you will need before you can actually begin solving data science problems with Python is knowing how to work with*functions*- let's discuss these next!
656
+
657
+
## Functions
658
+
*Functions* are blocks of code which we can use to perform a certain task over and over again.
659
+
660
+
The first line of a function is its *declaration*. It includes the `def` keyword (to tell Python we are "defining" a function), the name of the function (which follows the naming rules as [variables](#variables) do), and then whatever *parameters* the function has go inside a pair of parentheses.
661
+
662
+
Parameters are nothing to be afraid of - they are special variables that can be used once the function is actually called!
663
+
### Return Values and return Statements
664
+
665
+
When creating a function using the `def` keyword, you can specify what the return value should be with a `return` keyword. A return statement consists of the following:
666
+
667
+
- The `return` keyword.
668
+
669
+
- The value or expression that the function should return.
670
+
671
+
Once the flow of control hits a `return` statement, it will execute that line of code andexit the function.
672
+
673
+
```python
674
+
import random
675
+
def getAnswer(answerNumber):
676
+
if answerNumber ==1:
677
+
return'It is certain'
678
+
elif answerNumber ==2:
679
+
return'It is decidedly so'
680
+
elif answerNumber ==3:
681
+
return'Yes'
682
+
elif answerNumber ==4:
683
+
return'Reply hazy try again'
684
+
elif answerNumber ==5:
685
+
return'Ask again later'
686
+
elif answerNumber ==6:
687
+
return'Concentrate and ask again'
688
+
elif answerNumber ==7:
689
+
return'My reply is no'
690
+
elif answerNumber ==8:
691
+
return'Outlook not so good'
692
+
elif answerNumber ==9:
693
+
return'Very doubtful'
694
+
```
695
+
696
+
### The None Value
697
+
Some functions have no `return` statement - these functions have a return value of `None`, which is just Python's way of representing the *absence* of data.
698
+
699
+
For example, the `print()` function in Python has a return value of `None`:
700
+
701
+
```python
702
+
spam=print('Hello!')
703
+
spam isNone
704
+
```
705
+
706
+
*Note*: never compare to `None`with the `==` operator. Always use `is`.
707
+
708
+
### Local and Global Scope
709
+
All the variables in a Python program have a *scope*. *Scope*is how we describe the place in a program where we can actually access the value of a variable.
710
+
711
+
To start off with, let's discuss the **2 main scopes in Python:**
712
+
713
+
1. *Local*: we say all the variables *inside* of a function have a *local* scope - meaning, they can be only be accessed within the function body.
714
+
715
+
2. *Global*: these are all the variables outside of any function.
716
+
717
+
### Rules of Thumb For Scope:
718
+
Here are some basic rules to remember, so you never run into issues with scope:
719
+
720
+
1. The code in the global scope cannot use any local variables.
721
+
722
+
2. However, a variable in a local scope can access global variables.
723
+
724
+
3. The code in a function’s local scope cannot use variables inany other function.
725
+
726
+
4. You *can* use the same name for different variables if they are in different scopes. That is, there can be a local variable named `spam`and a global variable also named `spam`.
727
+
728
+
### What Scope Does This Variable Have?
729
+
730
+
There are four rules to tell whether a variable isin a local scope orglobal scope:
731
+
732
+
1. If the variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
733
+
734
+
2. If there is a global statement for that variable in a function, then it is a global variable.
735
+
736
+
3. Otherwise, if the variable is used in an assignment statement in the function, then it is a local variable.
737
+
738
+
4. However, if the variable isnot used in an assignment statement, then it is a global variable.
739
+
467
740
## Credits
468
741
469
-
This section would not be possible ifnotfor the following sources:
742
+
This section would not be possible ifnotforhelpfromthe following sources:
470
743
471
744
1. *[Automate the Boring Stuff with Python](https://automatetheboringstuff.com/)*, a book by Al Sweigart under the [Creative Commons license](https://creativecommons.org/licenses/by-nc-sa/3.0/).
472
745
2. The [Python Cheatsheet](https://www.pythoncheatsheet.org/) website and [GitHub repository](https://github.com/wilfredinni/python-cheatsheet) by wilfredinni.
0 commit comments