Week 1: Variables, Operators, Strings Flashcards
a) Define Variable
b) In python everything is an ______
c) Variables _______objects stored in a computer’s memory
d) Python does not require variables to be _____ ______ (ie. you can create a variables by simply assigning it a value)
a) Variable: Named area in a computer’s memory that can store a value
b) In python, everything is an object
c) Variables point to (reference) objects stored in the computer’s memory
d) Python does not require variables to be explicitly stated (you can create a variable by simply assigning it a value)
Define identifier
What are the rules for variable or function identifiers?
An identifier is a name we give to variables or functions
- In python there are certain rules we must follow when naming variables or functions
- Case sensitive
- Must start with a letter or underscore
- Can only contain letters, digits, or underscores
- Can not be identical to a built-in keyword
Some common naming conventions for identifiers
Some common naming conventions:
- snake_case
- camelCase
- SCREAMIG_SNAKE_CASE
- SCREAMINGCASE
- UpperCamelCase (aka. Pascal Case)
- flatcase
Style guidelines for variable identifiers
- should always have a meaningful name
- try not to make it too long
- should follow a consistent style
What is PEP8
Naming conventions under PEP8
PEP8 is python’s recommended style guide
PEP8 Naming Conventions:
- snake_case should be used for variable and function identifiers
- Never use the characters “I” “l” or “O” as single character variable names
- Shoud only use English words and letters whenever feasible
- SCREAMING_SNAKE_CASE should be used for constants
Define Constants
Constants are variables whose value should never change after its initial value set
- python does not enforce this, but you should let other programs know a value is a constant by using SCREAMING_SNAKE_CASE
Variables in python are ____ typed
This means ___?
Variables in python are dynamically typed
This means one variable can be assigned values of different types
Some of the built-in data types
-
int (integer)
used for whole numbers, negative or positive -
float (floating-point)
used for real numbers with decimal points, can be positive or negative -
bool (boolean)
stores a true or false value, often used in conditions and logical operations -
str (string)
used for text, allowing you to work with strings of characters. can include most numbers, letters, and symbols -
list (list)
used to store a collection of items of any type. lists are often ordered and changeable, meaning you can add, remove or modify elements after creating them -
tuple (tuple)
similar to a list but immutable, meaning once its created, its elements can not be changed, added, or removed -
set (set)
unordered collection of unique elements, meaning it does not allow duplicate values and does not maintain any specific order. supports set operations like unions and intersections -
dict (dictionary)
collection of key-value pairs where each key is unique and maps to a corresponding value
What is the type() function
- We can find the type of an object using the type function
- The type function takes an object and returns its type
I.e.
Input:
w = true
type(w)
Output:
< class ‘bool’>
Define casting
What is implicit casting vs. explicit casting
Casting: converting values from one type to another is called casting
- Casting in python can either be implicit or explicit
- Implicit casting occurs automatically when some operation is performed by an object
- Explicit casting requires the programmer to manually use one of the built-in data type functions
Some built-in data type functions
int()
- Creates an integer value by converting a float or string (when possible)
- trunicates the decimal point
float()
- Creates a floating-point value by converting an integer or string (when possible)
str()
- Creates a string value by converting a value of another type (supports most other types)
2 common cases where you need explicit casting
- You wish to input a numerical value from the user, but the input() function returns a string
- You wish to concatenate (add) a numerical value to a string, but strings can not be added to numerical types
Define operators
How are they represented?
- Operators are used to perform operations on objects and values
- Operators are represented as special symbols or keywords that designate some type of computation
Categories of operators
- Assignment operators
- Arithmetic operators
- Comparison operators
- Booelean or logical operators
- Identity operators
- Membership operators
- Concatenation and repetition operators
- Bitwise Operators
What is the Assisgnment Operator and how it works?
The Assignment Operator: used to assign values to variables
- The value of the expression on the right is evaluated and the result is stored in the variable on the left
Assignment Operator Example:
Input:
x = 10
y = 5
z = x + y
x = 3
y = 2
z = z +1
print(x, y , z)
What is the output, and explain why?
3 2 16
- x is assigned to 10 then reassigned to 3 so x is 3
- y is assigned to 5 then reassigned to 2 so y is 2
- z is assigned to x+y. At the time x was 10 and y was 5 so z is 15, and 15 is stored in z even after x+y change.
- then z is reassigned to z+1 so z now stores the value 16
Define arithmetic operators
arithmetic operators allow you to perform arithmetic operations on numeric values
What are some common arithmetic operators
More common arithmetic operators
What is the order of operations for arithmetic operators?
The order of operations from highest to lowest priority is:
1. Parentheses
2. Exponents
3. Multiplication, Division, and Modulo
4. Addition and Subtraction
What are compound operators.
Examples of compound operators.
additional Assignment Operators called compound operators provide shorthand for some common assignments we tend to see with variables.
What are some built-in math functions?
What is a module
A python module is a file containing Python code, such as functions, classes, and variables, that can be imported and used in other Python programs
The Python standard library comes with many premade modules that include helpful functions and classes we can use in our programs.
How do we import modules? (what keywords do we use)
To use a module, we first need to import it into our program using the from and import keywords.
Example:
- from math import sqrt
What is the math module?
What are some common functions in the math module.
The math module contains extra math functions that are not included by default. These must be imported before using them.
Some more math module functions (2)
Some more math module functions (3)
What are 4 ways to import modules
Define strings and string literals
strings are immutable sequences of characters that store text (letters, digits, symbols etc)
- Immutable means strings can not be changed after they are created
string literals are string values specified by the programmer in the source code of a program
- String literals are always surrounded by quotation marks
- Can be single or double quote
What does immutable mean?
can not be changed after its creation
Define escape sequences
What is the escape character?
escape sequences are used to represent special characters within strings
- each escape sequence starts with the escape character, a backslash
Common escape sequences
Why is dealing with quotes within strings a common problem and how do we solve it (2 ways)?
- Dealing with quote marks inside strings is a problem because the string is represented by quotation marks.
- You can use escape sequences to insert quotation marks
- Also if you use double quote marks for the string then you can have single inside it with no problems and vice versa
BUT to keep the style consistent you have to use double or single for the entire thing
What is the len( ) function and what can we use it for?
The len( ) function takes a collection or sequence value and returns the length of that value. For strings, this is the number of characters.
We can find the number of characters in a string using the built-in len( ) function.
Explain string indexing
What do we use to represent string indexing?
We can think of strings as a continuous set of boxes, one for each character, each with their own index.
We can access the value of a specific character using string indexing.
String indexing uses brackets [ ] after the variable name that contain the index of the character we want
- is read from left to right
- starts with index 0 and counts up per character
Explain negative string indexing
like string indexing but is read from right to left (backwards) and the indexing starts at -1
Example:
Input:
s = “Hello World”
print(s[0])
print(s[5])
print(s[10])
What is the output?
H
d
- index 0 outputs H
- index 5 outputs a whitespace character
- index 10 outputs d
Example:
Input:
s = “Hello World”
print(s[-1])
print(s[-3])
print(s[-10])
What is the output?
d
r
e
- index -1 is the last character in the string in the string
- index -3 is the third from last character in string
- and index 10 is the 10th from last/10th character when you read string from right to left
Example:
Input:
s = ‘Hello World’
print(s[11])
print(s[-12])
s[0] = ‘Z’
What is the problem/error with each of these?
- print(s[11]) is out of range, there is no index 11
- print(s[-12]) is out of range, there is no index -12
- s[0] = ‘Z’ is not possible - not allowed to modify strings
What are some string operations?
several of the arithmetic operations we have seen have a special meaning when used on strings.
What are methods?
- Some objects have methods associated with them
- Methods are a collection of programming instructions to carry out a specific task
- Methods define the behaviors of objects or the actions we can perform on them
- Similar to functions but methods can only be applied to objects of a given type
What are some common string methods
What are docstrings
How do we represent them?
- Python provides a second way to document our code in addition to comments (lines that start with a #)
- Docstrings are a special kind of string literal that can be used to document a module (file), function, method, or class
- If we don’t assign a string to any variable it acts like a comment and is ignored by Python. Docstrings take advantage of this.
- Docstrings are surrounded by triple quotes (The double quote character repeated 3 times “””)
Can multiple variables point to the same object
yes
What is an algorithm
a sequence of instructions that solves a problem
What is computational thinking
creating a sequence of instructions to solve a problem (an algorithm) - in the information age, many people believe this will become increasingly important, like mathematical thiking was in the industrial age
What is a computer program
consists of instructions executing one at a time.
What are the basic instruction types (the basic things a computer program consists of)
- input: a program receives data from a file, keyboard, touchscreen, network, etc.
- process: a program performs computations on that data such as adding two values like x + y
- output: a program puts that data somewhere, such as a file, screen or network
Where does the name variable come from for programming
the name variable is to due a variable’s value varrying as a program assigns a variable with new values
What is the Python interpreter?
What is an interactive interpreter?
The Python interpreter is a computer program that executes code written in Python language
Aninteractive interpreteris a program that allows the user to execute one line of code at a time.
What is code? What is a line?
code: the text that represents a program
line: a single row of text in the code
What symbol does the interactive interpreter use to show it’s ready for input?
> > >
How do you execute a line of code in the interactive interpreter?
Type the code and press Enter.
When is the interactive interpreter useful?
For simple operations or short programs.
Why might a programmer write code in a file instead of using the interactive interpreter?
Writing in a file is better for longer programs, as the interpreter can run all lines from top to bottom.
What is a statement?
A single instruction in a program.
What is an expression?
Code that returns a value, like wage * hours * weeks.
How do you create a variable in Python?
By using the = symbol, like salary = wage * hours * weeks.
What does the print() function do?
It displays values or results.
What symbol is used for comments in Python?
#
are comments optional in python code
yes, you dont need comments for your code to run, but they can help a human reader understand the code
How to keep output on the same line with print()
Use end=’ ‘ inside print()
What is the newline escape sequence and its use
\n moves output to the next line
How to print “1”, “2”, and “3” each on a new line
print(‘1\n2\n3’)
What is whitespace in programming
Includes spaces, tabs, and newlines
What does the input() function do
It reads input from a user
How to store user input as a variable in Python
Use variable_name = input()
What happens when input() is called
The program waits until the user enters text and presses Enter
What type of data is returned by input()
A string
How to prompt the user with input()
Add text inside input(“Enter a number: “)
What is IDLE?
The official Python IDE, included with Python installation
What is an IDE?
An integrated development environment for writing and debugging code
What does a processor do?
Executes instructions stored in memory
What is memory in a computer?
A circuit that stores instructions and data as 0s and 1s in addressed locations
What are high-level languages?
Programming languages using formulas or algorithms, like FORTRAN and ALGOL
How does a processor execute a program?
By reading and executing instructions in sequence from memory
What are bits?
Binary digits (0s and 1s) used to represent data in computers
What is a switch in computing?
A device that controls electricity flow, with “1” for flow and “0” for no flow
What are machine instructions?
Program instructions written in 0s and 1s
What is assembly language?
A human-readable form of machine instructions (e.g., “Mul 97, #9, 98”)
What is an assembler?
A program that translates assembly language into machine code
What is a compiler?
A program that translates high-level language code into executable programs
What is the base for decimal numbers?
What is the base for binary numbers?
What digits are used in binary numbers?
How is each digit weighted in decimal numbers?
How is each digit weighted in binary numbers?
What limits the range of values a variable can hold?
Why do computers use binary numbers?
- Base 10
- Base 2
- 0 and 1
- By increasing powers of 10
- By increasing powers of 2
- The number of bits allocated for it
- Memory locations are composed of bits (0s and 1s)
What is binary? What is a binary number?
a base 2 number system (only uses 2 digits: 0 and 1), which is different than the base 10 decimal system we are used to (which uses digits 0-9)
therefore, binary numbers are digits 0 and 1
How binary works vs. how decimal system works
what does the number 1011 in binary convert to in decimal? Explain why
How Binary Works
In the decimal system, each position (place) in a number represents a power of 10:
- For example, in the number 123, you have:
- 1 * 100 (10^2)
- 2 * 10 (10^1)
- 3 * 1 (10^0)
In binary, each position represents a power of 2:
- For example, in the binary number
1011
, you have:- 1 * 8 (2^3)
- 0 * 4 (2^2)
- 1 * 2 (2^1)
- 1 * 1 (2^0)
So, 1011
in binary equals:
- (1 * 8) + (0 * 4) + (1 * 2) + (1 * 1) = 8 + 0 + 2 + 1 = 11 in decimal
What are input/output devices?
Devices like screen, keyboard, mouse, and USB ports
What is storage in a computer?
Disk or flash storage that holds files and data, non-volatile
What is RAM?
Temporary memory that holds data for quick access, volatile
What is a processor (CPU)?
The component that runs programs and executes instructions
What is the clock in a processor?
A timer that controls the speed of processor instructions
How does adding RAM make a computer faster?
It allows more data to be kept close to the processor, reducing storage access
What is a scripting language?
A language that executes programs without needing compilation
What is a script?
A program executed by an interpreter
Why is interpreted execution slower?
It requires multiple interpreter instructions for each script instruction
Who created Python?
Guido van Rossum
What did Python 1.0 introduce?
What new feature did Python 2.0 add?
Why isn’t Python 3.0 backward compatible?
- Functional programming constructs
- Automatic memory management (garbage collection)
- It has design changes that prevent Python 2.7 programs from running on Python 3
What does it mean that Python is open-source?
As of January 2023, how popular is Python?
The community helps define the language and create interpreters
It’s the most popular language, with 16.36% popularity
Python is a high-level language that excels at creating exceptionally fast-executing programs.
True or False? Explain.
False
Python excels at providing powerful programming paradigms such as object-oriented programming and dynamic typing. Python incurs additional overhead costs because the language is interpreted.
What is an object?
represents a value and is automatically created by the interpreter when executing a line of code. For example, executing x = 4 creates a new object to represent the value 4.