Python Programming Basics
- 129Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- spaceFlip card
- KI knew it
- DI didn't know it
- ←Previous card
- →Next card
What are common reasons to learn Python?
Python is useful for pursuing programming jobs, automating tasks, and writing scripts and programs.
Or swipe the card
129 cards
What are common reasons to learn Python?
Python is useful for pursuing programming jobs, automating tasks, and writing scripts and programs.
Why is Python often considered beginner-friendly?
It has relatively little syntax to learn, so beginners can start writing programs quickly.
What are the two major Python versions described in the course, and which is presented as the forward-looking version?
Python 2 and Python 3; Python 3 is presented as the newer version being actively maintained and supported.
What is the status of Python 2 compared with Python 3, according to the course?
Python 2 is a legacy version and is no longer officially maintained or supported; Python 3 is the actively maintained version.
What is one stated advantage of Python 2, and what is its drawback?
It has more existing libraries and code, but it is no longer officially supported.
How similar are Python 2 and Python 3, according to the course?
They have some syntax and other small differences, but learning Python 3 makes it possible to start coding in Python 2 as well.
What does IDE stand for, and what is it used for?
Integrated development environment; it provides tools for writing, running, and debugging code.
Which IDE is used in the course, and what are its two editions?
PyCharm; it has a paid Professional edition and a free, open-source Community edition.
When creating a PyCharm project for this course, which Python interpreter should be selected?
A Python 3 interpreter.
What does a basic Python
printstatement do?It displays the value or text passed to it, such as
print("Hello world").Where does output from a Python
printstatement appear in the IDE?In the console.
How does Python execute the instructions in a file, and why does their order matter?
Python executes the lines in order. Changing their order can change the program’s output and behavior.
What is a variable in Python, and why is it useful?
A variable is a named container for a value. It makes data easier to manage and reuse than manually changing repeated values throughout a program.
How are multiple words commonly separated in a Python variable name?
With underscores, as in
character_name.How can a Python variable’s value be changed?
Assign a new value to the variable, for example,
character_name = "Mike".What are the three basic data types emphasized for new Python programmers?
Strings (text), numbers (whole or decimal), and Booleans (
TrueorFalse).How does Python distinguish a string value from a numeric value?
Strings are enclosed in quotation marks; numeric values are written without quotation marks.
What is a Boolean value, and what is an example of its use?
A Boolean is either
TrueorFalse. For example,is_malecan record whether a condition is true.How can a newline be inserted inside a Python string?
Use the escape sequence
\n.What is the escape character in Python strings, and what does it do?
The backslash (
\) is the escape character; it lets a following character be treated literally or used in an escape sequence.How can a quotation mark or a backslash be included literally in a Python string?
Escape it with a backslash, such as
\"for a quotation mark or\\for a backslash.What is string concatenation?
Combining strings, often with
+, such asphrase + " is cool".What do the string methods
lower()andupper()do?They return versions of a string converted entirely to lowercase or uppercase.
What does the string method
isupper()check?It returns
Trueif the string is entirely uppercase andFalseotherwise.How can the number of characters in a string be found?
Use
len(string).How are characters indexed in a Python string?
Indexing starts at 0, so the first character is at index 0, the second at index 1, and so on.
How can a specific character in a string be accessed?
Use square brackets with its index, such as
phrase[0]for the first character.What does the string method
index()return?The index where the specified character or substring first occurs. If it is not found, the call raises an error.
What does the string method
replace(old, new)do?It returns a string in which occurrences of
oldare replaced withnew.What does
10 % 3return, and why?It returns 1, the remainder when 10 is divided by 3. The
%operator is the modulus operator.What is the difference between
int()andfloat()?int()converts a value to an integer (a whole number);float()converts it to a floating-point number, which can include a decimal.How can a number be converted to a string, and why might this be necessary?
Use
str(number). It is needed when combining or printing a number alongside a string.What mathematical operations can Python perform directly on numbers?
Basic arithmetic, including addition, subtraction, multiplication, and division; parentheses can specify order of operations.
What does the
abs()function return?The absolute value of a number, such as 5 for
abs(-5).What does
pow(base, exponent)calculate?The base raised to the specified exponent, such as
pow(3, 2)returning 9.What do Python’s
max()andmin()functions return?max()returns the largest supplied value;min()returns the smallest.What does Python’s
round()function do?It rounds a number according to standard rounding rules, such as 3.2 to 3 and 3.7 to 4.
How can the
floor(),ceil(), andsqrt()functions be accessed, and what do they do?Import them from the
mathmodule.floor()rounds down,ceil()rounds up, andsqrt()returns a square root.What type of value does Python’s
input()function return by default?A string, regardless of what the user types.
How can a program prompt a user and store their response?
Assign a call to
input()to a variable, optionally including a prompt, such asname = input("Enter your name: ").Why must user input be converted before it is used as a number in calculations?
input()returns a string, so convert the response withint()orfloat()before performing numeric arithmetic.Why might adding two unconverted inputs such as
"5"and"8.3"produce"58.3"instead of a sum?They are strings, so
+concatenates them rather than adding them numerically.When should a calculator convert user input with
int(), and when should it usefloat()?Use
int()when only whole numbers are needed; usefloat()when decimal inputs should be accepted.What is the basic structure of a Mad Libs program?
Prompt the user for words, store them in variables, and insert those values into a story or poem.
What is a Python list, and what is it commonly used to store?
A list is a structure for storing multiple values, often related values, so they can be organized and accessed together.
How is a Python list written, and what kinds of values can it contain?
Use square brackets, such as
["Kevin", "Karen"]. A list can contain strings, numbers, Booleans, or other values.How are list elements indexed in Python?
Starting at 0: the first element has index 0, the second has index 1, and so on.
How can an element near the end of a Python list be accessed using a negative index?
Negative indexes count from the end:
-1is the last element,-2the second-to-last, and so on.How can a slice select elements from a list?
Use
list[start:stop]; it includes the start index and excludes the stop index. Omitting the stop index selects through the end.How can an existing list element be changed?
Assign a new value at its index, such as
friends[1] = "Mike".What does the list method
extend()do?It appends the elements of another collection, such as another list, to the end of the list.
What does the list method
append()do?It adds one item to the end of a list.
What does the list method
insert(index, item)do?It inserts an item at the specified index and shifts later elements to the right.
What do the list methods
remove(),clear(), andpop()do?remove(item)removes a matching item;clear()removes all items;pop()removes and returns the last item by default.What does the list method
index(item)do, and what happens if the item is absent?It returns the index of the item. If the item is absent, it raises an error.
What does the list method
count(item)return?The number of times the item occurs in the list.
What do the list methods
sort()andreverse()do?sort()orders a list in ascending order;reverse()reverses its current order.What does the list method
copy()do?It creates a copy of the list.
What is the key difference between a list and a tuple?
A list is mutable and can be changed; a tuple is immutable after it is created.
How is a tuple created and indexed?
Create it with parentheses, such as
(4, 5). Its elements are indexed starting at 0, like list elements.When is a tuple a suitable choice instead of a list?
When storing values that should not be changed, such as a fixed set of coordinates.
What is a dictionary in Python?
A structure that stores information as key-value pairs, allowing a value to be looked up by its key.
How is a Python dictionary written, and what constraint applies to its keys?
Use curly braces with key-value pairs separated by colons, such as
{"JAN": "January"}. Keys must be unique.How can a dictionary value be accessed using square brackets?
Use the key inside square brackets, such as
month_conversions["NOV"].What does a dictionary’s
get()method do, and how can it provide a fallback?dictionary.get(key)returns the value for the key. A second argument supplies a default value if the key is missing.What is a Python function?
A reusable collection of code that performs a specific task.
How is a function defined in Python?
Use
def, a function name, parentheses, and a colon; indent the function body beneath the definition.Does defining a function execute its body?
No. The body runs when the function is called by its name with parentheses.
What is a function parameter?
A named input that a function can receive and use when it runs.
What does the
returnstatement do in a function?It sends a value back to the caller and exits the function.
What happens to statements placed after a function’s
returnstatement?They are not executed because
returnexits the function.What is an
ifstatement used for?It runs a block of code only when its condition evaluates to
True.What do
elseandelifdo in a conditional structure?elsehandles the case when preceding conditions are false;elifchecks another condition if earlier ones were false.What does the Boolean operator
orrequire for its condition to be true?At least one of its conditions must be true.
What does the Boolean operator
andrequire for its condition to be true?Both conditions must be true.
What does the
notoperator do?It negates a Boolean condition:
TruebecomesFalse, andFalsebecomesTrue.What do the comparison operators
==and!=test?==tests whether two values are equal;!=tests whether they are not equal.What do
>,<,>=, and<=test?They test whether one value is greater than, less than, greater than or equal to, or less than or equal to another.
How can comparisons be used to find the largest of three numbers?
Use conditional comparisons to test which number is at least as large as the other two, then return that number.
How can an
ifstatement be used to build a basic calculator?Compare the user’s operator with
+,-,*, or/, perform the corresponding operation, and handle an unrecognized operator separately.What is a
whileloop, and when does it continue running?It repeatedly executes an indented block while its condition remains
True.When does Python check a
whileloop’s condition?Before each iteration. If the condition is false, the loop body is skipped or the loop ends.
How can a counter be incremented by one using shorthand?
Use
counter += 1.What is an infinite-loop risk when writing a
whileloop?If the loop’s condition never becomes false, the loop continues indefinitely; update relevant state so the loop can eventually end.
What is a
forloop commonly used to iterate over?Items in a collection, such as characters in a string, elements in a list, or values in a range.
In a
for item in collectionloop, how does the loop variable behave?It refers to the next item in the collection on each iteration.
What does
range(5)produce for aforloop?The sequence of integers 0 through 4; the stop value 5 is excluded.
What does
range(3, 10)produce?The integers from 3 through 9; the stop value 10 is excluded.
How can a
forloop iterate over a list using its indexes?Use
range(len(list))for the indexes, then access each element aslist[index].What is a nested
forloop useful for when working with a two-dimensional list?The outer loop can traverse rows and the inner loop can traverse each row’s elements.
How can one list represent a two-dimensional grid in Python?
Store lists as elements of an outer list; each inner list can represent a row.
How can an element in a two-dimensional list be accessed?
Use two indexes:
grid[row][column].What is the key logic of a guessing game that repeats until the user guesses correctly?
Store the secret word and the user’s guess, then continue prompting in a
whileloop while the guess differs from the secret word.How can a guessing game enforce a limit on the number of guesses?
Track a guess count, compare it with a guess limit, and stop prompting when the limit is reached or the correct word is guessed.
How can a
forloop calculate a number raised to a variable power?Start a result at 1, multiply it by the base once per loop iteration, and repeat for the number of times specified by the exponent.
How can a loop-based translator replace vowels with another character?
Loop through the phrase’s characters, test whether each character is a vowel, and append either the replacement or the original character to a result string.
What is a Python comment, and what symbol begins a single-line comment?
A comment is text ignored by Python and intended for people reading the code. A single-line comment begins with
#.What does it mean to comment out a line of code?
Make Python ignore the line by turning it into a comment, without deleting it from the file.
What is the purpose of a
try/exceptblock?It lets a program handle an error instead of stopping unexpectedly when the error occurs.
Why should an
exceptclause usually name a specific error type?A bare
exceptcan catch many unrelated errors, making it harder to handle the actual problem correctly.What error can occur when converting nonnumeric user input with
int()?A
ValueErrorcan occur because the input cannot be converted to an integer.What error occurs when a program divides by zero?
A
ZeroDivisionError.How can the caught exception itself be made available in an
exceptclause?Use
except SomeError as err:; the exception details can then be accessed througherr.How is a file opened in Python, and what does the mode specify?
Use
open(filename, mode). The mode specifies how the file will be used, such as reading, writing, or appending.What do the file modes
r,w,a, andr+mean?rreads;wwrites and can overwrite existing contents;aappends;r+allows reading and writing.Why should a program close a file after using it?
Closing releases the file after use and is good file-handling practice.
What do the file methods
read(),readline(), andreadlines()return?read()reads the file’s contents;readline()reads the next line;readlines()returns the lines as a list.What does the file method
readable()indicate?Whether the opened file can be read.
What is the difference between opening a file in
wmode andamode?wwrites from scratch and can replace existing contents;aadds new content at the end.How can a new line be added when writing or appending text to a file?
Include the newline escape sequence
\nwhere the new line should begin.What is a Python module?
A Python file that can be imported so its functions, variables, and other contents can be used in another file.
How can a module be imported and one of its functions called?
Use
import module_name, then call an item with the module prefix, such asmodule_name.function_name().What is
pipused for?It is a package manager used to install, manage, update, and uninstall Python packages.
What does
pip install package_namedo?It installs the named package so it can be used in Python projects.
What are classes and objects in Python?
A class defines a data type or template; an object is a specific instance of that class with its own values.
Why are classes useful for representing real-world entities?
They let programmers define custom data types with attributes suited to entities that cannot be represented adequately by a single basic value.
How is a class defined in Python?
Use
class, a class name, and a colon; the class body is indented beneath the declaration.What is the purpose of a class’s
__init__method?It initializes a new object by setting up its attributes from values supplied when the object is created.
What does
selfrefer to in a class method?The particular object whose method is running.
How can attributes of an object be accessed?
Use dot notation, such as
student.nameorstudent.gpa.What is a class function, and what is it commonly used for?
A function defined inside a class; it can provide behavior or information for that class’s objects, such as checking whether a student meets an honor-roll GPA threshold.
What is inheritance in Python?
A class can inherit attributes and methods from another class instead of reimplementing them.
How is inheritance specified in a Python class declaration?
Put the parent class in parentheses, as in
class ChineseChef(Chef):.What does it mean for a child class to override a method?
It defines its own method with the same name, so the child class’s behavior is used instead of the inherited version.
How can a question class help organize a multiple-choice quiz?
A question object can store a prompt and its answer, allowing a quiz program to keep questions and answers together.
What is the basic process for running and scoring a multiple-choice quiz?
Loop through the question objects, display each prompt, compare the user’s response with the stored answer, increment the score for correct answers, and report the score.
What is the Python interpreter?
An interactive environment for entering and executing Python commands individually.
How does the Python interpreter differ from writing a program in an IDE?
The interpreter is useful for quick experiments and testing snippets; a text editor or IDE is better organized for writing full programs.
How can the Python interpreter be started from a command-line environment?
Open a terminal or command prompt and run the appropriate Python command, such as
python3for Python 3 where available.

Ask anything
We've read this whole study set, so questions about it get the best answers.