1 of 43

Intro to Python

CSCI 344: Advanced Web Technologies

Spring 2025

2 of 43

Outline

  • Installing and configuring Python
  • Python Crash Course
  • Practice

3 of 43

Outline

  • Installing and configuring Python + Poetry
  • Python Crash Course
  • Practice

4 of 43

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.

5 of 43

Installing Poetry

You will also need to install Poetry, which is analogous to npm.

6 of 43

Outline

  • Installing and configuring Python
  • Python Crash Course
  • Practice

7 of 43

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

8 of 43

Data Types

9 of 43

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

10 of 43

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

11 of 43

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

12 of 43

List Methods

  • Detecting the length of a list:�len(my_list)
  • Indexing a list:�my_list[0]
  • Appending an element to a list:�my_list.append('some value')
  • Removing an element from a list (from the bottom):�my_list.pop()

12

13 of 43

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

14 of 43

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

15 of 43

Variables

16 of 43

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

17 of 43

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:�

  1. Ensure your variable names are mnemonic
  2. “Snake case” for functions and variable names
    1. first_name = 'Beyonce'
    2. last_name = 'Knowles'
  3. “Snake case” for file names too: hello_world.py
  4. Python is case-sensitive

17

18 of 43

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

19 of 43

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

20 of 43

Operators

21 of 43

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

22 of 43

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.

23 of 43

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

24 of 43

Functions

25 of 43

Some useful built-in functions

  • Outputting information — print()
  • Asking for information from a user — input()
  • Converting between data types — int(), float(), bool(), and str()

25

26 of 43

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)

27 of 43

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)

  • Indentation matters (4 spaces per “level”)
  • Type hints are suggestions, but they’re not enforced

27

28 of 43

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

29 of 43

Things that your interpreter doesn’t care about (but that you should): Type Hints

  1. Type Hints: Python doesn’t care whether or not your function signature has a data_type, but it’s *very useful for code readability:

def say_hello(name, time_of_day='morning'):

...

def say_hello(name: str, time_of_day: str='morning'):

...�

29

30 of 43

Things that your interpreter doesn’t care about (but that you should): Docstrings

  1. Docstrings: a way of documenting your code. Useful for helping others who might use your function later on; and also about helping your future self out when you revisit this code...wait...what did this do again?

30

31 of 43

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

32 of 43

Control & “Truthiness”

33 of 43

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

34 of 43

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

35 of 43

...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

36 of 43

...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

37 of 43

...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

38 of 43

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

39 of 43

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']

40 of 43

For Loops + Range Function

for i in range(10):� print(i)

41 of 43

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

42 of 43

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()

43 of 43

Practice Time!

Please download the lecture19 files