Python Basics: Course Overview

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following best describes the use of indentation in Python code?

  • It is only necessary for aligning code neatly in the editor.
  • It is optional and used only for comments.
  • It defines code blocks, such as those within functions and loops. (correct)
  • It improves readability but is not syntactically enforced.

Given the list my_list = ['apple', 'banana', 'cherry'], how can you randomly select an item from this list using the random library?

  • `random.get(my_list)`
  • `random.shuffle(my_list)`
  • `random.choice(my_list)` (correct)
  • `my_list.random()`

What is the key difference between the sort() method and the sorted() function when used with lists in Python?

  • `sort()` can only be used with lists containing numbers, while `sorted()` can be used with any data type.
  • `sort()` modifies the original list, while `sorted()` returns a new sorted list. (correct)
  • `sort()` is a function of the `random` library, while `sorted()` is a built-in Python function.
  • `sort()` returns a new sorted list, while `sorted()` modifies the original list.

Which of the following operators is used to check if two values are not equal in Python?

<p>!= (B)</p> Signup and view all the answers

How can you convert the string '3.14' into a floating-point number in Python?

<p><code>float('3.14')</code> (A)</p> Signup and view all the answers

What is the result of the expression 15 // 4 in Python?

<p>3 (C)</p> Signup and view all the answers

Which of the following is a valid way to define a multi-line string in Python?

<p>Using triple quotes <code>'''</code> or <code>&quot;&quot;&quot;</code> to enclose the string. (A)</p> Signup and view all the answers

What is the primary purpose of using enums in Python?

<p>To define a set of named constants, making code more readable and maintainable. (C)</p> Signup and view all the answers

Given the tuple my_tuple = (10, 20, 30, 40), how would you access the second element (20) of the tuple?

<p><code>my_tuple[1]</code> (B)</p> Signup and view all the answers

In Python, what is the difference between an expression and a statement?

<p>An expression returns a value, while a statement performs an action or operation. (C)</p> Signup and view all the answers

Flashcards

What is a Variable?

A name in Python that refers to a value. It is created using the assignment operator (=).

What is a String?

A sequence of characters, words, or text, enclosed in quotation marks (single or double).

What is a Function?

A reusable block of code that performs a specific task. Defined using def keyword.

What is a Dictionary?

A data structure that stores data in key-value pairs, enclosed in curly braces.

Signup and view all the flashcards

What is the input() function?

A function to retrieve user input from the console.

Signup and view all the flashcards

What is the random library?

A module used for generating random numbers or making random selections.

Signup and view all the flashcards

What is a List?

A data structure that stores an ordered collection of items, enclosed in square brackets.

Signup and view all the flashcards

What is an if statement?

A conditional statement that executes a block of code if a specified condition is true.

Signup and view all the flashcards

What are f strings?

Uses embed variables into a string, string must start with f

Signup and view all the flashcards

What is a Boolean?

A value representing either True or False.

Signup and view all the flashcards

Study Notes

Python Basics Course Overview

  • Aims to teach the core aspects of Python programming
  • Does not require previous programming experience
  • Only a web browser is needed

Key Features and Applications of Python

  • Popular programming language
  • Excels in shell scripting, task automation, and web development
  • Commonly used for data analysis and machine learning
  • Adaptable for creating games and working with embedded devices

Introduction to Replit

  • Replit is an online IDE used for coding and running programs in web browsers
  • Replit provided a grant that made this course possible

Setting up Replit

  • Users can sign up or log in with a Google account
  • After logging in, create a new Replit, selecting Python as the language

Familiarizing with the Replit Interface

  • Code is written in the code editor
  • Output is displayed on the right side console
  • Files can be created and managed on the left side

Variables in Python

  • A variable is created by assigning a value to a name
  • Example: player_choice = "rock"
  • Convention: Use underscores for spaces in variable names
  • The equal sign (=) assigns a value to a variable

Strings in Python

  • A string is a word or a collection of characters
  • Strings are enclosed in quotation marks
  • Both single quotes and double quotes can be used, as long as the same quote is on each side

Functions in Python

  • A function is a set of code that runs when called
  • Defined using def, followed by the function name and parentheses
  • For example: def get_choices():

Indentation in Python

  • Indentation is important
  • Code indented the same amount is considered within the function
  • Use the tab key to indent lines of code

Return Statements

  • A return statement specifies what the function returns when called
  • Example: return player_choice
  • The function will return the player's choice to use elsewhere

Calling functions

  • Function is called by typing the name and using parenthesis
  • Call function like this: greeting()
  • The print() function will output text to the console

Dictionaries in Python

  • Dictionaries store data values in key-value pairs
  • Dictionaries are enclosed in curly braces

Key-Value Pairs

  • A sample key value pair in a dictionary would be name:beau
  • Key-Value Pairs are separated by a comma

Input function

  • Input function accepts input from a user which can be stored in a variable
  • Example: players_choice = input("Enter a choice rock, paper, or scissors")

Importing the Random Library

  • Libraries are imported with the import keyword
  • The random library generates random numbers

Lists in Python

  • Lists are used to store multiple items in a single variable
  • Lists are surrounded by brackets
  • Items in a list are separated by commas.
  • Example: food = ["pizza", "carrots", "eggs"]

Random library with Lists in Python

  • You can get a random item from a list using the random library
  • Using the random library you can call the .choice() method to randomly grab from a list
  • Example: dinner = random.choice(food)

Function Arguments

  • Functions can receive data when called, known as arguments
  • Arguments are specified inside the parentheses
  • Example with the function from the text: def checkwhen(player, computer):

If Statements

  • Allows programs to do different things depending on certain conditions
  • Checks a condition
  • Executes code under the if statement

Conditionals and Operators in Python

  • == checks if two values are equal
  • != checks if two values are not equal
  • < less than
  • > greater than
  • <= less than
  • >= greater than
  • and checks if two conditions are true

Else and Elif Statements

  • Used for additional conditions

Elif Statements

  • Elif statement can be used to evaluate a new condition

F Strings

  • Uses embed variables into a string
  • String must start with "f"

Refactoring Code

  • Making sure a program is easier to read and more understandable

Nested if statement

  • Is a if statement written inside of another if statement

How Access dictionary Value Via a Key

  • Use brackets []
  • Example: choices["player"]

Local Python Setup

  • Python can be setup locally on users machine
  • Visit python.org to download the latest version for your system

Run Python Through Terminal

  • Open a terminal in your OS and run the python command

Interactive Prompt

  • Python can be run through the command live using the REPL

Python in Visual Studio Code

  • Visual Studio Code (VSC) can be setup on users system
  • In VSC install the python extension

Variable Names in Python

  • Variable names can include characters, numbers, and underscores.
  • A variable name cannot start with a number.
  • Examples of valid variable names: name1, NAME, _name.
  • Invalid variable names include those starting with a number or containing special characters like !, or %.
  • Python keywords (e.g., for, if, while, import) cannot be used as variable names.
  • The Python editor typically alerts users when a keyword is used as a variable name, and the keyword often changes color (e.g., to blue).

Expressions and Statements

  • An expression is a piece of code that returns a value.
    • Example: 1 + 1 (returns 2) or "bow" (returns the string "bow").
  • A statement is an operation on a value.
    • Example: name = "bow" (assigns the value "bow" to the variable name) or print(name) (prints the value of the variable name).
  • A program comprises a series of statements, each typically on its own line.
  • Multiple statements can be placed on a single line using a semicolon (;).

Comments

  • Anything after a hash mark (#) in a Python program is considered a comment and is ignored by the interpreter.
  • Comments are often displayed in gray in code editors.
  • An inline comment is a comment that appears on the same line as code

Indentation

  • Indentation is significant in Python.
  • Random indentation will result in an IndentationError.
  • Indentation defines blocks of code, such as those within control statements, conditional blocks, functions, or class bodies.

Data Types

  • Python has several built-in data types.
  • A string is a data type indicated by anything surrounded by quotation marks.
  • The type() function can check the data type of a variable.
    • Example: type(name) returns the class of name.
  • isinstance() function checks if a variable is an instance of a particular class or data type.
    • Example: isinstance(name, str) checks if the variable name is a string and returns boolean.
  • Integer numbers are represented by the int class, while floating-point numbers (fractions) are represented by The float class.
  • Python automatically detects the data type from the assigned value.
  • Creating a variable of a specific type can be done using the class constructor.
    • Example: float(2) creates a float with the value 2.0.
  • Converting from one data type to another (casting) uses class constructors.
    • Example: int("20") converts the string "20" to the integer 20.
  • Converting a string to an integer will result in an error if the a non- numerical string is passed.
    • For instance int("test") should result in error
  • Other common data types in Python include complex (for complex numbers), bool (for booleans), list, tuple, range, dict (for dictionaries), and set.

Operators

  • Python has various operators, including assignment, arithmetic, comparison, logical, and bitwise operators.
  • Assignment operator = is used to assign a value to a variable.
  • Arithmetic operators include:
    • + (addition)
    • - (subtraction)
    • * (multiplication)
    • / (division)
    • % (remainder/modulus)
    • ** (exponent)
    • // (floor division, which divides and rounds down to the nearest whole number)
  • The minus sign (-) can also be used to denote a negative number.
  • The plus operator (+) can concatenate strings.
    • Example: "scamp" + " is a good dog" results in "scamp is a good dog".
  • Arithmetic operators can combine with the assignment operator.
    • Example: age += 8 is equivalent to age = age + 8.
    • This shorthand works with other arithmetic operators like -=, *=, etc.### Arithmetic Operators
  • Used for mathematical calculations
  • Examples include addition, subtraction, multiplication, division, and modulus

Comparison Operators

  • Used to compare two values
  • == checks if two values are equal
  • != checks if two values are not equal
  • > checks if one value is greater than another
  • < checks if one value is less than another
  • >= checks if one value is greater than or equal to another
  • <= checks if one value is less than or equal to another
  • Comparison operators return a Boolean value (True or False)

Boolean Data Type

  • Represents truth values: True or False
  • Boolean operators include NOT, AND, and OR

Boolean Operators

  • not negates a Boolean value (if something is not true)
  • and returns true if both operands are true
  • or returns the first non-falsy operand

OR Operator

  • If the first operand is not a false value, it returns the first operand (if x is not false, then x)
  • If the first operand is a false value, it returns the second operand (if x is false, then y)
  • Empty brackets [] evaluate to False.

AND Operator

  • Returns the second argument only if the first argument is true (If x is false, then x else y)
  • If the first argument is falsy (False, zero, empty string, empty brackets), it returns the first argument.

Bitwise Operators

  • Used for bit-level operations
  • Rarely used, only in very specific situations

Identity Operator (is)

  • Compares two objects
  • Returns true if both variables point to the same object

Membership Operator (in)

  • Checks if a value is contained in a list or another sequence

Ternary Operator

  • Allows you to define a conditional expression in a single line
  • return true if age > 18 else false implements it

Strings

  • A series of characters enclosed in single or double quotes
  • Strings can be assigned to variables
  • Strings can be concatenated with the + operator (phrase = 'bo' + 'is my name')
  • String variables can be concatenated (name + 'is my name')
  • += operator can be used to append to a string (name += “is my name”)
  • Numbers can be converted to strings using the str() constructor (str(age))
  • Strings enclosed in sets of three quotes (single or double) can span multiple lines

String Methods

  • Strings have built-in methods for manipulation
  • upper() converts a string to uppercase (name.upper())
  • lower() converts a string to lowercase (name.lower())
  • title() converts the first letter of each word to uppercase (name.title())
  • islower() checks if all characters in a string are lowercase (name.islower()) and returns a Boolean
  • Many other string methods, including isalpha(), isalnum(), isdecimal(), startswith(), endswith(), replace(), split(), strip(), and find()

String Method Return Values

  • String methods return a new modified string
  • They do not alter the original string

Global Functions for Strings

  • The len() function returns the length of a string (len(name))
  • The in operator checks if a string contains a substring ('au' in name)

String Escape Characters

  • Escaping allows special characters to be added to a string
  • Use a backslash character (\) to escape a character (e.g., \" to include a double quote in a double-quoted string)
  • \n creates a new line
  • \\ allows you to include a backslash in the string

String Indexing

  • Individual characters in a string can be accessed using square brackets with the index number (name[0])
  • Indexing starts at zero
  • Negative numbers count from the end of the string

String Slicing

  • A range of characters can be extracted from a string using slicing(name[1:3])
  • Omitting the start index starts at the beginning of the string
  • Omitting the end index goes to the end of the string

Boolean Data Type (bool)

  • Represents True or False values (done = True)
  • Booleans are useful with conditional control structures like if statements (if done: print("Yes"))
  • Capital T and F must be added to recognize the values

Boolean Evaluations

  • Numbers are true except for 0
  • Strings are false only when empty
  • Lists, tuples, sets, and dictionaries are false only when empty
  • The type() function can be used to check if a value is a boolean (type(done) == bool)

Boolean Functions

  • any() returns True if any value in an iterable is True
  • all() returns True only if all values in an iterable are True

Number Data Types

  • int: integer (whole number)
  • float: number with a decimal point (5.5)
  • complex: a number with a real and imaginary part (2 + 3j)

Complex Numbers

  • Complex numbers are written with a j suffix to denote the imaginary part (complex = 2 + 3j)
  • You can get the real and imaginary parts of a complex number using .real and .imag (num.real)

Math Functions

  • abs() returns the absolute value of a number (abs(-5.5))
  • round() rounds a number to the nearest integer (round(5.5))
  • Can specify precision with a second parameter(round(5.5,1) which would make the output 5.6)

Math Libraries

  • Math utility functions and constants are also provided by the math standard library module
  • math ,c math, decimal, fractions

Enums

  • Enumerations (enums) are readable names bound to a constant value
  • To use enums, you need to import the enum module (e.g.,from enum import Enum)
  • Enums must be initialized with a class (class State(Enum):)
  • An example includes inactive = 0 and active = 1

Enums in Python

  • Enums can be utilized to effectively create constants in Python, as the language lacks a direct method to enforce variable constancy.
  • Using state.active.value returns the actual pre-set value (e.g., 1).
  • state.active gives a reference to the enum member itself.
  • Enums can be accessed using bracket notation, such as state["active"].
  • Reassigning values within an enum is not possible, ensuring their constant nature.
  • To list all potential values, refer to the list property of that enum.
  • The total number of enum members can be determined by calling len(enum_name).

User Input in Python

  • The input() function facilitates obtaining user input.
  • input() pauses program execution, awaiting user input followed by the Enter key.
  • Incorporating a prompt directly within the input() function is possible.
  • Command-line tools can benefit from accepting input during program start.

Control Statements

  • Control statements are exemplified by the if construct.
  • Code blocks are delineated by indentation.
  • An else block executes if the if condition is unmet.
  • elif serves as a chained else if, testing additional conditions sequentially.
  • If no conditions in the if-elif chain are met, the else block is executed.

Lists in Python

  • Lists group multiple values under a common name.
  • Lists are defined using square brackets [].
  • List items are comma-separated.
  • Lists can contain mixed data types.
  • The in operator verifies item existence within a list.
  • Lists can be initialized as empty using [].
  • List items are accessed via zero-based indexing.
  • List items can be updated using their index.
  • Negative indexing allows access from the end of the list.
  • Slices extract portions of a list using [:].
  • The len() function returns the number of items in a list.
  • append() adds an item to the end of a list.
  • extend() adds multiple items (from another list) to the end of a list.
  • The += operator combines lists, similar to extend().
  • Omitting square brackets when using extend() or += with a string will add each character of the string as individual items.
  • remove() eliminates a specific item from a list.
  • pop() removes and returns the last item from a list.
  • insert() adds an item at a specific index.
  • Slices can insert multiple items at a specific index.
  • sort() arranges list items in ascending order and modifies the original list.
  • Mixing data types in attempts to sort will throw errors.
  • Uppercase letters are sorted before lowercase.
  • The key argument in sort() can customize the sorting logic.
  • To preserve the original list, create a copy, such as utilizing the [:] slice.
  • sorted() returns a new sorted list without altering the original.

Tuples in Python

  • Tuples create immutable groups of objects.
  • Tuples are defined using parentheses ().
  • Tuple items are accessed via zero-based indexing or negative indexing.
  • The len() function counts the items.
  • The in operator checks for item existence.
  • Slices extract portions of a tuple using [:].
  • sorted() creates a new sorted tuple.
  • The + operator concatenates tuples, creating a new tuple.

Dictionaries in Python

  • Dictionaries store key-value pairs.
  • Dictionaries are defined using curly braces {}.
  • Keys are immutable, while values can be of any data type.
  • Key-value pairs are separated by commas.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

Use Quizgecko on...
Browser
Browser