Python 3: Fundamental Concepts of Programming
63 Questions
27 Views

Python 3: Fundamental Concepts of Programming

Created by
@ProminentBowenite4083

Questions and Answers

What is a literal in programming?

  • An object created from a class
  • A specific realization of a program
  • A block of code that can be reused
  • A notation for representing a fixed value (correct)
  • Python is an object-oriented programming language.

    True

    What is the purpose of functions in programming?

    Functions encapsulate a block of code that can be reused and called multiple times within a program, promoting code organization, readability, and reusability.

    In Python, indentation is used to indicate a __________ of code.

    <p>block</p> Signup and view all the answers

    Match the following data types with their descriptions:

    <p>int() = Converts a value to an integer float() = Converts a value to a floating point number str() = Converts a value to a string</p> Signup and view all the answers

    What does the 'input()' function do in Python?

    <p>To take user input from the console during runtime</p> Signup and view all the answers

    How can user input be type-casted to a different data type in Python?

    <p>By using type casting functions</p> Signup and view all the answers

    Which data structures can be used to assign multiple values to a single variable in Python?

    <p>All of the above</p> Signup and view all the answers

    To find the number of items in a list, which function is used in Python?

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

    In Python, the '==' operator is used to check if two values are equal.

    <p>True</p> Signup and view all the answers

    What is the purpose of the 'break' statement in Python?

    <p>To terminate the loop it is in</p> Signup and view all the answers

    Import the reduce function from which library in Python?

    <p>functools</p> Signup and view all the answers

    Which operator is used for formatting a set of variables in Python strings?

    <p>%</p> Signup and view all the answers

    What is the placeholder for formatted floating point numbers in Python's string formatting?

    <p>%f</p> Signup and view all the answers

    Match the following string formatting arguments with their meanings:

    <p>%s = String %d = Integers %f = Floating point numbers</p> Signup and view all the answers

    Python 3.6 introduced formatted string literals prefixed with 'f'.

    <p>True</p> Signup and view all the answers

    Which data types are included in Python's standard data types?

    <p>All of the above</p> Signup and view all the answers

    What are the three numerical types supported by Python?

    <p>int, float, complex</p> Signup and view all the answers

    Which escape sequence is used to escape single quotes in Python strings?

    <p>'</p> Signup and view all the answers

    The + operator is used for string concatenation in Python.

    <p>True</p> Signup and view all the answers

    What method is used to convert a string to uppercase in Python?

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

    Which method is used to join the elements of an iterable to the end of a string?

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

    What are some special attributes in Python classes?

    <p><strong>doc</strong>, <strong>name</strong>, <strong>dict</strong></p> Signup and view all the answers

    What is the purpose of a constructor in Python classes?

    <p>To initialize variables when a new object of the class is instantiated</p> Signup and view all the answers

    Which symbol is used in Python for overloading arithmetic addition?

    <ul> <li></li> </ul> Signup and view all the answers

    Python supports method overloading by default.

    <p>False</p> Signup and view all the answers

    Match the operator with its corresponding method for overloading in Python:

    <p>Addition = <strong>add</strong> Multiplication = <strong>mul</strong> Comparison (Less than) = <strong>lt</strong></p> Signup and view all the answers

    What is encapsulation in Python and how is it achieved?

    <p>Encapsulation restricts access to methods and variables; achieved by denoting private attributes with underscore prefix.</p> Signup and view all the answers

    What is the purpose of super() in Python classes?

    <p>To invoke methods or constructors of the parent class</p> Signup and view all the answers

    What will be printed when executing the following code:

    fruits = ['apple', 'banana', 'cherry'] print(fruits)

    <p>['apple', 'banana', 'cherry']</p> Signup and view all the answers

    What method is used to add the element 'orange' to the end of a list?

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

    Tuples are changeable in Python.

    <p>False</p> Signup and view all the answers

    What is the keyword used in Python to remove the specified index from a list?

    <p>del</p> Signup and view all the answers

    A set in Python is a collection which is ____________ and ____________.

    <p>unordered and unindexed</p> Signup and view all the answers

    Match the following Set methods with their descriptions:

    <p>copy() = Returns a copy of the set difference() = Difference between two or more sets clear() = Removes all elements from the set union() = Returns a set containing the union of sets</p> Signup and view all the answers

    What does OOP stand for in Python?

    <p>Object-Oriented Programming</p> Signup and view all the answers

    During which object creation is the Credit_Card init method called?

    <p>Payment object creation</p> Signup and view all the answers

    Which classes is the Payment class inherited from?

    <p>Both Credit_Card and Debit_Card</p> Signup and view all the answers

    In Python, __________ is the ability to use a common interface for multiple data types.

    <p>Polymorphism</p> Signup and view all the answers

    Python allows the overriding of methods in child classes inherited from parent classes.

    <p>True</p> Signup and view all the answers

    Match the following programming concepts with their descriptions:

    <p>Iterator = An object that contains a countable number of values Generator = A function that returns an iterator and can be iterated over Decorator = A function that augments the work of another function</p> Signup and view all the answers

    What is the purpose of a decorator in Python?

    <p>A decorator is used to modify or extend the behavior of functions or methods without changing their source code.</p> Signup and view all the answers

    In Python, methods are functions that expect their first parameter to be a reference to the current ______.

    <p>object</p> Signup and view all the answers

    What are the different modes for opening a file in Python?

    <p>Read</p> Signup and view all the answers

    The 'with' statement in Python simplifies exception handling and automatically closes the file.

    <p>True</p> Signup and view all the answers

    What is the purpose of a Python package?

    <p>A Python package is used to organize modules into a directory hierarchy.</p> Signup and view all the answers

    Match the following with their purpose: ['main', 'models', 'services', 'controllers']

    <p>Main = Root folder Models = Contain data structure classes Services = Business logic operations Controllers = Handle user input and interaction</p> Signup and view all the answers

    What does the os module provide in Python?

    <p>functions for interacting with the operating system</p> Signup and view all the answers

    Which module in Python provides tools for mathematical operations on real and complex numbers?

    <p>math and cmath</p> Signup and view all the answers

    What does the os.getcwd() function in Python return?

    <p>current working directory</p> Signup and view all the answers

    A file old.txt can be renamed to new.txt using the function os.rename('old.txt', ______).

    <p>new.txt</p> Signup and view all the answers

    The os.mkdir() method requires the full path of the new directory to be specified. (True/False)

    <p>False</p> Signup and view all the answers

    Match the OS module function with its description:

    <p>os.listdir() = Get all files and subdirectories inside a directory. os.rmdir() = Remove the empty directory. os.getlogin() = Get the user who has logged into the operating system. os.rename() = Renaming a directory or file.</p> Signup and view all the answers

    What will be printed after running the code to generate prime numbers between 1 to 100?

    <p>number + ' is a prime number'</p> Signup and view all the answers

    What statement is printed after 'Banana' in the first code snippet using for statement with break? - Banana gets printed and then exit the loop:

    <p>fruits = ['apple', 'banana', 'cherry'] for x in fruits: if x == 'banana': break</p> Signup and view all the answers

    The continue statement is used to terminate the loop entirely.

    <p>False</p> Signup and view all the answers

    What do list comprehensions in Python do?

    <p>Generate lists using an internal for loop</p> Signup and view all the answers

    How can you iterate through multiple lists in a list comprehension?

    <p>[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]</p> Signup and view all the answers

    What is the syntax for defining a function in Python?

    <p>def functionname( parameters ): function_suite return [expression]</p> Signup and view all the answers

    Default arguments in Python assume a value if not provided in the function call.

    <p>True</p> Signup and view all the answers

    What is the purpose of variable-length arguments in Python functions?

    <p>To handle more arguments than specified in the function definition</p> Signup and view all the answers

    What is the advantage of using lambda functions in Python?

    <p>They are used as arguments to higher-order functions</p> Signup and view all the answers

    How is the lambda function used inside the map() function in Python?

    <p>r = map(func, seq)</p> Signup and view all the answers

    Study Notes

    Fundamentals of Programming

    • Programming involves using variables to store and manipulate data, and operators to perform actions on that data.
    • Constant values stored in variables are referred to as Literals.
    • Decision making is a crucial part of programming logic, typically occurring after data handling and before implementing algorithms or executing actions based on conditions.
    • Looping is another fundamental concept in programming, enabling efficient and flexible execution of code, making it an indispensable tool for developers.

    Functions in Programming

    • Functions encapsulate a block of code that can be reused and called multiple times within a program, promoting code organization, readability, and reusability.
    • Functions help break down complex tasks into smaller, more manageable pieces, enhancing modularity and maintainability.
    • Additionally, functions allow for parameterization, enabling customization and flexibility in code execution.

    Introduction to Python Programming

    • Python is a general-purpose, interpreted, interactive, object-oriented, and high-level programming language.
    • Python was created by Guido van Rossum during 1985-1990.
    • Python source code is available under the GNU General Public License (GPL).
    • Python is designed to be highly readable, using English keywords frequently, and having fewer syntactical constructions than other languages.
    • Python is a great language for beginner-level programmers.

    Features of Python

    • Easy-to-learn: few keywords, simple structure, and clearly defined syntax.
    • Easy-to-read: Python code is more clearly defined and visible.
    • Easy-to-maintain: Python's source code is fairly easy to maintain.
    • A broad standard library: Python's library is extensive and highly portable, compatible with UNIX, Windows, and Macintosh platforms.
    • Interactive Mode: Python supports interactive testing and debugging of code snippets.
    • Portable: Python can run on a wide variety of hardware platforms and maintains the same interface across all platforms.
    • Extendable: Programmers can add low-level modules to the Python interpreter, enabling them to enhance or customize their tools for greater efficiency.
    • Databases: Python provides interfaces to all major databases.
    • GUI Programming: Python supports the creation and porting of GUI applications to various system calls, libraries, and windows systems, including Windows MFC, Macintosh, and the X Window system of Unix.
    • Scalable: Python offers better structure and support for large programs compared to shell scripting.

    Python Installation and Setup

    • Open a web browser and go to https://www.python.org/downloads/.
    • Follow the link to download the Windows installer, named python-XYZ.exe, where XYZ is the version required for installation.
    • Save the installer file to the local machine and then run it.
    • This will launch the Python installation wizard, which is easy to use.
    • Check the box labeled "Add to Path".
    • Simply accept the default settings, wait until the installation is finished, and it is done.
    • To verify if Python is installed on a Windows PC, run the following in the Command Prompt: python --version.

    Python Syntax

    • Indentations and Comments:
      • Indentations are important in Python, used to indicate a block of code.
      • Comments start with a #, and Python will render the rest of the line as a comment.
    • Suites:
      • A group of individual statements that form a single code block are called suites in Python.
      • Compound statements, such as if, while, def, and class, require a header line and a suite.
    • Semicolons:
      • The semicolon (;) allows multiple statements on a single line, provided that neither statement starts a new code block.

    Variables and Literals

    • Literals:
      • A notation for representing a fixed value in Python.
      • Examples: 5 is a numeric literal, and "hello" is a string literal.
      • Types of literals: numeric, string, boolean, and None.
    • Variables:
      • A variable is created the moment you first assign a value to it.
      • A variable name must start with a letter or the underscore character, and can only contain alphanumeric characters and underscores.
      • Variable names are case-sensitive.

    Printing Output

    • The Python "print" function is often used to output variables.
    • To combine both text and a variable, Python uses the "+" character, which is called string concatenation.

    Data Types and Casting

    • Python is dynamically typed, meaning the data type of a variable is determined by the type of value it currently holds.
    • Variables can have different data types during the execution of the program.
    • Type casting functions: int(), float(), str(), bool().

    Input and Output

    • The "input" function is used to take user input from the console during runtime.
    • Input provided by the user is always treated as a string.
    • Type casting functions can be used to convert input to other data types.

    Operators

    • Arithmetic Operators:
      • Addition, subtraction, multiplication, division, modulus, exponentiation, floor division.
    • Assignment Operators:
      • Addition assignment, subtraction assignment, multiplication assignment, division assignment, modulus assignment, floor division assignment, exponentiation assignment.
    • Comparison Operators:
      • Equal to, not equal to, greater than, less than, greater than or equal to, less than or equal to.
    • Logical Operators:
      • And, or, not.
    • Bitwise Operators:
      • And, or, xor, not, signed right shift, unsigned right shift.
    • Bitwise Assignment Operators:
      • And assignment, or assignment, xor assignment, signed right shift assignment, unsigned right shift assignment.

    Conditional Statements

    • If Statement:
      • An "if statement" is written by using the if keyword, followed by a condition, and then a block of code that executes if the condition evaluates to true.
    • If Else Statement:
      • An "else" statement in Python can be combined with an if statement to provide an alternative block of code that executes when the conditional expression in the if statement resolves to "False".
    • Nested If Statement:
      • In Python, you can nest if statements inside other if statements to create more complex conditional logic.

    Let me know if this meets your requirements!### Introduction to Python

    • Python is a programming language that has various standard data types
    • These data types define the operations possible on them and the storage method for each of them

    Standard Data Types in Python

    • There are six standard data types in Python:
      • Numbers:
        • Integers (int)
        • Floating point numbers (float)
        • Complex numbers (complex)
      • String: a sequence of characters (str)
      • List: an ordered collection of items that can be of any data type, including strings, integers, and other lists (list)
      • Tuple: an ordered, immutable collection of items that can be of any data type (tuple)
      • Set: an unordered collection of unique items that can be of any data type (set)
      • Other: Boolean (bool), Dictionary (dict), NoneType (None)

    Note: The last point "Other" is an additional category to cover other standard data types not directly mentioned in the original text.### Numbers

    • Number data types store numeric values and are created when a value is assigned to a variable.
    • There are three numerical types in Python: int (signed integers), float (floating point real values), and complex (complex numbers).
    • Python 2 has an additional type, long (long integers, can be represented in octal and hexadecimal), which has been removed in Python 3.

    Examples of Numbers

    • Examples of int: 10, 100, -786
    • Examples of float: 0.0, 15.20, -21.9, 70.2e-12
    • Examples of complex: 3+14j, 45j, -67+15j, 101+15j

    String

    • Strings can be enclosed in single quotes or double quotes.
    • Strings can be printed as raw strings by adding an r before the string.
    • Multiline strings are enclosed with triple-quotes """… """ or '''…'''.
    • Strings can be concatenated with the + operator and repeated with the * operator.
    • Two or more string literals next to each other are automatically concatenated.

    Accessing String Characters

    • Strings are arrays of characters, and individual characters can be accessed using indexing.
    • Indexing starts from 0, and negative indices can be used to access characters from the end.
    • A range of characters can be accessed using slicing.

    String Methods

    • There are various string methods, including:
      • capitalize(): Converts the first character to upper case.
      • casefold(): Converts string into lower case.
      • center(): Returns a centered string.
      • count(): Returns the number of times a specified value occurs in a string.
      • encode(): Returns an encoded version of the string.
      • etc.

    Python Casting

    • Casting in Python is done using constructor functions.
    • The int() function constructs an integer number from an integer literal, a float literal, or a string literal.
    • The float() function constructs a float number from an integer literal, a float literal, or a string literal.
    • The str() function constructs a string from a wide variety of data types.

    List

    • A list is a collection which is ordered and changeable.
    • Lists are written with square brackets.
    • Lists can be accessed, changed, and looped through.
    • List methods include:
      • append(): Adds an element to the end of the list.
      • insert(): Inserts an element at a specified position.
      • remove(): Removes an element with a specified value.
      • pop(): Removes an element at a specified position.
      • sort(): Sorts the list.

    Tuple

    • A tuple is a collection which is ordered and unchangeable.
    • Tuples are written with round brackets.
    • Tuples can be accessed, but not changed or looped through.
    • Tuple methods include:
      • count(): Returns the number of elements with the specified value.
      • index(): Returns the index of the first element with the specified value.

    Set

    • A set is a collection which is unordered and unindexed.
    • Sets are written with curly brackets.
    • Sets can be accessed, changed, and looped through.
    • Set methods include:
      • add(): Adds an element to the set.
      • remove(): Removes an element from the set.
      • pop(): Removes an element from the set.
      • clear(): Empties the set.
      • union(): Returns a set with the union of sets.
      • intersection(): Returns a set with the intersection of sets.

    Dictionary

    • A dictionary is a collection which is unordered, changeable, and indexed.
    • Dictionaries are written with curly brackets.
    • Dictionaries have keys and values, and can be accessed, changed, and looped through.
    • Dictionary methods include:
      • get(): Returns the value of a specified key.
      • update(): Updates the dictionary with the specified key-value pairs.
      • pop(): Removes an element with a specified key.
      • clear(): Empties the dictionary.

    Object-Oriented Programming

    • Object-oriented programming (OOP) in Python structures programs around objects.
    • Objects have properties and behaviors.
    • Classes are used to create user-defined data structures with attributes such as class variables and class methods.

    Class

    • A class is a blueprint for creating objects.
    • Classes have public and private class variables and methods.
    • Public class variables and methods can be accessed directly, while private class variables and methods can be accessed through public methods.

    Studying That Suits You

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

    Quiz Team

    Description

    This quiz covers the basics of programming in Python 3, including variables, data manipulation, operators, and decision making. Understand how to store and use literal values in programming logic.

    More Quizzes Like This

    Use Quizgecko on...
    Browser
    Browser