Python Basics
50 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

Which of the following numerical types is NOT supported in Python?

  • complex
  • long
  • float
  • decimal (correct)

What is the correct way to represent a long integer in Python, including octal and hexadecimal?

  • Appending 'L' to the integer literal, such as `0x19323L` for hexadecimal or `0122L` for octal (correct)
  • Prefixing with '0o' for octal and '0x' for hexadecimal, then casting to long
  • Using the `int()` constructor with base argument, like `int('122', 8)` for octal
  • Using a `long()` constructor, like `long(12345)`

What will be the output of the following Python code?

str = 'PYTHON PROGRAMMING' print(str[2:5])

  • YTHON
  • null
  • HTON
  • THON (correct)

Which operator is used for string concatenation in Python?

<ul> <li>(B)</li> </ul> Signup and view all the answers

What is the primary difference between single and double quotes when defining strings in Python?

<p>There is no difference; Python treats single and double quotes the same way. (C)</p> Signup and view all the answers

Given the following Python code, what will be the output?

str = 'PYTHON' print(str * 3)

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

Which command is used to execute a Python script named my_script.py from the Windows command line?

<p>python my_script.py (B)</p> Signup and view all the answers

Which of the following is a key consideration when writing interactive Python code in the command line?

<p>Ensuring statements are properly indented. (C)</p> Signup and view all the answers

In Python, how do you access the last character of a string assigned to a variable named my_string?

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

What is the purpose of Anaconda Navigator?

<p>To provide a GUI for launching Python development tools like Jupyter Notebook. (A)</p> Signup and view all the answers

What is the value of x after executing the following code?

x = 5 + 3j y = x.imag

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

When installing Anaconda, what is the significance of the option to “Add Anaconda to my PATH environment variable”?

<p>It enables running Anaconda commands from any command prompt location. (D)</p> Signup and view all the answers

Which of the following methods can be used to access Jupyter Notebook after installing Anaconda?

<p>Either through the Anaconda folder from the Start menu (Windows) or the Anaconda Navigator shortcut icon. (A)</p> Signup and view all the answers

Suppose you have two variables, x = 10 and y = 5. Which code snippet will print 'x is greater than y' when executed interactively in the Python command line?

<p><code>if x &gt; y: print('x is greater than y')</code> (A)</p> Signup and view all the answers

What happens if you try to run a Python script named 'test' without the .py extension using the command python test in the command line?

<p>The command prompt will display an error indicating the file cannot be found. (C)</p> Signup and view all the answers

What action is performed when you create a variable in Python?

<p>A section of memory is reserved to store a value. (B)</p> Signup and view all the answers

Given a = 5 and b = 2, what is the result of the expression a ** b?

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

Which operator returns the remainder of a division?

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

What is the output of the expression 15 // 4?

<p>3 (A), 3.0 (D)</p> Signup and view all the answers

If x = 10, what is the value of x after executing x %= 3?

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

What is printed by print(16 // 5)?

<p>3.0 (B), 3 (C)</p> Signup and view all the answers

If a = 4 and b = 6, what is the value of a after the operation a **= b?

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

What is the result of -17 // 5?

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

Given x = 7, what does x |= 2 do?

<p>Performs a bitwise OR operation between x and 2, assigning the result to x (D)</p> Signup and view all the answers

If y = 12, what is y //= 5?

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

Determine the value of 'result' after the following operations: a = 10 b = 3 result = a % b

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

What is the primary difference between the '==' and '!=' operators in Python?

<p>The <code>'=='</code> operator checks for equality, while <code>'!='</code> checks for inequality. (C)</p> Signup and view all the answers

Consider the following code:

x = 3 y = 7 print(x < 5 and y > 10)

What will be the output of this code?

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

Which of the following code snippets correctly concatenates the strings string1 and string2 with a space in between?

<p><code>concatenated_string = string1 + &quot; &quot; + string2</code> (A)</p> Signup and view all the answers

Assume you have a function count_word_occurrences(file_path, target_word). What is the most likely purpose of converting both the file content and target_word to lowercase within the function?

<p>To make the word counting case-insensitive. (A)</p> Signup and view all the answers

Given the following code:

x = 5 y = 2

What output do you expect from:

if x > 3: print("x is greater than 3") elif y < 1: print ("y is less than 1") else: print ("Else condition")

<p><code>x is greater than 3</code> (B)</p> Signup and view all the answers

Consider the following expressions:

  1. (x > 5) or (y < 10)
  2. (x > 5) and (y < 10) Under what conditions will expression 1 evaluate to True while expression 2 evaluates to False? Assume x and y are integers.

<p>When either <code>x &gt; 5</code> is true and <code>y &lt; 10</code> is false, or <code>x &gt; 5</code> is false and <code>y &lt; 10</code> is true. (B)</p> Signup and view all the answers

What is the effect of a break statement within a loop in Python?

<p>It terminates the loop entirely and continues with the next statement after the loop. (D)</p> Signup and view all the answers

If a function is defined with a default parameter, under what circumstance is the default value used?

<p>The default value is used only when the corresponding argument is not provided in the function call. (A)</p> Signup and view all the answers

What would be the outcome of attempting to access an element at an index that is beyond the bounds of a list?

<p>The program will raise an <code>IndexError</code> exception. (A)</p> Signup and view all the answers

Which of the operations is most suitable for adding a new book title to the end of the book_titles list?

<p><code>book_titles.append(&quot;New Title&quot;)</code> (D)</p> Signup and view all the answers

If you want to display a student's name and age in a formatted string, which string formatting method is preferred?

<p>Using f-strings (formatted string literals). (A)</p> Signup and view all the answers

In the shopping cart example, what operation is performed by total_cost += item_cost?

<p>It adds the value of <code>item_cost</code> to the current <code>total_cost</code>. (B)</p> Signup and view all the answers

Given shopping_cart = {"item1": {"price": 10, "quantity": 2}, "item2": {"price": 5, "quantity": 3}}, how would you access the price of item2?

<p><code>shopping_cart[&quot;item2&quot;][&quot;price&quot;]</code> (D)</p> Signup and view all the answers

If you have a list of numbers, which built-in Python function would you use to find the sum of all the numbers in the list?

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

Consider the following dictionary: student = {"name": "Bob", "age": 20}. What happens if you try to access student["grade"]?

<p>It raises a <code>KeyError</code> exception. (B)</p> Signup and view all the answers

What is the primary difference between using a list and a dictionary for storing data?

<p>Dictionaries store data in key-value pairs, while lists store data in an ordered sequence. (D)</p> Signup and view all the answers

In a scientific experiment involving a list of measurements over time, what is the primary benefit of using a for loop to analyze the data?

<p>It allows for applying the same calculation to each data point efficiently. (B)</p> Signup and view all the answers

If you have experimental data represented as experimental_data = [2.5, 3.0, 3.2, 3.8, 4.1, 4.5, 4.9], and you want to calculate the cube of each data point, how would you modify the loop?

<p>Both B and C (A)</p> Signup and view all the answers

When reading data from a CSV file using Python's csv module, what is the primary purpose of the csv.reader object?

<p>To provide an iterator that yields each row of the CSV file as a list of strings. (B)</p> Signup and view all the answers

What potential issue should be considered when processing a CSV file with the csv module?

<p>The size of the CSV file might exceed available memory. (C)</p> Signup and view all the answers

In the state machine example with a while loop and a break statement, what is the final value of i printed to the console?

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

In the state machine example using a continue statement, what is the primary effect of the continue statement within the while loop?

<p>It skips the rest of the current iteration and proceeds to the next iteration. (A)</p> Signup and view all the answers

What is the main function of the pass statement in Python?

<p>To serve as a placeholder where a statement is syntactically required but no action is needed. (A)</p> Signup and view all the answers

Which file type is best suited for storing image data that is not human-readable?

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

Flashcards

Python Interactive Mode

Executes Python code directly from the command line.

Indentation Error

A common error when Python code isn't properly spaced. Use spaces or tabs consistently

Run Python Script from Command Line

Run a Python file (.py or .pyw) by typing 'python filename.py' in the command line.

Jupyter Notebook

An environment for interactive coding, data analysis, and visualization using Python.

Signup and view all the flashcards

Anaconda

A popular Python distribution that simplifies package management and deployment.

Signup and view all the flashcards

Variables

Reserved storage locations that hold values. They have a name, type, and value.

Signup and view all the flashcards

Starting Jupyter Notebook

Go to the Anaconda folder from the Start menu or using the Anaconda Navigator shortcut icon.

Signup and view all the flashcards

variables

Reserved memory locations to store values.

Signup and view all the flashcards

What is an 'int' in Python?

Whole numbers, can be positive or negative, without any decimal points.

Signup and view all the flashcards

What is a 'long' in Python?

Integers of unlimited length, can be represented in octal or hexadecimal.

Signup and view all the flashcards

What is a 'float' in Python?

Numbers with a decimal point, representing real numbers.

Signup and view all the flashcards

What is a 'complex' number in Python?

Numbers with a real and imaginary part, denoted with 'j'.

Signup and view all the flashcards

What are Python strings?

A contiguous sequence of characters enclosed in single or double quotes.

Signup and view all the flashcards

What does the slice operator do?

Extracts a portion of a string using indexes.

Signup and view all the flashcards

What does the + operator do with strings?

Combines two strings together.

Signup and view all the flashcards

What does the * operator do with strings?

Repeats a string a specified number of times.

Signup and view all the flashcards

Subtraction Operator (-)

Subtracts the right-hand operand from the left-hand operand.

Signup and view all the flashcards

Multiplication Operator (*)

Multiplies values on either side of the operator.

Signup and view all the flashcards

Division Operator (/)

Divides the left-hand operand by the right-hand operand.

Signup and view all the flashcards

Modulus Operator (%)

Divides the left-hand operand by the right-hand operand and returns the remainder.

Signup and view all the flashcards

Exponent Operator (**)

Performs exponential (power) calculation on operators.

Signup and view all the flashcards

Floor Division Operator (//)

Divides operands and returns the quotient where digits after the decimal point are removed.

Signup and view all the flashcards

Assignment Operator (=)

Assigns the value from the RHS operand to the LHS operand.

Signup and view all the flashcards

Add AND Operator (+=)

Adds the right operand to the left operand and assigns the result to the left operand.

Signup and view all the flashcards

Subtract AND Operator (-=)

Subtracts the right operand from the left operand and assigns the result to the left operand.

Signup and view all the flashcards

Multiply AND Operator (*=)

Multiplies the right operand with the left operand and assigns the result to the left operand.

Signup and view all the flashcards

== Operator (Equality)

Checks if two values are equal, returning True if they are, and False otherwise.

Signup and view all the flashcards

!= Operator (Inequality)

Checks if two values are NOT equal, returning True if they are not equal, and False if they are.

Signup and view all the flashcards

String Concatenation

Combines two strings into a single string.

Signup and view all the flashcards

and Operator

Returns True only if ALL conditions are True.

Signup and view all the flashcards

elif Statement

Used to check additional conditions if the preceding if or elif conditions were False.

Signup and view all the flashcards

or Operator

Returns True if AT LEAST ONE of the conditions is True.

Signup and view all the flashcards

break Statement

Immediately terminates the loop's execution.

Signup and view all the flashcards

Default Parameters

Values provided when defining a function, which are used if the caller doesn't provide a value for that parameter.

Signup and view all the flashcards

List

A data structure that stores an ordered collection of items. Items can be of different data types.

Signup and view all the flashcards

Dictionary

A data structure that stores key-value pairs. Each key is unique and maps to a specific value.

Signup and view all the flashcards

Float

A numerical value with a decimal part.

Signup and view all the flashcards

String

A sequence of characters. Used to represent text.

Signup and view all the flashcards

Temperature Message

Stores the current temperature in Celsius using a variable and prints a message.

Signup and view all the flashcards

Book Titles List

Stores book titles in a list and prints the list to the console.

Signup and view all the flashcards

Student Information Card

Stores the student's name and age using variables and prints an introductory message.

Signup and view all the flashcards

Shopping Cart Cost

Calculates the total cost of items in a shopping cart, using prices and quantities from a dictionary.

Signup and view all the flashcards

Looping in Data Analysis

Repeating a block of code for each item in a dataset.

Signup and view all the flashcards

CSV File Reading Script

Opens a CSV file, reads each row, and prints its contents.

Signup and view all the flashcards

'continue' statement

Skips the rest of the current iteration and continues with the next one.

Signup and view all the flashcards

'pass' statement

A statement that does nothing; a placeholder where code will eventually go.

Signup and view all the flashcards

Text Files

Files that contain human-readable characters, such as .txt or .csv files.

Signup and view all the flashcards

Binary Files

Files containing non-textual data like images or audio.

Signup and view all the flashcards

CSV Files

Files that store tabular data separated by commas.

Signup and view all the flashcards

Study Notes

  • Python is a high-level, interpreted, interactive, and object-oriented scripting language designed for readability, using English keywords and fewer syntactical constructions.

Python Features

  • Interpreted: Python is processed at runtime by the interpreter, similar to PERL and PHP, negating the need to compile your program before executing it.
  • Interactive: Python enables direct interaction with the interpreter to write programs.
  • Object-Oriented: Python supports Object-Oriented programming, which encapsulates code within objects.
  • Beginner's Language: Python is suited for beginner-level programmers and supports a wide array of applications.

History

  • Guido van Rossum developed Python in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.
  • Python is derived from languages like ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell.
  • Python is copyrighted, with source code available under the GNU General Public License (GPL).
  • A core development team at the institute currently maintains Python, with Guido van Rossum still playing a vital role.
  • Python's Timeline:
    • Late 80s: Conceived
    • Dec 1989: Started implementation
    • Feb 1991: Released Python 0.9
    • Jan 1994: Released Python 1.0
    • Oct 2000: Released Python 2.0
    • Dec 2008: Released Python 3.0
    • Jun 2018: Released Python 3.7

Python's Key Features

  • Easy-to-learn: Few keywords, simple structure, and a clearly defined syntax allow quick language acquisition.
  • Easy-to-read: Python code is clearly defined and visible.
  • Easy-to-maintain: Python's source code is fairly easy to maintain.
  • Broad standard library: The library is portable and cross-platform compatible on UNIX, Windows, and Macintosh.
  • Interactive Mode: Interactive mode enables interactive testing/debugging.
  • Portable: Python runs on various hardware platforms with the same interface.
  • Extendable: Low-level modules can be added to the Python interpreter to customize tools.
  • Databases: Python provides interfaces to commercial databases.
  • GUI Programming: Python supports GUI applications that can be ported to various systems.
  • Scalable: Python provides better structure/support for large programs than shell scripting.

Advantages

  • Python is a high-level programming language with English-like syntax, making it easy to read and understand.
  • Python enhances productivity due to its simplicity.
  • Python is an interpreted language that executes code line by line.
  • Python automatically assigns data types during execution because it is dynamically typed. Programmers don't have to declare variable types.
  • Python is free to use and distribute under the OSI-approved open-source license.
  • Python offers vast library support, reducing dependency on external libraries.
  • Portability of Python means it only needs to be written once to run anywhere.

Running Python Scripts

  • A Python script is a file containing Python code or a program that ends with a .py extension.
  • An interpreter can execute a script as a module or as a script itself.
  • Code can be written in an interactive Python command prompt session.

Running Python Code Interactively

  • Open the command line in interactive mode.
  • Invoke the Python interpreter in the command line.
  • Sequentially write and execute Python code.
  • Can exit the windows command line by pressing Ctrl+Z and following with an Enter.
  • Python script files can end with either .py or .pyw.

Running Scripts via Jupyter Notebook

  • Download the Python installer, available on the Continuum Analytics website.
  • Note that the installer is larger than average, and should include Python, packages, code editor, and other gadgets.

Installing Anaconda/Python

  • Double click the .exe (Windows) or .pkg (Mac) file after downloading the graphical installer, then follow the on-screen instructions.
  • Steps for installing/uninstalling Python are available online.
  • When installing Anaconda, a pop-up menu may ask whether to “Add Anaconda to my PATH environment variable” and “Register Anaconda as my default Python 3.5."

Starting Jupyter Notebook

  • After downloading/installing Anaconda, find associated tools to open Jupyter Notebook.
  • Access the tools via the Anaconda folder from the Start menu (Windows only) or the Anaconda Navigator shortcut icon.

Variables

  • Variables are reserved memory locations for storing values, implying memory allocation upon creation.
  • The interpreter allocates memory based on the variable's data type.
  • Variables can store integers, decimals, or characters by assigning different data types.

Variable Creation Rules

  • Variables must start with a letter or the underscore character.
  • Variables cannot start with a number.
  • Variables can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • Variable names are case-sensitive (name, Name, NAME are distinct).
  • Reserved words or keywords cannot be used as variable names.

Assigning Values

  • Explicit variable declaration to reserve memory space is unnecessary.
  • Declaration happens automatically upon assigning a value to a variable, using the equal sign (=).
  • The operand to the left of = is the variable name, and the operand to the right is the value stored.

Assignment Types

  • Multiple Assignment: Assign a single value to multiple variables simultaneously.
  • Multiple Objects: Assign multiple objects to multiple to variables.

Standard Python Data Types

  • Data stored in memory can be numeric, alphanumeric, etc.
  • Standard data types in Python define the operations possible and the storage method for each.
  • Python Standard Data Types include Numbers, String, List, Tuple, Dictionary and Boolean. Set is also a Python Standard Data Type.

Python Numbers

  • Number data types store numeric values; objects created upon assignment.
  • Can delete single or multiple objects using the statement del.
  • Supports int, long, float, and complex number types.

Python Strings

  • Strings are contiguous sets of characters in quotation marks, allowing single or double quotes.
  • Subsets of strings use the slice operator ([ ] and [:]) with indexes starting at 0.
  • The plus (+) sign is the string concatenation operator; the asterisk (*) is the repetition operator.

String Operators

  • Strings are created by enclosing characters in quotes and are a popular type in Python.
  • Python treats single/double quotes the same.
  • String creation is simple and involves assigning a value to a variable.

Accessing Values

  • Python treats characters as strings of length one.
  • Substrings are accessed via square brackets for slicing with index/indices.

Updating Strings

  • Assigning a variable to another string is how strings are updated.
  • The new value can relate to its previous value or be a different string altogether.

String Special Operators

  • Assume variable a holds 'Hello' and variable b holds 'Python':: -+ Concatenation - Adds values on either side of the operator: a + b will give HelloPython -* Repetition - Creates new strings, concatenating multiple copies of the same string: a*2 will give HelloHello -[] Slice - Gives the character from the given index: a[1] will give e -[:] Range Slice - Gives the characters from the given range: a[1:4] will give ell -in Membership - Returns true if a character exists in the given string: H in a will give 1 -not in Membership - Returns true if a character does not exist in the given string: M not in a will give 1 -r/R Raw String - Suppresses actual meaning of Escape characters: print r'\n'prints \n and print R'\n'prints \n

Triple Quotes

  • Enable strings to span multiple lines, including NEWLINEs, TABs, etc.
  • Consists of three consecutive single/double quotes.

Built-in String Methods

  • Manipulate strings in Python using built-in methods.
    • capitalize(): Capitalizes the first letter of string.
    • center(width, fillchar): Returns a space-padded string with the original string centered to a total of width columns.
    • count(str, beg= 0,end=len(string)): Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
    • decode(encoding='UTF-8',errors='strict'): Decodes the string using the codec registered for encoding.
    • encode(encoding='UTF-8',errors='strict'): Returns encoded string version of string; Unless errors is given with 'ignore' or 'replace' a Value Error is raised if there is an error.
    • endswith(suffix, beg=0, end=len(string)): Determines if string (or substring with specified indices) ends with suffix; returns true if so.
    • expandtabs(tabsize=8): Expands tabs in string to multiple spaces and defaults to 8 spaces per tab.
    • find(str, beg=0 end=len(string)): Identifies if str occurs in string or if a string of str occurs in a substring - returns index if found and -1 if it is missed.
    • index(str, beg=0, end=len(string)): Same as find(), but raises an exception if str not found.
    • isalnum(): Returns true if string has at least 1 character and all characters including alphanumeric and false if this is missed.
    • isalpha(): Returns true if string has at least 1 character and all characters including alphabetic and false if this is missed.
    • isdigit(): Returns true if string contains only digits and false otherwise.
    • islower(): Returns true if string has at least 1 cased character and all cased characters are in lowercase, and the function returns false if this is missed.
    • isnumeric(): Returns true if a unicode string contains only numeric characters.
    • isspace(): Returns true if string contains only whitespace characters and returns false if this is missed.
    • istitle(): Returns true if string is properly "titlecased" and false otherwise.
    • isupper(): Returns true if string has at least one cased character and all cased characters are in uppercase.
    • join(sep): Merges, concatenates, the string representations of elements in sequence seq into a string, with separator string.
    • len(string): Returns the length of the string.
    • ljust(width[, fillchar]): Returns a space-padded string with the original string left-justified to a total of width columns.
    • lower(): Converts all uppercase letters in string to lowercase.
    • lstrip(): Removes all leading whitespace in string.
    • maketrans(): Returns a translation table to be used in translate function.
    • max(str): Returns the max alphabetical character from the string str.
    • min(str): Returns the min alphabetical character from the string str.
    • replace(old, new [, max]): Replaces all occurrences of old in string with new or at most max occurrences if max given.

Mathematical Operators

  • Manipulate the value of operands and are constructs that you can use.
  • 4 + 5 = 9 Here, 4 and 5 are the operands and + is the operator.

Operator Types

  • Arithmetic.
  • Comparison (Relational).
  • Assignment.
  • Logical.
  • Bitwise.
  • Membership.
  • Identity.

Python arithmetic operators

  • Assume variable a holds 10 and variable b holds 20: -+Addition: Adds values on either side of the operator: a + b = 30 -- Subtraction: Subtracts right hand operand from left hand operand: a - b = - 10 -Multiplication: Multiplies values on either side of the operator: a b = 200 -/Division: Divides left hand operand by right hand operand: b/a = 2 -% Modulus: Divides left hand operand by right hand operand and returns remainder: b%a = 0 -** Exponent: Performs exponential calculation on operators: a**b =10 to the power 20 -//Floor Division: The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored: 9//2 = 4 and 9.0//2.0 = 4.0, - 11//3 =-4, - 11.0//3 =-4.0

Python Comparison Operators

  • Used to compare the values on either sides of them and decide on the relation between them.
  • Are also called relational operators.

Python Assignment Operators

  • Assume variable a holds 10 and variable b holds 20: -= Assigns values from right side operands to left side operand: c = a + b assigns value of a + b into c -+= Add AND Adds right operand to the left operand and assign the result to left operand: c += a is equivalent to c = c + a --= Subtract AND: It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a -*= Multiply AND: It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a -/= Divide AND: It divides left operand with the right operand and assign the result to left operand: c /= a is equivalent to c = c / a -%= Modulus AND: It takes modulus using two operands and assign the result to left operand: c %= a is equivalent to c = c % a -**= Exponent AND: Performs exponential calculation on operators and assign value to the left operand: c **= a is equivalen t to c = c ** a -//= Floor Division: It performs floor division on operators and assign value to the left operand: c //= a is equivalent to c = c // a

Python Bitwise Operators:

  • Bitwise operator works on bits , and performs operation bit by bit.
  • There are following Bitwise operators supported by Python language: -& Binary AND: Operator copies a bit to the result if it exists in both operands. -| Binary OR: It copies a bit if it exists in either operand. -^ Binary XOR: It copies the bit if it is set in one operand but not both. -~Binary Ones Complement: Is unary and has the effect of flipping’ bits. -<< Binary Left Shift: The left operands value is moved left by the number of bits specified by the right operand. ->> Binary Right Shift: The left operands value is moved right by the number of bits specified by the right operand.

Python Logical Operators

  • Supported by program language.
  • AND: If both the operands are true then condition becomes true.
  • OR: If any of the two operands are non-zero then condition becomes true.
  • NOT: Used to reverse the logical state of its operand.

Identity Operators

  • Help to check if the operands share the same memory location

Membership Operators

  • Help to check if there is a member in a sequence - such a character within a string

Input Function

  • The input() function is used to take user input from the keyboard.
  • In Python 3, the input() function has been modified. The old raw_input() from Python 2 was removed.

Indentation

  • Indentation can be done with whitespace, such as blank spaces or tabs.
  • Helps define a block of code.
  • In Python, the blocks of code are highlighted with indentation.

Conditional Statements

  • Also called decision-making statements.
  • Used while trying to execute a block of code and check if the given condition is true or false.
  • Types include if, if else, Elif and Nested if:
    • if statement: Used to check a condition and execute a block of code if the condition is true. Is the primary conditional statement and can be used alone or in conjunction with else or elif. If the condition in the if statement is true, the associated block of code is executed, and then the program moves on to the next part.
    • elif statement: Is used to check additional conditions if the previous if or elif conditions were not true and is an abbreviation for "else if."

Loop Statements

  • Enable the the repeated execution of a block of code.
    • While loop: a set of statements can be executed in these loops, as long as their condition is true.
    • For loop: these loops iterate through items in a sequence.

Breaking and Continuing Loops

  • Break loop: Stop the loop even if the while condition is true.
  • Continue loop: Stop the current iteration, and continue with the next.

Nested Loops

  • Referred to when a loop becomes a loop inside a loop.
  • The "inner loop" will be executed one time for each iteration of the "outer loop."

Functions

  • A function is a block of code which only runs when it is called.
  • It is possible to pass data (parameters) into functions.

Function Creation

  • Functions are created by using the command def.

Function Calling

  • Calling a function is done with func()
  • Functions can also have parameters.

Default Parameter Value

  • It is possible to assign default parameters to functions.

Return Values

  • Use to obtain outputs from functions.

Recursion

  • A defined function can call itself.

Lambda Function

  • Short, anonymous function.
  • Lambda-function can take number of arguments, but an only have one expression.

File Handling (Why it is needed)

  • Used for storing and retrieving data persistently.
  • Allows to save data even after program termination and enables sharing with program loops.
  • Common configuration,logs and databases.

File Types

  • Text files contain human-readable characters where examples include .txt files.
  • Binary Files store data in a binary format.
  • CSV Files stores tabular data using commas.
  • JSON Files stores data in a structured format with key-value pairs.

File Operating

  • Opening files.
  • Reading from a file.
  • Writing to a file.
  • Closing a file.
  • Error handling.

Types of file access modes

  • r: Opens the file with read-only access.
  • w: Opens the file with write-only access.
  • a: Opens the file in the append mode.
  • r+: Opens the file for both reading and writing.

Python type of file

  • Text, binary, CSV and JSON files.

Different Modes and opening a file

  • r, w, a etc.

How to write and add content to a file

  • write()
  • file = open('thefile.txt', 'w')

Method used to close

  • close()
  • file.close()

Studying That Suits You

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

Quiz Team

Related Documents

Description

This quiz assesses fundamental concepts in Python, including data types, string manipulation, and basic operations. It covers string slicing, concatenation, and understanding of complex numbers. Also discussed are Anaconda Navigator and Python script execution.

More Like This

Use Quizgecko on...
Browser
Browser