---
# System prepended metadata

title: "Python Workshop #1 - Basics \U0001F40D"

---

# Python Workshop #1 - Basics 🐍
### ECE Undergraduate Student Council

---

## Goals
1. Get general introduction to the Python programming language
2. Learn Python basic syntax
3. Write some code!

---

## smol WARNING
- This can be hard to understand at first, but it's okay to be confused!
- Don't be afraid to ask questions! I'm here to help :smile: 

---

## What is Python?
- “Python is an interpreted **high-level** programming language for general-purpose programming” ([Wikipedia](https://en.wikipedia.org/wiki/Python_(programming_language)))
- World's fastest growing and most popular programming language
- Used by software engineers, analysts, data scientists, and machine learning engineers alike
- Versatile, powerful, and has a large community of supporters
- Great as a first programming language

---

## The Zen of Python
    “Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts…”
[Source](https://www.python.org/dev/peps/pep-0020/)

---

## Python Syntax 💻

----

### "Hello World!"
By tradition, we will create our very first Python program:
`"Hello World"`
In Python, it will look like this:
``` javascript
print("Hello World!")
```
There's two ways you can do this:
1. Interactive Mode
2. Script Mode

**Glitch time!**

----

#### 1. Interative Mode

In your terminal, type *`python`* to enter interactive mode.

Enter the command:
``` python
print("Hello World!")
```
What do you think `print` do?

To exit interactive mode, type `exit()`

----

#### 2. Script Mode

Create a file using a text editor (atom, sublime, vim, ...)
``` bash
vim helloWorld.py
```
`.py` indicates that the file is a Python file.

Type the code to print `"Hello World"` in the file.

To execute the file, run:
``` bash
python helloWorld.py
```

----

### Indentation ![](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/WikiMooc_Key_TAB_grey.svg/2000px-WikiMooc_Key_TAB_grey.svg.png =50x30)

In other languages, indentation is for readability. In Python, indentation is **necessary**.
Python uses indentation to indicate a block of code.

![Indentation gif](https://i.imgur.com/7lg2zJ6.gif)

----

To save us the hassle of switching back and forth from Glitch, we'll use Trinket for the rest of our tutorial to run our code. You can edit live code, try it!

<iframe src="https://trinket.io/embed/python/f87edcda84?showInstructions=true" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Comments
`# This is a comment`
- Used to explain a part of your code
- The computer won’t run this code - only for humans to read

Take our `Hello World` program: notice how only `"Hello World!"` is printed, and none of the comments appeared.
<iframe src="https://trinket.io/embed/python3/c461344d44?toggleCode=true&runOption=run" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Your Turn:

Print out your name and a fun fact about yourself 😎
Include comments to explain your code.

<iframe src="https://trinket.io/embed/python/b0301e5c48?showInstructions=true" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

---

## Variables 📥

----

### What is a variable? 
Think of a variable as a container for storing a value.
![](https://i.imgur.com/t7Ykq7l.jpg =300x300)

----

Create a variable by assigning a value to it (no need to be declared or typed!)
 **variable = value**
Use a single `=` sign (not to be confused with the equality operator `==`)

Example:
``` python
parking_on_campus = 0
```
Here, I'm assigning the value 0 to the variable `parking_on_campus`.

----

### How do I name my variables?

Common: myVariable or my_variable
- Must start with a letter or underscore
- Only alpha-numberic characters
- Case-sensitive (`NAME` and `name` are different)
- Descriptive names are useful!

<iframe src="https://trinket.io/embed/python/857adcfdef?runOption=run" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### What can I store in a variable?
Variables can store:
- Numbers (integers, floats)
- Strings (“This is a string”)
- Characters (‘c’)
- Booleans (True, False)
- Data Structures (lists, tuples, dictionaries)

![](https://i.imgur.com/IRnrG2N.png =500x200)


----

### What if I want to change the value?

Easy. Just reassign it to another value!

``` javascript
my_var = 5
my_var = my_var + 3
print(my_variable)
```
What will this print?

----

### Challenge

Let's make a RPG game character! 
<iframe src="https://trinket.io/embed/python/ee6914d6d3?runOption=run&showInstructions=true" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

---

## Data Types :1234: :abc: 
There are various data types in python that variables can store. Unlike other languages (like C or Java) you don't have to declare the variable type. Just simplying assign a variable something (like we have shown before).

----

### Numbers

Numbers are self-explanatory. What isn't so obvious is that python distinguishes the different types of numbers (e.g. integer vs. decimal numbers). 

Integer numbers are called `int`

Decimal numbers are called `float`

----

Let's use ints and floats to make some game variables.

<iframe src="https://trinket.io/embed/python/4fb78388d7" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Strings
Strings are a series of characters surrounded by either single quotation marks or double quotation marks:

`'hello'` is the same as `"hello"`.

Strings can output to the screen using `print()`:

`print("hello world!")`

----

Strings also have some cool built-in features and functions. Let's take a look at some of them:

<iframe src="https://trinket.io/embed/python/77c2c8f817" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Lists
A list is a collection of elements which is ordered and changeable. It allows duplicate members.

Let's take a closer look at what lists are by using a list as our game inventory.

<iframe src="https://trinket.io/embed/python/e8e4e290d4" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Dictionaries ()

Dictionary is a collection of objects that store data in key, value pairs.

Let's explore this through our game's shop.

<iframe src="https://trinket.io/embed/python/a345724aba" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Boolean
Boolean values are the two constant objects `False` and `True`. They are used to represent truth values.

Example: 
``` python
is_learning_python = True
```

Boolean values are useful for conditional statements and loops (more on that later).

<iframe src="https://trinket.io/embed/python/6ea1df06b5" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

---

## Operators ➕➖➗✖

----

### Arithmetic Operators
You can do math in Python using arithmetic operators.
![](https://i.imgur.com/kjM83c0.png)

----

Here are some examples of operators, try to guess what the values are. Then uncomment the print statements to check your answers.

<iframe src="https://trinket.io/embed/python/5cd6f4f1ed?runOption=run" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Challenge

Try it yourself! Use variables and operators to update your `gold` count.

<iframe src="https://trinket.io/embed/python/82ae803f25?showInstructions=true" width="100%" height="450" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Comparison Operators

You can compare two things using comparison operators.

![](https://i.imgur.com/GtK8Wz0.png)

----

Comparison Operators will **return Booleans (True/False)**.
Try to guess what the values are. Then uncomment the print statements to check your answers.

<iframe src="https://trinket.io/embed/python/e4b3ec41ae?runOption=run" width="100%" height="320" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>


----

### Logical Operators

Logical Operators reads like English! 

![](https://i.imgur.com/a1GiwTs.png =600x)

`and`: **both** are True -> True. Otherwise False
`or`: **either** are True -> True. None is True -> False
`not`: opposite

----

Again, try to guess the values and uncomment the print statements to check.

<iframe src="https://trinket.io/embed/python/48ab970df1?runOption=run" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

---


## Conditionals :question: 

----

Scenario: 
Suppose I want to drink a health potion, but only if my health is low (<50). How do I do that? 💔

Decision making is required when we want to execute a code only if a certain condition is satisfied.

In Python, the **if statement** is used for decision making.

----

### 'if' Statements
The syntax for a Python if statement is:
``` javascript
if test condition:
    code
```
If `test condition` is True, `code` will execute.
Pay close attention to the `:` and indentation!

Take our scenario from earlier,

<iframe src="https://trinket.io/embed/python/1caadf5c16" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

Another scenario:
I have two potions, big and small. I will drink the big potion when my health is extrememly low (<10), and I will drink the small potion when my health is low (<50). If my health is not low, I will not drink any.

What happens if I use if statements?

<iframe src="https://trinket.io/embed/python/406d2bbe65" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

Oh no! I drank both potions 😱

----

### 'if', 'elif', and 'else' Statements

This is where *`elif`* and *`else`* comes in.
``` python
if test condition 1:
    code1
elif test condition 2:
    code2
else:
    code3
```
If the test condition 1 is not met, the program will skip code1 and check test condition 2.
If test condition 2 is not met, the program will skip code2 and execute code3 in *`else`*.

You can add as many elif as you need!

----

Going back to our example, this is what the code will look like:
<iframe src="https://trinket.io/embed/python/e06e5c55b0" width="100%" height="250" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

### Challenge

I encountered a monster. Do I use Range Attack, Melee Attack, or Flee? 🏹🗡🏃‍

<iframe src="https://trinket.io/embed/python/4306f297b0?runOption=run&showInstructions=true" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

---

## Functions 💬

----

Let's say our character's
*`weapon = "Sword"`* 🗡
Every time our character hit an enemy with the sword, we want it to inflict some damage to the enemy.

What would be a good way to represent the damage of the weapon and the health of the enemy? ⚔:heart: 

----

If we used variables 
``` javascript
enemyHealth = 100
weaponDamage = 5
```
to represent health and damage respectively, we could represent a successful strike against an enemy as
``` javascript
enemyHealth = enemyHealth - weaponDamage
```

But if I had to do this again and again, that might get a little frustrating to type over and over, and for more complicated sets of instructions, it also increases the chances that I could make an error.

----

### Function to the Rescue!

A great way around this is to use something called a **function**. Much like math, it take some inputs (parameters) and does things with them.

Similar to the math function $f(x) = x^2$ which takes $x$ and gives us back $x^2$ for any number $x$, we can define sets of instructions in Python.

Let's see what a function like this would look like.

----

### Declaring Functions
In python, we need to explicitly tell python that we are trying to declare a function, and the way to do it is by using the *`def`* keyword.

So a function that subtracts weapon damage from an enemy's health would look something like:
``` javascript
def damageEnemy(weaponDamage, enemyHealth):
```
This is a function declaration (you declare that `damageEnemy` is a function with parameters `weaponDamage` and `enemyHealth`).

----

### Function Parameters
A function can take any number of parameters (interchangably called inputs) with which it can do fun little things.

----

### Return Statement
However, doing these things isn't very useful if we can't do anything with the result. For example, $f(x) = x^2$ returns the square of $x$. So if I evaluate $f(5)$ I get $25$.

Similarly, Python functions can also return values! To do this, put *`return whatIWantToReturn`* at the end of the function. So if I were to model $f(x) = x^2$ I could code this as:
``` javascript
def f(x):
    power = x**(2)
    return power
```

----

### Challenge

So now that you understand, can you make a function that damages an enemy? Try it out!

<iframe src="https://trinket.io/embed/python3/16e4bf65e0" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

Now you have a working function... or do you? A great way to test if your function works is by... literally making it work. So how do we actually get something out of a function? Well, you can just plug in values and assign the return value to another variable. Let's try this.

<iframe src="https://trinket.io/embed/python/ca93da31f2" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

See, it's that easy! Functions allow you to express more things in less code. A great saying I love is: efficiency is clever laziness, and this is exactly a mindset a good programer should have.

---

## Loops ➰

----

So we managed to be a little lazy, but I'm about to teach you guys how to escalate your laziness to a new level. Let's say your character encountered a boss with 50 health, but your damage is only 10. How would we be able to kill the boss?

----

### For Loops

One solution would be to call our function 5 times, but is there a lazier way to do it? There is! We can use something called a **for-loop** which basically executes an instruction many times.

Syntax:
```python=
for variable in range(numberOfTimesToLoop):
    code
```

----

<iframe src="https://trinket.io/embed/python/cc7780526a" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

A for-loop can also loop through a list of items:
``` javascript
shop = {"shield": 20, 
        "sword" : 30,
        "bow": 50,
        "armor": 100,
        "ax": 40 }
inventory = []
for item in shop:
    if shop[item] < 50:
      inventory.append(item)
print(inventory)
```
What do you think will be printed?

----

### While Loops
What if we want to keep attacking until the boss dies? :skull: 
Maybe we don't know his health ahead of time.

To keep repeating an operation when you don't know how many times you have to do it (in this case hit the boss) but do know when you would stop (when the boss dies), we use something called a **while loop**.
Like the name suggests, this kind of loop runs as long as a condition is satisfied.

----

So to kill this boss, we can write the following piece of code:


<iframe src="https://trinket.io/embed/python3/978a8f7316" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

---

## Libraries/Modules :book: 

----

Let's maximize our laziness. Let's say you are out in the woods and find a mystery chest full of both awesome and lame items. 

``` python
mystery_chest = ["shield","sword","bow","armor","ax","50 gold","a single pebble"]
```

Obviously if it's a mystery chest, we don't know what we're going to get. How can we make sure that we get a random item from the mystery chest? This is where using libraries comes in handy.

----

A 'library' is essentially a `.py` file containing a set of already pre-defined funtions. It is a 'library' of code that you can borrow. The way we can borrow code from the libary is using the `import` statement at the top of the file:

**`import library_name`**

In order to use a library's funcitons, we call the funtion using the following syntax:

**`library_name.function_name(parameters)`**

----

### 'random' Library
The `random` library is useful for things that rely on creating random sequences (e.g. generating random numbers, shuffling a list). Let's use the `random` library to randomize our mystery chest.

<iframe src="https://trinket.io/embed/python/928ca7f4ca?showInstructions=true" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

----

Check out the source code for the `random` library ([Source Code](https://hg.python.org/cpython/file/8962d1c442a6/Lib/random.py)). Imagine if we had to write this code from scratch, our game would take even longer to create!

Before you begin coding any complex function/program, try googling to see if a library already exists for it. Chances are, someone already did the hard work and coded up a library for it with proper documentation.

---

Congratulations, you made it to the end of the tutorial!
Hope you learned something useful :smile:

---

## Resources/Tutorials
- [Python 3 Official Documentation](https://docs.python.org/3/)
- [Codecademy](https://www.codecademy.com/learn/learn-python) interactive intro course to Python
- [W3Schools](https://www.w3schools.com/python/) Python tutorials
- [Tutorialspoint](https://www.tutorialspoint.com/python/) Python tutorials
- [Stack Overflow](https://stackoverflow.com/) online forum community for developers
- [Google](https://www.google.com/) what you are looking for starting the search with “python [question]”

---

## UCSD Classes with Python
- [ECE 16](https://www.ucsd.edu/catalog/courses/ECE.html): Rapid Hardware and Software Design for Interfacing with the World
- [ECE 143](https://www.ucsd.edu/catalog/courses/ECE.html): Programming for Data Analysis
- [COGS 18](https://www.ucsd.edu/catalog/courses/COGS.html): Introduction to Python
- [MATH 187A/B](https://www.ucsd.edu/catalog/courses/MATH.html): Introduction to Cryptography