Intro to Python
CSCI 344: Advanced Web Technologies
Spring 2025
Outline
Outline
Installing Python
You will need to install python to build your server. Here is the documentation for doing it.
If you already have python installed on your computer, make sure your version is at least 3.8. If it isn’t you’ll need to upgrade your python installation.
Installing Poetry
You will also need to install Poetry, which is analogous to npm.
Outline
Comments
'''
There are two ways to do comments. For longer
comments, please feel free to use the "docstring"
notation: three quotes at the beginning of the
comment, three quotes at the end.
'''
# use the pound sign for smaller comments!
7
Data Types
Data Primitives
Type Example
Integer (int) 1, 555, -1000000
Float (float) 2.567, 3.14159
String (string) 'Hello world!'
Boolean (bool) True, False
None empty variable
In Python, the most basic data types are:
9
Strings & String Functions
‘My string’.lower() # returns a copy of the string that is all lowercase
‘My string’.upper() # returns a copy of the string that is all uppercase
‘My string’.replace(‘ ‘, ‘_’) # returns a copy of the string where the instances of the
first argument are replaced by the second argument
‘My string’.find(‘s’) # returns the position where the first instance of the
argument is found. Returns -1 if argument not found
‘Hello {0}’.format('Walter') # allows you to format and inject data into a string
More here: https://docs.python.org/3/library/stdtypes.html#string-methods
10
Lists
A list is a mutable sequence of values:
� list_of_strings = ['freshman', 'sophomore', 'junior', 'senior']�
Useful for organizing and conveniently accessing related data
11
List Methods
12
Dictionaries
# two ways to create a dictionary:�my_dict = dict(a=123, b=456)�my_dict = {'a': 123, 'b': 456}
# access an item by its key:�my_dict.get('a') my_dict['a']
# add a new item to a dictionary:�my_dict['c'] = 789
# iterate through a dictionary:�for key in my_dict:� print(key, my_dict.get(key))
13
Dictionaries and JSON
Dictionaries are easily converted to and from JSON using the built-in JSON module:
import json
json.dumps(my_dict) # converts a Python dictionary into a JSON string
json.loads(json_string) # convert a JSON string into a dictionary
Variables
Declaring Variables
Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (_). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.
401k_account = 'Z346rgGX' # illegal
account_401k = 'Z346rgGX' # OK
You don’t declare a type when creating a variable. Type is determined when you assign.
16
Naming Variables
Although Python doesn’t care what you name your variables (beyond the rules specified in the previous slide), there are some conventions that most people follow:�
17
Naming Variables: Snake Case
Functions
def divide_two_nums(num, denom):� return num / denom
def move_avatar_left(dog):� dog.x -= 1� dog.redraw()
Variables
time_left_til_end_of_class = 35
first_name = 'Jazmin'
last_name = 'Morales'
Examples of snake case variables and functions:
18
Reserved words
When naming variables, you aren’t allowed to use reserved words. The following words have special meanings in Python.
and del global not with� as elif if or yield� assert else import pass False� break except in raise None� class finally is return True� continue for lambda try� def from nonlocal while
19
Operators
Arithmetic Operators
�
21
+ | Addition | Adds values on either side of the operator |
- | Subtraction | Subtracts right hand operand from left hand operand |
* | Multiplication | Multiplies values on either side of the operator |
/ | Division | Divides left hand operand by right hand operand |
** | Exponent | Performs exponential (power) calculation on operators |
% | Modulus | Divides left hand operand by right hand operand; returns remainder |
// | Quotient | Divides left hand operand by right hand operand; returns quotient |
Comparison Operators
Comparison operators compare two operands according to a comparison rule and evaluate to either True or False (boolean)
22
Operator | Description |
== | If the values of two operands are equal, then the condition becomes true. |
!= | If values of two operands are not equal, then condition becomes true. |
> | If the value of left operand is greater than the value of right operand, then condition becomes true. |
< | If the value of left operand is less than the value of right operand, then condition becomes true. |
>= | If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. |
<= | If the value of left operand is less than or equal to the value of right operand, then condition becomes true. |
Logical Operators
Logical operators provide additional ways to determine whether something is true or false:
23
Operator | Description |
and | If both operands are True then the expression evaluates to True. Otherwise, the expression evaluates to False |
or | If either or both operands are True then the expression evaluates to True. If both operands are false, the expression evaluates to False |
not | If the operand is False than the expression evaluates to True (and vice versa) |
in | If the left operand is an element of the right operand, then the expression evaluates to True. Otherwise, the expression evaluates to False |
Functions
Some useful built-in functions
25
def name_of_function(parameters):
statement(s)
return some_value
26
function body has 1 or more statements, which have same indentation level (usually 4 spaces)
An optional return statement to return a value from the function
colon (:) marks end of function header
parameters (the way we pass data to a function)
Example: Function with type hints
def add_em(num_1: float, num_2: float) -> int:
return num_1 + num_2
# call / invoke the function
result = add_em(33, 44)
print('The sum is:', result)
27
Functions can have required and optional parameters
# defining the function
def say_hello(name: str, time_of_day: str='morning'):
print('Hello there,' + name + '!')
print('How are you this ' + time_of_day + '?')
# calling (invoking) the function
say_hello('Varun')
say_hello('Grace', time_of_day='evening')
28
positional & keyword parameters
No keyword argument (uses default)
Keyword argument overrides default
Things that your interpreter doesn’t care about (but that you should): Type Hints
def say_hello(name, time_of_day='morning'):
...
�def say_hello(name: str, time_of_day: str='morning'):
...�
29
Things that your interpreter doesn’t care about (but that you should): Docstrings
30
Things that your interpreter doesn’t care about (but that you should): Docstrings
def add_em(num_1: float, num_2: float):
'''
Adds two numbers together.
Args:
num_1(float): the first number in the addition operation.
num_2(float): the second number in the addition operation.
Returns:
float: the sum of the two numbers
'''
return num_1 + num_2
31
Control & “Truthiness”
Truthiness → Things that evaluate to True?
if True:
print('True always evaluates to True')
if 1:
print('1 also evaluates to True')
if 'Walter':
print('any non-null or non-False value also evaluates to True')
33
What evaluates to False?
if False:
# will not execute
print('False always evaluates to False')
if 0:
# will not execute
print('0 always evaluates to False')�
if None:
# will not execute
print('None always evaluates to False')
34
...more ways to be True...
if not False:
print('not False always evaluates to True')
if not 0:
print('not 0 always evaluates to True')
if not None:
print('not None always evaluates to True')
35
...more ways to be True...
# expressions and other operators can also be part of a conditional:
def check_password(password:str, username:str):
# some logic...
return True
if check_password('12345678', 'tylan98'):
print('Login...')
else:
print('Try again...')
36
...more ways to be True...
my_list = [1, 2, 3]
so this...
if len(my_list) != 0:
print('Not empty!')
...does the same thing as...
if my_list:
print("Not empty!")
37
If / Elif / Else Example:
1. def give_grade(score):
2. if (score >= 90):
3. return 'A'
4. elif score >= 80:
5. return 'B'
6. elif score >= 70:
7. return 'C'
8. elif score >= 60:
9. return 'D'
10. else:
11. return 'F'
38
While Loops & For Loops
39
# while loop:
counter = 0
while counter < len(names):
print(names[counter])
counter += 1
# for loop:
for name in names:
print(name)
names = ['Seamus', 'Millie', 'Scout', ‘Froggie', 'Lucy', 'Bagel']
For Loops + Range Function
for i in range(10):� print(i)
Range Function
Range functions help you to conveniently generate a list of numbers. This details of the range function are elaborated here.
range(10)�Generates a sequence from 0 to 9 (excludes last number)
range(5, 10)�Generates a sequence from 5 to 9 (excludes last number)
range(2, 30, 3)�Generates a sequence from 2 to 30, incrementing by 3 each time
41
Classes & Objects
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def displayGreeting(self):
print(f'Welcome {self.name}')
_______________________________________________________________________
person1 = User('Shirly', 67)
person2 = User('Walter', 67)
person1.displayGreeting()
person2.displayGreeting()
Practice Time!
Please download the lecture19 files