Untitled Quiz

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

What is the main difference between a tuple and a list in Python?

  • Tuples are mutable, while lists are immutable.
  • Lists can change their content, while tuples cannot. (correct)
  • Tuples use square brackets, while lists use parentheses.
  • Lists are faster than tuples in execution.

Which operator has the highest precedence in Python?

  • Parentheses (correct)
  • Multiplication
  • Addition
  • Division

Which of the following is a rule for valid variable names in Python?

  • Variable names must start with a letter or underscore. (correct)
  • Variable names can include spaces.
  • Variable names can begin with a digit.
  • Variable names can include any special characters.

What is the issue with the expression 0.1 + 0.2 - 0.3 in Python?

<p>Python's floating point arithmetic can introduce precision errors. (B)</p> Signup and view all the answers

How do you toggle line numbers in a Jupyter notebook?

<p>Press <code>ESC</code> then <code>L</code>. (B)</p> Signup and view all the answers

What is the output of the expression (13 + 5) * 2 in Python?

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

In versions prior to Python 2.7, how did Python handle floating-point numbers?

<p>Displayed up to 17 significant digits. (D)</p> Signup and view all the answers

Which of the following is NOT a free 'no install' option for running Python code?

<p>Local Anaconda installation (B)</p> Signup and view all the answers

What is the purpose of the append() method in a list?

<p>It adds elements to the end of the list. (C)</p> Signup and view all the answers

How do you retrieve the number of times a specific value appears in a list?

<p>Using the count() method. (C)</p> Signup and view all the answers

Which method would you use to remove an item at a specific index from a list?

<p>pop() (D)</p> Signup and view all the answers

When using the sort() method on a list, what is important to note?

<p>The sort() method modifies the list in place and returns None. (D)</p> Signup and view all the answers

What distinguishes dictionaries from lists?

<p>Dictionaries store objects in key-value pairs. (C)</p> Signup and view all the answers

How are lists defined in Python?

<p>Using brackets and commas. (B)</p> Signup and view all the answers

What does the extend() method do in a list?

<p>It combines another list or iterable into the current list. (A)</p> Signup and view all the answers

Which method is used to reverse the elements of a list?

<p>reverse() (A)</p> Signup and view all the answers

What is a primary advantage of dynamic typing in Python?

<p>Faster development time (C)</p> Signup and view all the answers

Which of the following illustrates correct string slicing in Python?

<p>my_string[1:5:2] (A), my_string[0:5:1] (D)</p> Signup and view all the answers

Which of the following statements about variable assignments in Python is true?

<p>Variable names cannot include special meaning words like 'str'. (C)</p> Signup and view all the answers

What would be the output of the following code? print('The band for', name, 'is', band, 'out of 10')

<p>The band for Sarah Fier is 8 out of 10 (B)</p> Signup and view all the answers

What is the reverse index of the first character in the string 'hello'?

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

Which of the following is NOT a valid way to format a string for printing in Python?

<p>my_name.format('Hello') (C)</p> Signup and view all the answers

What occurs if you mix single and double quotes incorrectly in a string?

<p>Python raises a syntax error. (A)</p> Signup and view all the answers

What is the result of the operation mytax = myincome * tax if myincome is 1000 and tax is 0.2?

<p>200 (D)</p> Signup and view all the answers

What will happen if you try to add a duplicate value to a set?

<p>The set will ignore the duplicate and keep unique values. (A)</p> Signup and view all the answers

Which method can be used to remove an element from a set without raising an error if the element does not exist?

<p>Discard (D)</p> Signup and view all the answers

What does the 'update' method do in the context of sets?

<p>It adds elements from another iterable to the set. (B)</p> Signup and view all the answers

How can you create a set containing unique characters from the string 'Mississippi'?

<p>set('Mississippi') (A)</p> Signup and view all the answers

What is the result of reading a file after the cursor has reached the end of the file?

<p>An empty string will be returned. (A)</p> Signup and view all the answers

Which of the following correctly identifies a property of sets?

<p>Sets can contain mixed data types. (B)</p> Signup and view all the answers

What will the 'readlines' method return when called on a file object?

<p>A list of all lines in the file. (A)</p> Signup and view all the answers

Which statement correctly describes the outcome of calling the 'pop' method on a set?

<p>It removes and returns an arbitrary element from the set. (C)</p> Signup and view all the answers

What is the primary purpose of the myfile.seek(0) function?

<p>To reset the cursor to the beginning of the file (D)</p> Signup and view all the answers

What will the .readlines() method return?

<p>A list of all lines in the file (B)</p> Signup and view all the answers

Why is it important to use myfile.close() after file operations?

<p>To prevent errors when trying to delete the file externally (B)</p> Signup and view all the answers

What does the mode 'w' signify when opening a file?

<p>Write only mode, overwriting existing content (B)</p> Signup and view all the answers

Which of the following statements is true about the with statement in file operations?

<p>It automatically closes the file after the block is executed. (B)</p> Signup and view all the answers

What will happen if you try to open a file that does not exist using mode 'w'?

<p>Python will create the file. (C)</p> Signup and view all the answers

What does the mode 'r+' allow you to do?

<p>Read from and write to the file (D)</p> Signup and view all the answers

How can you retrieve the last character from the string s = 'hello'?

<p>s[-1] (A)</p> Signup and view all the answers

What characteristic differentiates tuples from lists?

<p>Tuples are immutable and cannot be changed. (D)</p> Signup and view all the answers

Which method is used to add a new element to a dictionary?

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

Which of the following operations can be performed on a set?

<p>Add new unique items (C)</p> Signup and view all the answers

How will the program respond if you attempt to reassign an element in a tuple?

<p>It will raise an error. (B)</p> Signup and view all the answers

What will the expression d.values() return if d is defined as d={'K1':100,'K2':200,'K3':300}?

<p>[100, 200, 300] (A)</p> Signup and view all the answers

What is the purpose of the method d.popitem() in a dictionary?

<p>To return and remove the last inserted key-value pair. (B)</p> Signup and view all the answers

Which method can be used to find the number of times a specific element appears in a tuple?

<p>Count (D)</p> Signup and view all the answers

Which of the following statements about sets is true?

<p>Sets store unique, unordered elements. (C)</p> Signup and view all the answers

Flashcards

Python Installation

Python can be installed using Anaconda from www.anaconda.com/downloads. Free online options like jupyter.org/try and Google Colab are alternative ways to use Python.

Jupyter Notebook - Keyboard Shortcuts

Jupyter Notebook uses keyboard shortcuts for common actions like toggling header or toolbar, and viewing line numbers.

Python - Adding Line Numbers

Line numbers in code cells can be added via the Jupyter Notebook menu (View -> Toggle Line Numbers) or by using a keyboard shortcut (ESC then L).

Python Data Types - Tuples vs. Lists

Tuples are immutable sequences (cannot be changed after creation) represented with parentheses, while lists are mutable sequences (can be changed) represented with square brackets.

Signup and view all the flashcards

Python Numbers - Integers vs Floats

Python supports integers (whole numbers) and floating-point numbers (numbers with decimals).

Signup and view all the flashcards

Floating-Point Arithmetic Limitations

Due to how computers store floating-point numbers, calculations involving decimals might not always produce precise results, like 0.1 + 0.2 != 0.3.

Signup and view all the flashcards

Python Variable Names - Rules

Python variable names cannot start with a number, contain spaces, or use special symbols like ", /, ?, , (, ), !, @, #, etc. Lowercase names are preferred (PEP 8).

Signup and view all the flashcards

Python Order of Precedence

Python follows a specific order for evaluating mathematical operations (parentheses, exponents, multiplication, division, addition, subtraction).

Signup and view all the flashcards

Dynamic Typing

Python allows variables to hold different data types without explicit declaration.

Signup and view all the flashcards

Variable reassignment

Changing a variable's value to a different data type is allowed in Python.

Signup and view all the flashcards

String

A sequence of characters enclosed in single or double quotes.

Signup and view all the flashcards

String Indexing

Accessing individual characters within a string using their position (index).

Signup and view all the flashcards

String Slicing

Extracting a portion (a "slice") of a string based on starting and ending positions.

Signup and view all the flashcards

String Interpolation

Injecting variable values into strings for printing (displaying).

Signup and view all the flashcards

Escape Sequences

Special characters used to represent non-printable characters or formatting in strings.

Signup and view all the flashcards

String Length

The total number of characters within a string or sequence.

Signup and view all the flashcards

List append()

Adds an element to the end of a list.

Signup and view all the flashcards

List count()

Counts how many times an element appears in a list.

Signup and view all the flashcards

List index

Retrieving elements from a list using their position.

Signup and view all the flashcards

List slicing

Selecting a portion of a list by its range of indices.

Signup and view all the flashcards

List vs Dictionary

Lists store objects in order; Dictionaries use key-value pairs for faster retrieval.

Signup and view all the flashcards

Dictionary key-value

A way to store objects in dictionaries—using unique keys to identify each object’s value.

Signup and view all the flashcards

Dictionaries

Unordered data-structures used to store data using key-value pairs.

Signup and view all the flashcards

Nested Lists

Lists containing other lists.

Signup and view all the flashcards

What are Lists in Python?

Lists are ordered collections of items that can be indexed, sliced, and modified. They use square brackets [ ] to enclose elements.

Signup and view all the flashcards

What makes Lists unique?

Lists are mutable, meaning their elements can be changed or modified after they're created.

Signup and view all the flashcards

Dictionaries in Python

Dictionaries are unordered collections of key-value pairs. Keys are unique and can be used to access the corresponding value.

Signup and view all the flashcards

Accessing values in a Dictionary

You can access the value associated with a key using square brackets [ ] and the key name, like my_dict['Key1'].

Signup and view all the flashcards

Tuples in Python

Tuples are ordered, immutable collections of items enclosed in parentheses ( ). They are similar to lists but cannot be changed after creation.

Signup and view all the flashcards

Tuple Immutability

Once elements are inside a tuple, they cannot be reassigned. This ensures data integrity in situations where you need a constant sequence.

Signup and view all the flashcards

Sets in Python

Sets are unordered collections of unique elements. They are used to store multiple items without duplicates, and are represented by curly braces { }.

Signup and view all the flashcards

Set Mutability

Sets are mutable, allowing you to add or remove elements after creation. However, the elements themselves are immutable.

Signup and view all the flashcards

Reset File Cursor

Move the file's reading position back to the beginning. This allows you to read the entire file again from the start.

Signup and view all the flashcards

Read Entire File

Read the entire contents of a file into a list, where each line is an element in the list.

Signup and view all the flashcards

Read Single Line

Read only the next line from a file, returning the line as a string.

Signup and view all the flashcards

Open File From Any Location

Use the full path of the file to open it regardless of where your Python script is located.

Signup and view all the flashcards

Close File

Release the file, allowing other programs to access it, and preventing errors.

Signup and view all the flashcards

Open File with 'with' Statement

A safer way to open a file. It automatically closes the file when finished, even if errors occur.

Signup and view all the flashcards

File Modes

Different ways to open a file, specifying how you'll interact with it (read, write, append, etc.).

Signup and view all the flashcards

File Mode 'w' (write)

Opens a file for writing. If the file doesn't exist, it's created. Existing content is overwritten.

Signup and view all the flashcards

How do you create a set?

Sets are created using curly braces {} and elements are separated by commas. For example, {1, 2, 3} creates a set with elements 1, 2, and 3.

Signup and view all the flashcards

What is add() for sets?

The 'add()' method is used to add an element to a set.

Signup and view all the flashcards

What is remove() for sets?

The 'remove()' method is used to remove an element from a set. If the element doesn't exist, it will raise an error.

Signup and view all the flashcards

What is a boolean?

A boolean represents a truth value, either True or False, and is used to represent logical statements.

Signup and view all the flashcards

What is the purpose of 'open()' for files?

The 'open()' function is used to open a file in Python. It takes the file name as an argument and returns a file object that can be used to read or write data to the file.

Signup and view all the flashcards

What is the purpose of 'read()' for files?

The 'read()' method is used to read the entire contents of a file into a string.

Signup and view all the flashcards

What is the purpose of 'readline()' for files?

The 'readline()' method is used to read a single line from a file. It returns the line as a string, including the newline character at the end.

Signup and view all the flashcards

Study Notes

Python Installation

  • Download Anaconda from www.anaconda.com/downloads
  • Free "No Install" options are available:
    • jupyter.org/try
    • Google Colab Online Notebooks
  • Using free "No Install" options may present challenges in uploading user code, data, or notebooks
  • File saving may not be possible in free versions

Jupyter Notebook

  • Keyboard shortcuts are available through the Help menu
  • Toggle header and toolbar can be accessed through the View menu

Add Number to Cells

  • Use the menu, view, then toggle line number.
  • Use the keyboard shortcut or press ESC then L.

Basic Data Types

  • Integers: Whole numbers (e.g., 3, 300, 200) - int type
  • Floating-point: Numbers with a decimal point (e.g., 2.3, 4.6, 100.0) - float type
  • Strings: Ordered sequence of characters (e.g., "hello", 'Sammy', "2000"), or even emojis - str type
  • Lists: Ordered sequence of objects (e.g., [10,"hello",200.3]) - list type
  • Dictionaries: Unordered key-value pairs (e.g., {"mykey":"value","name": "Frankie"}) - dict type
  • Tuples: Ordered immutable sequence of objects (e.g., (10,"hello",200.3)) - tup type
  • Sets: Unordered collection of unique objects (e.g., {"a","b"}) - set type
  • Booleans: Logical values indicating True or False - bool type

Example Data Types

  • a=10, type is int
  • b=10.5, type is float
  • c="adel", type is str
  • d=[10,20.5,"adel"], type is list
  • e={"K1":"vaue1", "k2": "Value2"}, type is dict
  • f=(10,20.5,"adel"), type is tuple
  • s={"a","b",10,20.5}, type is set

Order of Precedence in Python

  • Parentheses, Exponential (exp), Multiplication, Division, Addition, Subtraction
  • Multiple variable assignments in one line (e.g., a, b, c = 10, 20, 30)

Basic Data Types: Tuples and Lists

  • Tuples: Ordered, immutable sequences. Once an element is in a tuple, it cannot be changed or reassigned. Uses parentheses (e.g., (1,2,3)).
  • Lists: Ordered, mutable sequences. Elements can be changed. Uses square brackets (e.g., [1,2,3]).

Basic Data Types: Numbers

  • Integers: Whole numbers (e.g., 3, 100)
  • Floating-point: Numbers with decimal points (e.g., 3.14, 10.0)

Floating Point Arithmetic Issues

  • Python's floating-point representation has limitations leading to inaccuracies in calculations involving decimal values (e.g., 0.1 + 0.2 ≠ 0.3).

Variable Assignments

  • Variable names cannot start with numbers or contain spaces. Use underscores to separate words in variable names (e.g., my_dogs).
  • Variables should typically be lowercase.
  • Avoid Python keywords like list and str as variable names.
  • Python uses dynamic typing, meaning you can reassign a variable to a different data type.

Variable Assignments: Example Usage

  • myincome = 1000
  • tax = 0.2
  • mytax = myincome * tax
  • print("The band for", name, "is", band, "out of", 10)

Strings: Basic Concepts

  • Strings are sequences of characters. Enclose strings in either single ('...') or double ("...") quotes.
  • Indexing: Access individual characters (e.g., s[0] for the first character)
  • Slicing: Extract subsets of characters (e.g., s[1:4] to get characters from index 1 to 3)

Strings: Example Indices

  • Characters: h -> e -> l -> l -> o
  • Indices: 0 -> 1 -> 2 -> 3 -> 4
  • Reverse Indices: -5 -> -4 -> -3 -> -2 -> -1

Strings: Escape Sequences

  • '\n' (newline character) - starts a new line in a string print operation
  • '\t' (tab character) - provides indentation in print operations

String Formatting

  • String interpolation, using print("Hello" + my_name), helps display data in strings.

String Indexing and Slicing: Summary

  • Indexing grabs a single character.
  • Slicing extracts a subsection of a string (e.g., slice[start:end:step]).

String Operations: Mutability

  • Strings are immutable. Attempts to assign a new value to a single index in a string will result in an error.

String Operations: Concatenation

  • The "+" operator can be used to concatenate strings (e.g., 'Hello' + ' ' + 'World!')

String Operations: Functions

  • Use x.split('character') to split a string based on a specific character

String Operations: Immutability

  • Strings are immutable (cannot be changed after creation).

String Formatting for Printing

  • Use format() method and f-strings:
    • {variable} in format strings
    • f'{variable}' in f-strings

List Methods

  • append(): Adds an element to the end of a list.
  • insert(): Inserts an element at a specific index.
  • pop(): Removes and returns the item at a specific index (or the last item if no index is given).
  • remove(): Removes the first occurrence of a specific item.
  • sort(): Sorts a list in place. sorted(mylist) sorts a list and returns a new sorted list, without modifying the original.
  • extend(): Add multiple items to the end of a list.
  • reverse(): Reverses a list.

Dictionaries: Basic Concepts

  • Dictionaries are unordered collections of key-value pairs.
  • Use curly braces {} to define dictionaries, with keys and values separated by colons.

Dictionary Operations

  • Access values by their keys: my_dict['key1']
  • Adding new key-value pair: d['K4'] = 400
  • Modifying an existing value: d['K3'] = 5000
  • Iterating over keys/values: for k, v in my_dict.items():
  • keys(), values(), items() methods return views.

Tuples: Summary

  • Tuples are similar to lists but are immutable. Values inside tuples cannot be changed. Use parenthesis (()).

Sets: Basic Concepts

  • Sets are unordered collections of unique elements.
  • Use curly braces {} to create sets or use the set() constructor to create a set from a list.

Set Methods

  • add(): Adds an item to the set. If the item already exists, it's ignored.
  • remove(): Removes the specific item, resulting in an error if the item doesn't exist.
  • pop(): Removes and returns an arbitrary item from the set.
  • discard(): Removes the specific item if it exists. Otherwise, it does nothing. No error if the item doesn't exist.

Boolean: Summary

  • Booleans represent truth values (True or False).

Math Operations

  • import math
  • math.pow(10, 2) calculates 10 raised to the power of 2 (10 squared)

Files

  • I/O (Input/Output): Reading and writing to files in python.
  • Modes:
    • read only ('r') - open only to read from the file
    • write only ('w') - overwrite the file or create a new one
    • append ('a') - add to the file, without overwriting existing content
    • reading and writing ('r+') - open to modify existing file
    • writing and reading ('w+') - overwrite the file but read from file
  • Using .read() to read the entire file content
  • Using .readline() to read a single line from a file.
  • Using .readlines() read all lines (from file) into a list
  • Using .seek(0) to reset the cursor to the beginning of the file.
  • with statement:
    • A useful way for opening and closing files, ensuring the file is always closed, and avoiding potential errors.

Assessment Test: Examples

  • Strings: Find the square root of 100, reverse and print the string 'hello'.
  • Lists: Build a list of three zeroes in two different ways, reassign a nested list element.
  • Dictionaries: Access nested dictionary values.
  • Tuples: Explain the difference between tuples and lists.
  • Sets: Remove duplicates, Explain about set method and what they can do.
  • Booleans: Explain boolean operators.

Studying That Suits You

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

Quiz Team

Related Documents

Python Introduction PDF

More Like This

Untitled Quiz
55 questions

Untitled Quiz

StatuesquePrimrose avatar
StatuesquePrimrose
Untitled Quiz
18 questions

Untitled Quiz

RighteousIguana avatar
RighteousIguana
Untitled Quiz
50 questions

Untitled Quiz

JoyousSulfur avatar
JoyousSulfur
Untitled Quiz
48 questions

Untitled Quiz

StraightforwardStatueOfLiberty avatar
StraightforwardStatueOfLiberty
Use Quizgecko on...
Browser
Browser