Network Prog Ch 3: Python Control Flow Basics
59 Questions
2 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 does the 'elif' statement do in an if-else block?

  • It can only be used once in a block.
  • It replaces the standard if statement.
  • It allows for additional conditions to be checked. (correct)
  • It terminates the if-else block.

What will the output be if 'a' equals 0 in the nested if statement?

  • 'zero!' (correct)
  • 'negative!'
  • No output will be generated.
  • 'positive!'

How is code grouped within control flow statements in Python?

  • By indentation (correct)
  • By semicolons
  • By parentheses
  • By curly braces

What happens if multiple conditions are True in an if-else block?

<p>Only the first True condition's block will execute. (A)</p> Signup and view all the answers

Which of the following is NOT a comparison operator in Python?

<p>&amp;&amp; (D)</p> Signup and view all the answers

What is the role of indentation in an if-else statement?

<p>It determines the block of code executed. (B)</p> Signup and view all the answers

What will be printed if 'a' is 5, 'b' is 3, and 'c' is 4 in the largest number finding code?

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

Which statement correctly describes the purpose of control flow in programming?

<p>To make decisions based on conditions. (C)</p> Signup and view all the answers

What does SOCK_STREAM indicate in Python networking?

<p>It is a connection-oriented TCP protocol. (B)</p> Signup and view all the answers

How can you display the user manual for a module in Python?

<p>By using the help function: 'help(modulename)' (B)</p> Signup and view all the answers

What do the parameters 'num' and 'denom' represent in the Fraction class?

<p>The top and bottom parts of a fraction (D)</p> Signup and view all the answers

What is the purpose of the name variable in Python?

<p>It shows the name of the current module or script. (B)</p> Signup and view all the answers

What will the output be when running a Python script directly from the command line?

<p>The variable <strong>name</strong> will be set to <strong>main</strong>. (A)</p> Signup and view all the answers

What will the output of the command 'print(b.inverse())' be if b is defined as 'Fraction(3,4)'?

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

What method would you use to get a float value of a Fraction object?

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

What is the first step to create a user-defined module in Python?

<p>Create a new Python script with function definitions. (B)</p> Signup and view all the answers

How do you call a function from a user-defined module?

<p>Using dot notation after importing the module. (C)</p> Signup and view all the answers

How is a new Fraction object created when adding two fractions together?

<p>By adding the numerators and multiplying the denominators (D)</p> Signup and view all the answers

In Python, what happens when a file is imported as a module?

<p>The <strong>name</strong> variable is assigned the file name. (D)</p> Signup and view all the answers

If Fraction a is defined as 'Fraction(1, 4)' and Fraction b as 'Fraction(3, 4)', what will be the value of c after 'c = a + b'?

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

What does the method str return in the Fraction class?

<p>A string representation of the fraction (A)</p> Signup and view all the answers

What is required to utilize the help() function for a module?

<p>The module must be successfully imported first. (C)</p> Signup and view all the answers

Which of the following methods has not been implemented in the Fraction class?

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

What is the internal representation of a fraction in the Fraction class?

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

What happens to the argument passed into the function in Python?

<p>A copy of the value is passed to the function. (D)</p> Signup and view all the answers

Which keyword is necessary to modify a global variable within a function?

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

What is the main disadvantage of using global variables?

<p>They make code less independent and portable. (C)</p> Signup and view all the answers

What will be the output of this code segment if name is originally 'Ahmad'? name = 'Ahmad' def showname(): global name name = 'Ali'?

<p>'Ahmad' and 'Ali' (A)</p> Signup and view all the answers

In the string_test function, how is the number of UPPER_CASE letters counted?

<p>By using the isupper() method. (A)</p> Signup and view all the answers

What will the function string_test return when the input string is 'Hello World'?

<p>2 uppercase, 8 lowercase. (B)</p> Signup and view all the answers

What is the output of the print statement in the change_me function after v is assigned 10?

<p>argument is now: 10 (B)</p> Signup and view all the answers

Which type of variable can only be accessed within its defining function?

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

If a variable is defined outside of any functions, what type is it considered?

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

How should the string_test function terminate its input loop?

<p>When 'quit' is entered by the user. (A)</p> Signup and view all the answers

What are data attributes in a class?

<p>Objects that belong to the class and are initialized in the constructor (C)</p> Signup and view all the answers

Which operator is used to access attributes of an object in a class?

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

When defining a method in a class, what is the first argument that is automatically passed?

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

What does the init method do in a class?

<p>Initializes data attributes of the class's instance (C)</p> Signup and view all the answers

How would you define a distance method in the Coordinate class?

<p>Use the Pythagorean theorem to compute the distance (C)</p> Signup and view all the answers

What is the purpose of the str method in a class?

<p>To override the print functionality for class objects (A)</p> Signup and view all the answers

How can special operators be defined for a class?

<p>Using double underscores before and after the operator (D)</p> Signup and view all the answers

Which of the following correctly initializes a Coordinate object at the origin?

<p>c = Coordinate(0, 0) (D)</p> Signup and view all the answers

What would be the result of accessing x attribute of a Coordinate object initialized with 2 and 3?

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

What will happen if you attempt to print a Coordinate object without a defined str method?

<p>It will show an uninformative representation (B)</p> Signup and view all the answers

What is the primary purpose of dividing code into functions?

<p>To keep code organized and reusable (B)</p> Signup and view all the answers

Which of the following is NOT a characteristic of a function?

<p>It must have at least one parameter (D)</p> Signup and view all the answers

What happens when a function is called?

<p>Control transfers to the function being called (A)</p> Signup and view all the answers

What is the correct way to define a function that checks if a number is even?

<p>function is_even(i): return i % 2 == 0 (D)</p> Signup and view all the answers

Which of the following statements about variable scope is accurate?

<p>Each function call creates a new scope (B)</p> Signup and view all the answers

What does Python return if no return statement is provided in a function?

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

What distinguishes a return statement from a print statement within a function?

<p>Return statements provide a value to the caller while print does not (A)</p> Signup and view all the answers

When defining a function, which character must the function name start with?

<p>An uppercase or lowercase letter or an underscore (C)</p> Signup and view all the answers

What is the primary use of parameters in function definitions?

<p>To allow functions to take inputs (C)</p> Signup and view all the answers

If you want to call a function named 'calculate_area' with the parameters length and width, how would you do it?

<p>calculate_area(length, width); (C)</p> Signup and view all the answers

What will be the output of the function is_even(3) if defined to return True for even numbers?

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

How does Python interpret the function return statement?

<p>By passing a value back to the caller (C)</p> Signup and view all the answers

In the statement 'print(sum(100, 90, 90))', what is the expected output?

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

What does the function 'hello()' do as defined in the example?

<p>Prints a greeting message to the console (A)</p> Signup and view all the answers

What will the output for the following code be? 'x = is_even(3); print(x)'

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

Flashcards

If-Else Statement

A fundamental control flow structure that allows code execution to branch based on a conditional expression. It evaluates a condition and executes different blocks of code depending on whether the condition is true or false.

Indentation in Python

Indentation is crucial in Python, as it defines code blocks and their relationship to control flow structures. Code within the same indentation level belongs to the same block, while different indentation levels indicate different blocks.

Elif Statement

Used in conjunction with if and else statements, elif allows for multiple conditions to be evaluated sequentially. If the previous if or elif condition is false, elif checks its own condition, executing the corresponding block if true.

Nested If Statements

A nested if statement is an if statement that is inside another if statement. This allows for multiple levels of decision-making within a program.

Signup and view all the flashcards

Comparison Operators

Used to compare values in Python, resulting in a Boolean value (True or False). Examples include '>' (greater than), '<' (less than), '==' (equal to), '!=' (not equal to), '>=' (greater than or equal to), and '<=' (less than or equal to).

Signup and view all the flashcards

Finding the Largest Number

Involves comparing multiple values using comparison operators and conditional statements to determine the largest value among them. This requires careful logic to handle various scenarios where multiple values could share the largest value or if all values are equal.

Signup and view all the flashcards

SOCK_STREAM

Indicates a connection-oriented TCP protocol, meaning data is reliably transmitted in order.

Signup and view all the flashcards

help() function

A built-in Python function used to display the documentation (user manual) for a module.

Signup and view all the flashcards

User-Defined Modules

Custom Python scripts that contain functions, classes, and variables, allowing code reuse and organization.

Signup and view all the flashcards

Importing Modules

The process of loading a module's content into your current script to use its functions or variables.

Signup and view all the flashcards

name Variable

A special built-in Python variable holding the name of the current module or script being executed.

Signup and view all the flashcards

Running as a Script

Executing a Python file directly from the command line, where the name variable is set to 'main'.

Signup and view all the flashcards

Running as a Module

Importing a Python file (module) into another Python program, where the name variable is set to the module's filename (without .py).

Signup and view all the flashcards

main() Function Convention

Python uses the name variable to determine the entry point of a script. The code block under if __name__ == '__main__': is executed only when the script is run directly, not when imported.

Signup and view all the flashcards

Passing by Value

A function receives a copy of the data passed as an argument, not the original variable itself.

Signup and view all the flashcards

One-Way Communication

Passing by value allows data to be sent into a function, but the function cannot modify the original variable.

Signup and view all the flashcards

Local Variable

A variable declared inside a function, accessible only within that function (its scope).

Signup and view all the flashcards

Global Variable

A variable declared outside any function, accessible from anywhere in the program.

Signup and view all the flashcards

Accessing a Global Variable Within a Function

To modify a global variable inside a function, you need to use the 'global' keyword.

Signup and view all the flashcards

Global Variable Impact on Debugging

Excessive use of global variables can make debugging harder, as their values can be changed from anywhere in the code.

Signup and view all the flashcards

Global Variable Impact on Portability

Functions using global variables are less portable because they depend on those variables' specific values.

Signup and view all the flashcards

Function string_test

Takes a string as input, counts uppercase and lowercase letters within it, and prints the information.

Signup and view all the flashcards

Function string_test Mechanism

The 'string_test' function iterates through each character in the string, checking if it's upper or lowercase using 'isupper()' and 'islower()', and updating a dictionary to count occurrences.

Signup and view all the flashcards

Function string_test Usage

The code continuously receives a string from the user, calls 'string_test' to analyze it, and stops when the user enters 'quit'.

Signup and view all the flashcards

What is the internal representation of a Fraction object?

A Fraction object in Python is represented internally using two integers, the numerator and the denominator.

Signup and view all the flashcards

How do you create a new Fraction object?

You create a new Fraction object using the Fraction class with the __init__ method. It takes two integers, the numerator and denominator, as arguments. For example, Fraction(3, 4) creates a fraction representing 3/4.

Signup and view all the flashcards

str method

The __str__ method provides a string representation of the object, making the object printable and easier to understand when displayed.

Signup and view all the flashcards

What does add method do?

The __add__ method defines how two Fraction objects are added together. It returns a new Fraction object representing the sum of the two operands. It calculates the numerator and denominator of the sum, ensures they are properly combined, and returns a new Fraction object.

Signup and view all the flashcards

What does sub method do?

The __sub__ method defines the subtraction operation for Fraction objects. Like __add__, it returns a new Fraction object representing the difference of two Fraction objects.

Signup and view all the flashcards

What does float method do?

The __float__ method allows you to convert a Fraction object to a floating-point number. It divides the numerator by the denominator internally and returns the result as a float.

Signup and view all the flashcards

What does inverse method do?

The inverse method calculates the reciprocal of a Fraction object. It creates a new Fraction object with the denominator as the numerator and numerator as the denominator, effectively inverting the original fraction.

Signup and view all the flashcards

Python class

A Python class serves as a blueprint for creating objects. They define the attributes (data) and methods (functions) that objects of that class will have.

Signup and view all the flashcards

Class Attributes

Data and procedures that belong to a class. They define the structure and behavior of objects created from that class.

Signup and view all the flashcards

Data Attributes

Variables that hold data specific to an object. They represent the object's state or properties.

Signup and view all the flashcards

Methods (Procedural Attributes)

Functions that operate on objects of a specific class. They define the object's actions or behaviors.

Signup and view all the flashcards

How to Create a Class Instance

To create an instance of a class, call the class name like a function, passing in any required arguments.

Signup and view all the flashcards

init Method

A special method used to initialize an object's data attributes when an instance is created.

Signup and view all the flashcards

Instance Variables

Variables that hold data specific to an individual instance of a class.

Signup and view all the flashcards

What is a Method?

A function that is part of a class and operates on objects of that class. It defines behaviors specific to the class.

Signup and view all the flashcards

Self Argument in Methods

The first argument of a method, representing the object itself. It's automatically passed by Python.

Signup and view all the flashcards

'. (Dot)' Operator for Accessing Attributes

Used to access both data attributes and methods of an object.

Signup and view all the flashcards

What are functions in programming?

Functions in programming are self-contained blocks of code designed to perform specific tasks. They are reusable, help organize code, and make it easier to debug and maintain.

Signup and view all the flashcards

Why are functions used?

Functions promote code reusability, enhance organization, improve readability, and simplify debugging by breaking down complex tasks into manageable units.

Signup and view all the flashcards

What happens when a function is called?

When a function is called, the program's execution temporarily jumps to the function's body. The function executes its code and then 'returns' the control back to the line after the function call.

Signup and view all the flashcards

What's the purpose of a function's 'return' statement?

The 'return' statement determines the value that the function sends back to the part of the code that called it. Without a 'return' statement, the function returns 'None' by default.

Signup and view all the flashcards

What is the difference between 'print' and 'return'?

'print' displays output on the console, while 'return' sends a value back to the caller. You can use 'print' multiple times within a function, but only one 'return' statement is executed.

Signup and view all the flashcards

What are parameters in a function?

Parameters are variables declared within the function definition that act as placeholders for values passed to the function when it's called. They specify the data the function expects.

Signup and view all the flashcards

What is the difference between formal and actual parameters?

Formal parameters are the variables listed in the function definition, while actual parameters are the values passed to the function when it's called. Formal parameters receive the values of the actual parameters.

Signup and view all the flashcards

What is a function's 'scope'?

A function's scope defines which parts of the program have access to its variables. Variables declared inside a function are local to that function and can't be accessed outside of it.

Signup and view all the flashcards

What happens to variables passed as arguments to a function?

When you pass a variable as an argument to a function, a copy of its value is created within the function's scope. Changes made to the parameter variable inside the function don't affect the original variable.

Signup and view all the flashcards

What is the flow of execution in a program with functions?

The program executes lines of code sequentially from top to bottom. When a function is called, the execution jumps to the function, executes its code, and returns to the line after the function call.

Signup and view all the flashcards

How are functions useful for modular programming?

Functions allow you to break down large programs into smaller, independent modules, each with a specific purpose. This improves code organization, reusability, and maintainability.

Signup and view all the flashcards

Can functions call other functions?

Yes, functions can call other functions. This is called function nesting and allows for more complex program structures.

Signup and view all the flashcards

What are the advantages of defining functions at the beginning of a program?

Placing function definitions at the beginning ensures that all functions are accessible throughout the program. This makes code easier to read and understand.

Signup and view all the flashcards

What is a docstring?

A docstring is a multiline string placed inside a function definition that describes its purpose, arguments, and return value. It's used for documentation.

Signup and view all the flashcards

Why are docstrings important?

Docstrings help make code more understandable and maintainable. They serve as a reference for programmers using the function, even if they didn't write it themselves.

Signup and view all the flashcards

Study Notes

Network Programming: Control Flow, Functions, and OOP in Python

  • The presentation covers network programming in Python, focusing on control flow, functions, and object-oriented programming (OOP) concepts.
  • An agenda outlines the topics to be covered, including introduction to Python, Python programming, data types, control flows, functions and modules, file handling, object-oriented programming, and relevant lab assignments.
  • If-else statements are fundamental blocks for conditional execution. The example demonstrates how the program executes based on a variable "answer" being True or False. Correct indentation is crucial for if-else statements to work as expected.
  • Conditional statements can be extended using "elif". This allows for multiple conditions to be checked. If multiple conditions are true, using elif ensures only the first True condition is executed.
  • Nesting of if-else blocks is possible for more complex conditional logic. Nested if-else allows for multiple levels of condition evaluation.
  • Indentation is essential in Python because it defines the block of code that belongs to an if-else statement. Errors can occur if indentation is not correct.
  • Combined conditions with 'and' and 'or' operators can be performed for conditional checks.
  • For loops allow for iteration over a sequence of items. This example demonstrates a loop over a list. The code calculates and prints squares of numbers with correct indentation. Another idiom for for loops with sequences is using range(len(a)).
  • While loops execute a block of code repeatedly as long as a condition remains True. Example provides a clear demonstration of while loop execution and control flow.
  • Break statement allows to exit a loop prematurely using the "break" keyword. It can be used within for or while loops to exit based on a specific condition being met.
  • While loops can be used in the context of file handling to efficiently process data sequentially as opposed to using for loops which require prior knowledge of the data size in a file.
  • For and while loops comparison - for loops are suitable when the number of iterations is known or easily calculable. For loops can be rewritten using while loops with a counter to repeat the iterations. Conversely while loops do not need the iterations to be known first. While loops are better suited when the number of iterations is unknown.
  • Control flow continue keywords. Using continue, the current iteration of a loop is skipped and the next iteration begins.
  • Control flow pass keyword. This keyword serves as a placeholder for future code and avoids errors when empty code isn't allowed in a script.

Functions

  • Functions are reusable blocks of code for performing specific tasks and enhance code organization.
  • Functions can be defined and called to reuse frequently used logic, leading to an organized and modular program layout.
  • A main() function (defined for example in the code) could be central to call other functions that do part of the work.
  • Functions are not automatically executed, they need to be called at a specific point.
  • Function structure to be followed includes function name, parameters, docstrings, body, and return statement with appropriate indentation.
  • Passing parameters to functions. A function can receive data by passing parameters and variable arguments are processed, as opposed to only using local variables, for efficient code management.
  • Importance of function return statements. Return statement in a function returns a value back to the point it was called at. If not provided it automatically returns a None value, representing no value to be provided as an output of the function.
  • Flow of execution in Python. How the code structure is executed line-by-line top-to-bottom and how functions are run (called) along the execution.

Control flow continue keyword

  • The continue keyword skips the rest of the current loop iteration and proceeds to the next iteration in a loop.

Control flow pass keyword

  • The pass keyword is a no-operation statement, used as a placeholder where a statement is syntactically required but no action is needed.

Modules in Python

  • Python modules are collections of functions and other objects that can be imported to utilize their functionality in your code.
  • Built-in modules provide pre-packaged functionalities for common programming tasks.
  • User-defined modules can contain functions and variables to improve code reusability and organization. Using the import statement, you can load these modules to your current script for usage.

Files in Python

  • Files are used to store data persistently; data read from a file is mutable data that can be manipulated.
  • Programs need the ability to read and write files for tasks including data access and management.
  • Python's built-in functions allow opening and handling files including reading and writing data.

Objects in Python

  • Python is an object-oriented programming language (OOP), everything in python is considered an object.
  • Python object has an internal data representation and procedures for interacting with that object.
  • Objects in Python are instances of a data type, similar to other common programming languages.

Object-Oriented Programming (OOP)

  • OOP is a programming paradigm enabling the creation of well-structured and reusable programs.
  • In OOP, data is bundled with the functions that operate on that data, leading to more modular code and enhanced management of complex programs.
  • Classes defined in other files or modules using import can be called to perform a task.
  • The main() function in Python enables a program to execute the functions sequentially.

Special Methods

  • Methods can be used to operate over a class using special method functions in OOP.
  • These provide a mechanism to overload operators for different purposes (i.e. addition, comparison, etc.) in a user-defined class.

Global Variables

  • Global variables are defined outside of any function and accessible from any part of the program. They maintain a defined scope and help manage data that multiple parts of the program might need to access.
  • Global variable access and update. Using the global keyword, you tell the program to use a global variable, as opposed to one defined within a function. Accessing or updating a global variable in code helps when a function needs to access or change the global variable's value.

Passing Arguments to a Function

  • Python uses "pass by value." When you pass an argument to a function, a copy of the value is made, not the original variable. Thus, modifying the argument within the function does not affect the original variable.

Variable Scope

  • Variable scope determines where a variable is accessible within a program. Local variables (inside a function) are only accessible within the function, and global variables are accessible from anywhere.

Studying That Suits You

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

Quiz Team

Description

This quiz covers the fundamental concepts of control flow in Python, including the use of 'if', 'elif', and 'else' statements. Test your understanding of how conditions are evaluated and how indentation affects code execution. Gain clarity on comparison operators and nested conditions in Python.

More Like This

Use Quizgecko on...
Browser
Browser