Programming by Python - Lecture 2
26 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the function of triple quotes in Python?

  • To span a string across multiple lines. (correct)
  • To create a string variable only.
  • To represent comments in the code.
  • To escape characters in a string.

How can you assign multiple variables in one line in Python?

  • Using an array to hold the values.
  • Python does not support multiple assignments.
  • Using the syntax x = y = z = value.
  • Using combined variable assignments with commas. (correct)

What would be the result of the following code? x = 100; del x; print(x)

  • Error: variable x is deleted. (correct)
  • The value is stored but not printed.
  • None
  • 100

Which of the following statements is correctly utilizing single and double quotes in Python?

<p>&quot;He said, 'Hello' to her.&quot; (B)</p> Signup and view all the answers

What does the print command do in Python?

<p>It displays the values of variables or strings on the screen. (D)</p> Signup and view all the answers

What will be the output of the following code: a = int(20.5)?

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

What is the result of converting the boolean value True using int()?

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

What will happen if you try to convert the string 'Hello World' to an integer using int()?

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

What will be the output of the following code: a = int('110011', 2)?

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

What will be the output of the following code: a = float('9.99')?

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

What is the correct way to define a tuple containing the elements 'a', 7, and 2.2?

<p>tuple = ( 'a', 7 , 2.2 ) (B)</p> Signup and view all the answers

Which statement about dictionaries is correct?

<p>Dictionaries consist of key:value pairs. (B)</p> Signup and view all the answers

How does a set in Python differ from a list?

<p>Sets cannot contain duplicate elements, while lists can. (A)</p> Signup and view all the answers

What will the expression 'bool(a == b)' evaluate to if a = 2 and b = 4?

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

Which of the following statements about Boolean data type is false?

<p>Non-empty collections are considered False. (D)</p> Signup and view all the answers

What type of conversion occurs when performing an arithmetic operation between an int and a float?

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

Which of the following is a valid syntax for initializing a dictionary in Python?

<p>dict = {} (A)</p> Signup and view all the answers

What is the output of 'print(bool(()))'?

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

What is the result of the following code? x = 100; print(x); del x; print(x)

<p>Traceback (most recent call last): NameError: name 'x' is not defined (B)</p> Signup and view all the answers

Which Python function is used to retrieve the data type of a variable?

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

What will be the output of print(type(10.10))?

<p>&lt;class 'float'&gt; (A)</p> Signup and view all the answers

How are elements in a Python list defined?

<p>Separated by commas and enclosed in square brackets (B)</p> Signup and view all the answers

What will the following code output? str = 'Hello World!'; print(str[2:5])

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

Which of the following statements is true about tuples?

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

What is the purpose of the + operator when used with strings in Python?

<p>It concatenates the strings. (C)</p> Signup and view all the answers

What is the output of print(['a', 786, 2.23] + [1, 'c'])?

<p>['a', 786, 2.23, 1, 'c'] (B)</p> Signup and view all the answers

Flashcards

Python Variable Creation

A Python variable is created when a value is assigned to it using the equal sign (=).

Python Variable Types

Python variables can hold different data types like integers (e.g., 100), floating-point numbers (e.g., 1000.0), and strings (e.g., 'Noha Sakr').

Multiple Variable Assignments

Python allows assigning the same value to multiple variables simultaneously (e.g., a = b = c = 10).

Combined Variable Assignments

Python allows assigning multiple values to multiple variables at once by separating variables and values with commas (e.g., a, b, c = 10, 20, "Yusef").

Signup and view all the flashcards

String Literals (Python)

Python uses single (' '), double (" "), or triple quotes (''' ''') to define strings.

Signup and view all the flashcards

Single Quotes

Single quotes are primarily used for shorter strings and can contain double quotes without escaping ('This is a "single-quoted" string.)

Signup and view all the flashcards

Double Quotes

Double quotes are primarily used for shorter strings and can contain single quotes without escaping ("This is a 'double-quoted' string.").

Signup and view all the flashcards

Triple Quotes

Triple quotes are used to define multi-line strings ('''This is a paragraph.''').

Signup and view all the flashcards

Printing Variables (Python)

Use the print() function to display the values of variables on the console.

Signup and view all the flashcards

Deleting Variables (Python)

Use the del statement to remove a variable from memory.

Signup and view all the flashcards

Tuple

An ordered, immutable sequence of items in Python. Tuples use parentheses ( ).

Signup and view all the flashcards

Tuple Immutability

Once a tuple is created, you cannot change its contents.

Signup and view all the flashcards

Dictionary

A collection of key-value pairs, where each key is unique. Use curly brackets { }

Signup and view all the flashcards

Dictionary Key

A unique identifier in a dictionary that maps to a value.

Signup and view all the flashcards

Dictionary Value

The data associated with a key in a dictionary.

Signup and view all the flashcards

Set

An unordered collection of unique items. Uses curly brackets { }

Signup and view all the flashcards

Boolean

A data type that represents one of two values: True or False.

Signup and view all the flashcards

Boolean Conversion

The bool() function converts a value to its boolean equivalent. Many values convert to False (e.g. empty strings, 0).

Signup and view all the flashcards

Implicit Conversion

Automatic type conversion that Python performs when necessary during operations.

Signup and view all the flashcards

Implicit bool to int/float

Boolean values (True/False) are automatically converted to integers (1/0) and then to floats (1.0/0.0) in operations.

Signup and view all the flashcards

Explicit int() conversion

Manually convert values to integers using the int() function.

Signup and view all the flashcards

Explicit float() conversion

Manually convert values to floating-point numbers using the float() function.

Signup and view all the flashcards

Explicit str() conversion

Manually convert values to strings using the str() function.

Signup and view all the flashcards

int(string) base

Converts a string representation of a number to an integer. Can specify the number base (e.g., binary, octal, hexadecimal).

Signup and view all the flashcards

Converting sequences to lists

Use the list() function to convert strings or tuples into lists.

Signup and view all the flashcards

Type Conversion Error

An error that occurs when trying to convert a value to a different type that is not supported or possible(like converting "hello" to a number).

Signup and view all the flashcards

Variable Deletion

Deleting a variable removes it from the memory, making it unavailable for further use.

Signup and view all the flashcards

NameError

A Python error raised when trying to use a variable that has been deleted or never defined.

Signup and view all the flashcards

Type Function

A built-in Python function (type()) that returns the data type of a variable.

Signup and view all the flashcards

Integer (int)

A whole number (positive, negative, or zero).

Signup and view all the flashcards

Boolean (bool)

A data type representing True or False values.

Signup and view all the flashcards

Float (float)

A number with a decimal point (e.g., 3.14, -2.5).

Signup and view all the flashcards

Complex Number (complex)

A number with a real and imaginary part (e.g., 2+3j).

Signup and view all the flashcards

String

A sequence of characters enclosed in quotes (single or double).

Signup and view all the flashcards

String Slicing

Extracting a portion of a string using indexing ([ ] and [:]).

Signup and view all the flashcards

String Concatenation

Joining two or more strings together using the '+' operator.

Signup and view all the flashcards

String Repetition

Repeating a string using the '*' operator.

Signup and view all the flashcards

List

An ordered, mutable collection of items of different data types.

Signup and view all the flashcards

List Indexing

Accessing list elements using numerical positions (indexes).

Signup and view all the flashcards

List Slicing

Extracting portions of a list using index ranges ([ ]and [:])

Signup and view all the flashcards

List Concatenation

Joining two or more lists together using the '+' operator.

Signup and view all the flashcards

Tuple

An ordered, immutable collection of items.

Signup and view all the flashcards

Study Notes

Programming by Python - Lecture 2

  • Topics covered in lecture 2 include Python variable creation and deletion, and data types and casting in Python.
  • Python accepts single, double, and triple quotes for string literals.
  • Single and double quotes are used for short strings.
  • Single quotes can contain double quotes without escaping.
  • Double quotes can contain single quotes without escaping.
  • Triple quotes span strings across multiple lines.

Creating Python Variables

  • Python creates a variable automatically when you assign a value.
  • The '=' sign assigns values to variables.
  • Variable declaration: Variable name = Value
  • Multiple assignments are allowed.
  • Combined assignments are allowed, separating variable names on the left and values on the right with commas.

Printing Python Variables

  • Use the print() command.
  • Example: print(x), print(y), print(name), print(x, y, name).

Deleting Python Variables

  • The del statement deletes references to number objects.
  • Example: x = 100, print(x), del x, print(x).

Type of Variable

  • Use type() to determine a variable's data type.
  • Example: x = "Zara", y = 10, z = 10.10, print(type(x)), print(type(y)), print(type(z))
    • Output: <class 'str'>, <class 'int'>, <class 'float'>.

Python Data Types

  • Python data types include:
    • Number: Integer, Float, Boolean, Complex
    • Sequence: String, List, Tuple
    • Set
    • Dictionary

Sequence Data Types - String

  • Strings cannot be modified, you can only concatenate and slice.
  • Use slicing ([ ] or [:]) to get substrings, starting from 0 (first character); last character using -1.
  • Concatenation (+) combines strings.
  • Repetition (*) repeats a string.
  • Examples:
    • str = 'Hello World!', print(str)
    • print(str[0]), print(str[2:5]), print(str[2:]), print(str * 2), print(str + "TEST")

Sequence Data Types - List

  • Lists are mutable (changeable) and store ordered collections of data.
  • Lists use square brackets ([]).
  • Elements are separated by commas.
  • Elements can be of different types.
  • Examples:
    • list = ['a', 786, 2.23, 'b', 70.2], print(list), print(list[0]), print(list[1:3]), print(list[2:]), print(tinylist * 2), print(list + tinylist).

Sequence Data Types - Tuple

  • Tuples are immutable, meaning you cannot change them after creation.
  • Tuples use parentheses ().
  • Elements are separated by commas.
  • Example: tuple = ('a', 7, 2.2, 'b')
    • Accessing elements works like a list: tuple[0], tuple[2]

Dictionary Data Types

  • Dictionaries store key-value pairs.
  • Use curly braces {}.
  • Key and value are separated by a colon :
  • Keys must be immutable (string, number, tuple)
  • Example: dict = {}, dict['one'] = "This is noha", dict[2] = "This is Yusef", print(dict['one']), print(dict2), print(dict2.keys()), print(dict2.values()).

Set Data Type

  • Sets are unordered collections of unique elements.
  • Use curly braces {}.
  • Elements are separated by commas
  • No repeated elements.
  • Example: student_id = {1, 2, 3, 4, 5}, print('Student ID:', student_id), vowels = {'a', 'e', 'i', 'o', 'u'}, print('Vowel Letters:', vowels), mixed_set = {'Hello', 1, -2, 'Bye'}, print('Set of mixed data types:', mixed_set).

Boolean Data Type

  • Represents True or False.
  • bool() function evaluates expressions/values.
  • True is equivalent to 1, False is equivalent to 0.

Data Types Casting

  • Implicit: Automatic type conversion, e.g., operating on integers and floats.
    • True is treated as 1, and False as 0.
  • Explicit: Manual type conversion using functions like int(), float(), str().
    • Examples include int("100"), float("9.99"), str(10).
    • Note potential errors with explicit casting, e.g. conversion of strings that aren't valid numeric values.
  • Special case conversions: Converting between binary, octal, and hexadecimal numbers to decimal.

Sequence Type Casting

  • Convert strings and tuples to lists using list() function.

Studying That Suits You

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

Quiz Team

Related Documents

Description

This quiz covers key concepts from Lecture 2 on Python, focusing on variable creation, deletion, and handling data types and casting. It discusses the use of quotes for string literals and the syntax for printing variables. Assess your understanding of these foundational programming skills.

More Like This

Python Data Types and Variables Quiz
32 questions

Python Data Types and Variables Quiz

IndividualizedScandium4508 avatar
IndividualizedScandium4508
Python Programming Fundamentals
10 questions
Python Programming Basics
5 questions

Python Programming Basics

PopularCalifornium avatar
PopularCalifornium
Use Quizgecko on...
Browser
Browser