Try   HackMD

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
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More β†’

What is Python?

  • β€œPython is an interpreted high-level programming language for general-purpose programming” (Wikipedia)
  • 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


Python Syntax πŸ’»


"Hello World!"

By tradition, we will create our very first Python program:
"Hello World"
In Python, it will look like this:

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:

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, …)

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:

python helloWorld.py

Indentation
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’

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

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’


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!


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.


Your Turn:

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


Variables πŸ“₯


What is a variable?

Think of a variable as a container for storing a value.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’


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:

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!

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)


What if I want to change the value?

Easy. Just reassign it to another value!

my_var = 5
my_var = my_var + 3
print(my_variable)

What will this print?


Challenge

Let's make a RPG game character!


Data Types
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’

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.


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:


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.


Dictionaries ()

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

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


Boolean

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

Example:

is_learning_python = True

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


Operators βž•βž–βž—βœ–


Arithmetic Operators

You can do math in Python using arithmetic operators.


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


Challenge

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


Comparison Operators

You can compare two things using comparison operators.


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


Logical Operators

Logical Operators reads like English!

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.


Conditionals
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’


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:

if test condition:
    code

If test condition is True, code will execute.
Pay close attention to the : and indentation!

Take our scenario from earlier,


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?

Oh no! I drank both potions 😱


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

This is where elif and else comes in.

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:


Challenge

I encountered a monster. Do I use Range Attack, Melee Attack, or Flee? πŸΉπŸ—‘πŸƒβ€


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? βš”

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’


If we used variables

enemyHealth = 100
weaponDamage = 5

to represent health and damage respectively, we could represent a successful strike against an enemy as

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)=x2 which takes
x
and gives us back
x2
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:

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)=x2 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)=x2 I could code this as:

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!


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.

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:

for variable in range(numberOfTimesToLoop): code


A for-loop can also loop through a list of items:

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?

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’

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:


Libraries/Modules
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’


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.

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.


Check out the source code for the random library (Source Code). 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

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More β†’


Resources/Tutorials


UCSD Classes with Python

  • ECE 16: Rapid Hardware and Software Design for Interfacing with the World
  • ECE 143: Programming for Data Analysis
  • COGS 18: Introduction to Python
  • MATH 187A/B: Introduction to Cryptography