Course: CSCI 1250
Assignment: Assignment 3 - Variables, Data Types, and Coding Standards
Variables
- Containers for storing data
- The value can change when a variable is mutable
- Because Python is dynamically typed, variables must be declared and assigned in the same statement
- You can use
None
if you don’t want a value yet.
- You can use
- In Python, you need a name and a value for a variable.
- You can optionally add a type, such as
str
- You can optionally add a type, such as
Assignment
- Assignment operator (
=
)- The value on the right is assigned to the variable on the left.
- IE:
cheese = "mozarella"
- Variables can be re-assigned to any type.
- If you have a type hint for the variable, your IDE should stop you, but Python itself doesn’t care.
Data Types
- Numeric data and non-numeric data
int
→ integersfloat
→ decimal numbersstr
→ a list of characters; text databool
→True
orFalse
Type Checking
- You can check the type of a variable with the
type()
function in Python. - You can use this in a conditional expression, such as:
Type Conversion (Casting)
- Changes the data type of a variable to another
- Normally you’d have to use a casting operator, such as
as
- In Python, you have to use the casting functions, such as
int()
,float()
, andstr()
- These functions can raise errors when converting invalid values
float
→int
will truncate
Math
Operators
+
→ addition-
→ subtraction*
→ multiplication/
→ division//
→ floor division%
→ modulus**
→ exponentiation
Division
- In Python, division between two integers always results in a
float
, unless you use integer/floor division//
:
Modulo
- Returns the remainder of a division operation:
Strings
- Represented by the
str
class in Python - Concatenation → combining two or more strings
- You can only concatenate strings with other strings (or you raise a
TypeError
) - IE:
"me" + "ow"
→"meow"
- You can only concatenate strings with other strings (or you raise a
- Interpolation → inserting different things into a string
- You can use the
.format
method on strings, or anf-string
- IE:
f"i am {x} years old
(wherex
is anint
)
- You can use the
Methods
- You can get the character from a certain index using the
str[idx]
syntax.- IE:
"Hello"[0]
→"H"
,"Hello"[-1]
→"o"
- IE:
- You can get the length of a string using the
len()
function- IE:
len("ABC")
→3
- IE:
- You can slice strings using the
str[start:stop:step]
syntax.- The
stop
option is exclusive, and you can skip options - IE:
"Hello"[0:4]
→"Hell"
,"Hello"[0::4]
→"Ho"
- The
You can reverse a string with slicing by using
[::-1]
Coding Standards
- The style guide for Python is known as PEP 8
- Use
#
for inline (single-line) comments - Use
"""
for block (multi-line) comments - Use
snake_case
for naming variables/functions;PascalCase
for naming classes - Empty lines between functions/classes; two empty lines after
import
statements - Keep lines characters
- Use
Comments should describe the why not the what