Python Input/Output and String Formatting

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 is the correct way to use the modulo operator to format a string in Python?

  • `'Hello, %s! You are %d years old.' % ('Alice', 30)` (correct)
  • `'Hello, %name! You are %age years old.' % {name: 'Alice', age: 30}`
  • `'Hello, {name}! You are {age} years old.' % (name='Alice', age=30)`
  • `'Hello, {0}! You are {1} years old.'.format('Alice', 30)`

In Python, what is the primary purpose of comments in code?

  • To optimize the code for faster execution.
  • To be executed by the Python interpreter as instructions.
  • To define the data types of variables used in the code.
  • To provide information for human readers to understand the code. (correct)

Which of the following is NOT a valid rule for naming identifiers in Python?

  • Identifiers are case-insensitive. (correct)
  • Identifiers can be of any length.
  • Identifiers must start with a letter or an underscore.
  • Identifiers can contain letters, digits, and underscores.

What happens when you try to use a keyword as a variable name in Python?

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

In Python, what is the significance of the None type?

<p>It signifies the absence of a value. (C)</p>
Signup and view all the answers

Which of the following data types is immutable in Python?

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

What is the result of the following Python code?

x = 10
y = 3.14
z = x + y
print(z)

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

What does the term 'object sharing' or 'aliasing' refer to in Python?

<p>Having multiple variables refer to the same object in memory. (D)</p>
Signup and view all the answers

What is the purpose of the del statement in Python?

<p>To delete a variable reference, allowing memory reclamation. (C)</p>
Signup and view all the answers

Given the following code, what will be output?

a = [1, 2]
b = a
print(a is b)

Signup and view all the answers

What is the associativity of most operators in Python, and how does it affect evaluation?

<p>Left-to-right; operators are evaluated from left to right. (B)</p>
Signup and view all the answers

What makes the exponentiation operator (**) unique in terms of associativity?

<p>It has right-to-left associativity. (B)</p>
Signup and view all the answers

In Python, what are the three key attributes that every object has?

<p>Type, ID, Value (B)</p>
Signup and view all the answers

What is the difference between rebinding a variable and mutating an object in Python?

<p>Rebinding creates a new object, while mutating modifies the existing object in-place. (B)</p>
Signup and view all the answers

Given the code below, what will be the final output?

x = [1, 2, 3]
y = x
y.append(4)
print(x)

<p><code>[1, 2, 3, 4]</code> (B)</p>
Signup and view all the answers

Which of the following scenarios best illustrates the importance of understanding mutability in Python?

<p>Avoiding unexpected side effects when multiple variables refer to the same mutable object. (B)</p>
Signup and view all the answers

What is the key difference between a function and a method in Python?

<p>Methods are associated with a specific data type, while functions are not. (B)</p>
Signup and view all the answers

How do you list all available methods for a given type in Python?

<p><code>dir(typename)</code> (A)</p>
Signup and view all the answers

Which of the following statements correctly describes the use of modules and importing in Python?

<p>Modules are Python files that organize related functions and definitions, and importing makes those functions available in your program. (C)</p>
Signup and view all the answers

What is the primary role of indentation in Python code?

<p>To indicate the scope and structure of code blocks. (A)</p>
Signup and view all the answers

Flashcards

What is the input() function?

A function that takes a prompt as an argument and returns the user's input as a string.

What is Old-style String Formatting?

A method using the modulo operator (%) to format strings, similar to C's printf function.

String Formatting Method

A string formatting method where values are substituted using .format().

What are f-Strings?

Formatted string literals, indicated by 'f' before the string, where variables and expressions within curly braces are evaluated and inserted directly into the string.

Signup and view all the flashcards

What are Comments in Python?

Lines of code ignored by the Python interpreter, used for human understanding.

Signup and view all the flashcards

What are Identifiers in Python?

Names assigned to variables, functions, classes, etc., following specific rules.

Signup and view all the flashcards

What are Keywords in Python?

Reserved words with predefined meanings that cannot be used as identifiers.

Signup and view all the flashcards

What is a Variable in Python?

A named storage location that holds a value; type is automatically assigned.

Signup and view all the flashcards

What are Python's Numeric data types?

int, float, complex

Signup and view all the flashcards

What are Container Types?

Data structures that hold collections of objects.

Signup and view all the flashcards

What is a String in Python?

Sequence of characters.

Signup and view all the flashcards

What is a List in Python?

Ordered, mutable collection of items.

Signup and view all the flashcards

What is a Tuple in Python?

Ordered, immutable collection of items.

Signup and view all the flashcards

What is a Dictionary in Python?

Unordered collection of key-value pairs.

Signup and view all the flashcards

What is a Set in Python?

Unordered collection of unique items.

Signup and view all the flashcards

What is Implicit Type Conversion?

Automatic conversion of data types by Python.

Signup and view all the flashcards

What is Explicit Type Casting?

Conversion of data types using functions like int(), float(), and str().

Signup and view all the flashcards

What is the Identity of an Object?

A unique integer that identifies an object.

Signup and view all the flashcards

What is Object Sharing or Aliasing?

Assigning one variable to another creates another reference to the same object.

Signup and view all the flashcards

What is Dynamic Typing?

Python's ability to determine and change a variable's type during runtime.

Signup and view all the flashcards

Study Notes

Python Fundamentals: Input/Output

  • The input() function displays a prompt and gets user input as a string.
  • name = input("Enter your name: ") prompts the user for their name.
  • age = int(input("Enter your age: ")) prompts for age and converts the input to an integer.
  • print("Hello World") outputs a string.
  • print("and your age,", age) outputs a string and the value of the age variable.

Output Formatting in Python

  • Python has multiple string formatting methods each with unique syntax and advantages.
  • Old-style string formatting utilizes the (%) modulo operator, similar to C's printf function.
  • %s is a placeholder for strings, and %d is a placeholder for integers.
  • Values are substituted based on their order in a tuple.
  • Example:
    name = "Alice"
    age = 30
    print("Hello, %s! You are %d years old." % (name, age))
    # Output: Hello, Alice! You are 30 years old.
    
  • The string formatting method uses .format() with {} placeholders.
     name = "Bob"
     age = 25
     print("Hello, {}! You are {} years old.".format(name, age))
     # Output: Hello, Bob! You are 25 years old.
    
  • F-strings (formatted string literals) use an f before the string and evaluate variables directly inside curly braces {}.
    name = "Charlie"
    age = 35
    print(f"Hello, {name}! You are {age} years old.")
    # Output: Hello, Charlie! You are 35 years old.
    
  • Format specifiers inside curly braces customize number and string formatting.
    number = 3.14159
    formatted_number = f"Pi is approximately {number:.2f}"
    print(formatted_number)
    # Output: Pi is approximately 3.14
    
  • .2f formats the number as a floating-point number with two decimal places.
  • Other format specifiers:
    • f: Floating-point number
    • e: Scientific notation
    • %: Percentage

Comments

  • Comments are ignored by the Python interpreter.
  • Single-line comments begin with #.
  • Multi-line comments (docstrings) are enclosed in triple quotes """Docstring goes here""".
  • Comments improve code readability, facilitate maintenance, and aid in debugging.

Identifiers

  • Identifiers are names for variables, functions, classes, etc.
  • Identifiers must begin with a letter or underscore.
  • Identifiers can contain letters, digits, and underscores.
  • There is no limit to identifier length.
  • Identifiers are case-sensitive.
  • Keywords are reserved with predefined meanings and can't be identifiers.
  • Use help('keywords') to list them.
  • Avoid using built-in names as identifiers.
  • Use meaningful and descriptive identifier names.
  • Use lowercase with underscores for variables and functions, and CapWords for classes.
  • Avoid single or double leading underscores.

Variables and Data Types

  • A variable is a named storage location for a value.
  • Python automatically assigns the data type based on the assigned value, without explicit declaration.
  • Numeric types:
    • int: Integer numbers (e.g., 10, -5, 0)
    • float: Floating-point numbers (e.g., 3.14, -2.5)
    • complex: Complex numbers (e.g., 2+3j)
  • bool: Boolean (True or False)
  • None: Represents the absence of a value
  • Container types hold collections of objects.
  • Sequential Collections:
    • str: Sequence of characters (e.g., "Hello, world!")
    • list: Ordered collection of items (e.g., [1, 2, 3, "apple"])
    • tuple: Ordered, immutable collection of items (e.g., (1, 2, 3))
  • Associative Collections:
    • dict: Unordered collection of key-value pairs (e.g., { "name": "Alice", "age": 30})
    • set: Unordered collection of unique items (e.g., {1, 2, 3})

Type Conversions

  • Implicit type conversion: Python automatically converts data types when necessary.
  • Explicit type conversion (type casting): Use functions like int(), float(), and str().
    x = 10         # int
    y = float(x)   # y will be a float (10.0)
    

Object

  • Everything in Python is an object with a type, identity, and value.
  • Objects are chunks of memory used to store data.
  • Type: The kind of object (e.g., int, list).
  • Identity: A unique integer identifier for the object (memory address).
  • Value: The data stored inside the object.
  • Python stores values in objects, and variables are names that reference these objects.
  • Assigning a value to a variable binds the name to an object.
    x = 56        # x refers to an integer object with value 56
    p = 'Hello'   # p refers to a string object
    
  • Variables act as object references, storing memory locations rather than values themselves.
  • Assigning one variable to another does not copy the object, both variables point to the same object.
    z = x  # z now refers to the same object as x
    
  • All variables are bound to the same object, and any of them can be used to access it.
  • Using id(variable) confirms this.
  • Variables can be reassigned to new objects.
    x = 25    # Now x refers to a new object
    z = z + 3   # z is rebound to a new object with value 59
    y = 3.6   # y now refers to a float object
    
  • If no variable references an object, Python's garbage collector removes it.
  • Multiple assignment assigns the same value to multiple variables simultaneously.
    variable1 = variable2 = variable3 = value
    
  • Pairwise assignment assigns different values to multiple variables in a specific order.
    x, y, z = 1, 2.5, 3  # x gets 1, y gets 2.5, z gets 3
    
  • The number of variables on the left must match the number of values on the right in pairwise assignment.
  • Python is dynamically typed, variables do not have fixed types.

Deleting a Name

  • The del statement removes a variable reference.
    x = 50
    del x
    # print(x)  # This will cause an error since x no longer exists
    

Operators

  • Arithmetic operators: +, -, *, /, // (floor division), % (modulo), ** (exponentiation)
  • Result Type: / always returns a float. // returns an integer if both operands are integers, otherwise a float.
  • / preserves decimal precision, // discards the decimal part.
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: and, or, not
  • Identity: is, is not (compare object identities)
    a = [1, 2]
    b = a
    print(a is b)  # True
    
  • Membership: in, not in (check if a value is in a sequence)
    fruits = ["apple", "banana"]
    print("apple" in fruits)  # True
    

Python Operator Precedence and Associativity

  • Operator precedence dictates the order of operations:
    1. Parentheses ()
    2. Exponentiation ** (Right-to-Left)
    3. Positive, Negative, Bitwise NOT +x, -x, ~x (Right-to-Left)
    4. Multiplication, Division, Floor Division, Remainder *, /, //, % (Left-to-Right)
    5. Addition, Subtraction +, - (Left-to-Right)
    6. Bitwise Shift <<, >> (Left-to-Right)
    7. Bitwise AND & (Left-to-Right)
    8. Bitwise XOR ^ (Left-to-Right)
    9. Bitwise OR | (Left-to-Right)
    10. Membership, Identity tests, Comparisons in, not in, is, is not, <, <=, >, >=, !=, == (Left-to-Right)
    11. Boolean NOT not (Left-to-Right)
    12. Boolean AND and (Left-to-Right)
    13. Boolean OR or (Left-to-Right)
  • Associativity determines the evaluation direction when operators have the same precedence. Most operators are left-to-right.
  • The exponentiation operator ** is right-to-left.

Mutable/Immutable

  • Every Python object has a type, ID, and value.
  • Immutable Types: Value can't be changed after creation (e.g., int, float, bool, str, tuple, frozenset).
  • Mutable Types: Value can be modified in-place (e.g., lists, sets, dictionaries).
  • Mutability applies to objects, not variable names. Variables can be rebound to a new object.
  • Rebinding a variable means making it reference a new object and applies to both mutable and immutable types.
  • Example:
    a = 56  # a refers to an int object with value 56
    a = a + 3  # a now refers to a new int object with value 59
    
  • Int is immutable. a + 3 doesn't modify the original object but creates a new one.
    x = [1, 2, 3]  # 'x' refers to a list object
    x = [4, 5, 6]  # 'x' is now rebound to a new list object
    
  • When x = [4, 5, 6] is executed, a new list object is created, discarding the reference to the original.
  • Mutating an object changes the content of a mutable object in-place.
    x = [1, 2, 3]  # x refers to a list object
    x.append(4)  # The list object itself is modified
    
  • Changes to a mutable object affect all references.

Functions/Methods

  • Functions are reusable blocks of code that perform specific tasks.
  • Built-in Functions: Always available in Python (e.g., print(), input(), type(), id()).
  • Methods are functions associated with a specific data type and use dot notation.
    'hello'.upper()
    list1.append(10)
    
  • dir(typename) lists all methods for a type.
  • help(typename.methodname) provides details about a method.

Modules and Importing

  • Standard Library: Pre-written modules with functions and tools.
  • Modules: Python files that organize related functions and definitions.
  • Importing makes module functions available.
    from math import sqrt, trunc   # Imports specific functions
    sqrt(34)                        # Use functions directly
    
    import math                     # Imports the entire module
    math.sqrt(34)                   # Prefix functions with module name
    
  • help(modulename) shows module documentation.
  • dir(modulename) lists names defined in a module.

Indentation

  • Indentation defines code blocks.
  • Use the same indentation consistently, typically four spaces.
  • It enhances readability and prevents errors.

Studying That Suits You

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

Quiz Team

Related Documents

Python Fundamentals PDF

More Like This

Java String: Part 1
23 questions
Fmt Overview in Go Programming
10 questions
Python String Formatting and Operators
25 questions
Introduction to Python Programming
10 questions
Use Quizgecko on...
Browser
Browser