Python Basics

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 NOT a basic data type in Python?

  • float
  • int
  • list (correct)
  • bool

Python int data type has a fixed size limit, meaning it cannot exceed a certain value.

False (B)

Name the three categories of data types in Python.

Basic, Container, User-defined

In Python, integers can be represented in decimal, binary, _______, and hexadecimal.

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

Match the following Python data types with their corresponding category:

<p>int = Basic type list = Container type class = User-defined type bytes = Basic type</p> Signup and view all the answers

Which action activates the Python interpreter in the shell or command prompt?

<p>Typing <code>python</code> (A)</p> Signup and view all the answers

IDLE is an optional, third-party add-on for running Python.

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

What is the command to execute a Python script named myscript.py from the command prompt?

<p>python myscript.py</p> Signup and view all the answers

A Python __________ is a name used to identify a variable, function, class, or module.

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

Which of the following best describes the purpose of Python keywords?

<p>Reserved words with predefined meanings that cannot be used as identifiers (C)</p> Signup and view all the answers

Match the following Python keywords with their descriptions:

<p>and = A logical operator from = To import specific parts of a module global = To declare a global variable if = To make a conditional statement</p> Signup and view all the answers

Which keyword is used to bring specific parts of a module into the current scope?

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

The number of keywords in Python has remained constant across all versions.

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

Which of the following features contributes to Python's versatility?

<p>Its powerful development libraries, including AI and ML. (B)</p> Signup and view all the answers

Python requires manual memory management by the programmer.

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

Who created Python and in what year?

<p>Guido van Rossum, 1991</p> Signup and view all the answers

Python is an ______ language, meaning code is executed line by line.

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

What inspired Guido van Rossum to name the Python programming language?

<p>The BBC comedy show 'Monty Python's Flying Circus'. (D)</p> Signup and view all the answers

Which of the following is NOT a key feature of Python?

<p>Requires compilation before execution (B)</p> Signup and view all the answers

What does it mean that Python is an 'interpreted' language?

<p>Python code is executed line-by-line directly by an interpreter. (C)</p> Signup and view all the answers

Which keyword is used to define a function in Python?

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

In Python, you must explicitly declare the data type of a variable before assigning a value to it.

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

What will the following code output? x = 8 x = "example" print(x)

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

In Python, the keyword ______ is used to represent a null value.

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

Which of the following is NOT a valid variable identifier in Python?

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

Match the following keywords with their corresponding descriptions:

<p>pass = A null statement lambda = Creates an anonymous function del = Deletes an object continue = Goes to the next loop iteration</p> Signup and view all the answers

What is the purpose of the finally block in a try-except statement?

<p>To define a block of code that always executes, regardless of whether an exception occurred. (D)</p> Signup and view all the answers

In Python, Name and name would be considered the same identifier.

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

Which of the following is NOT a valid representation of a float in Python?

<p>3+2j (B)</p> Signup and view all the answers

The input() function in Python always returns an integer value.

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

What is the data type of the expression 5 // 2 in Python, and what value does it evaluate to?

<p>The data type is an integer and the value is 2.</p> Signup and view all the answers

In Python, a __________ is an immutable collection of Unicode characters.

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

Match the following operators with their descriptions:

<ul> <li>= Addition % = Modulus (remainder of division) ** = Exponentiation // = Floor Division</li> </ul> Signup and view all the answers

Given x = 10 and y = 3, what is the result of the expression x ** y?

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

Which comparison operator would you use to check if two variables, a and b, are not equal?

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

What is the result of the following operation: x //= 3 if x = 10 initially?

<p>x = 3 (B)</p> Signup and view all the answers

Flashcards

Python Interactive Mode

Interactive mode where you can execute Python commands one at a time.

IDLE

The standard Python development environment, good for both Unix and Windows.

Python Identifier

A name used to identify a variable, function, class, module, or other object.

Python Keywords

Reserved words that cannot be used as identifiers.

Signup and view all the flashcards

"and" Keyword

A logical operator that returns True if both operands are true.

Signup and view all the flashcards

"as" Keyword

Used to create an alias, giving a module or object a different name.

Signup and view all the flashcards

"assert" Keyword

Used as a debugging tool to test conditions in your code.

Signup and view all the flashcards

"from" Keyword

To import specific parts of a module

Signup and view all the flashcards

Basic Data Types

Fundamental data types: int, float, complex, bool, string, bytes.

Signup and view all the flashcards

Container Data Types

Data types that hold collections of other data: list, tuple, set, dict.

Signup and view all the flashcards

User-Defined Data Types

Data types defined by the user using the 'class' keyword.

Signup and view all the flashcards

int Data Type

Whole numbers, without any decimal point.

Signup and view all the flashcards

Integer Representations

Integers can be represented in decimal (base 10), binary (base 2), octal (base 8), and hexadecimal (base 16).

Signup and view all the flashcards

continue

Skips the rest of the current loop iteration and proceeds to the next one.

Signup and view all the flashcards

def

Defines a new function.

Signup and view all the flashcards

del

Removes a variable or item from memory.

Signup and view all the flashcards

What is Python?

A popular, general-purpose, high-level programming language that is both interpreted and object-oriented.

Signup and view all the flashcards

elif

An alternative condition if the initial 'if' condition is false.

Signup and view all the flashcards

Why learn Python?

It is open source, simple to learn, versatile for different applications, and has powerful development libraries.

Signup and view all the flashcards

None

Represents 'nothing' or 'no value'.

Signup and view all the flashcards

pass

A statement that does absolutely nothing.

Signup and view all the flashcards

Python is Interpreted

Python is executed line-by-line by an interpreter, allowing code to run on different platforms without separate compilation.

Signup and view all the flashcards

Variable

A memory location where a value can be stored and changed.

Signup and view all the flashcards

High-Level Language

Python hides low-level details like memory management, allowing programmers to focus on the logic of the code.

Signup and view all the flashcards

Origin of 'Python' Name

Watching 'Monty Python's Flying Circus' inspired Guido van Rossum when naming the Python language.

Signup and view all the flashcards

Identifier

A case-sensitive name used to identify a variable, function, class, module or other object.

Signup and view all the flashcards

Who created Python?

Created by Guido van Rossum in 1991 and further developed by the Python Software Foundation.

Signup and view all the flashcards

Easy to Learn Python

Beginners find Python easy to pick up because it doesn't need knowledge of lower level coding.

Signup and view all the flashcards

Benefits of Interpreted Language

You can run the same code across different platforms and make changes in code without restarting the program.

Signup and view all the flashcards

Float

Represents numbers with fractional parts or in exponential form (e.g., 3.14, 2.5e-3).

Signup and view all the flashcards

Complex

Data type holding pairs of real and imaginary numbers (e.g., 3+2j).

Signup and view all the flashcards

Bool

Data type with two possible values: True or False.

Signup and view all the flashcards

String

An immutable sequence of Unicode characters (text) enclosed in quotes.

Signup and view all the flashcards

Bytes

Represents a sequence of bytes, often used for binary data.

Signup and view all the flashcards

print()

Outputs values to the console or screen.

Signup and view all the flashcards

input()

Retrieves input from the keyboard as a string.

Signup and view all the flashcards

Floor Division (//)

Returns the largest whole number less than or equal to the division result.

Signup and view all the flashcards

Study Notes

Introduction to Python Programming

  • Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level programming language.
  • Python is open source, simple, easy to learn, versatile and has powerful development libraries like AI and ML.
  • Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation.
  • Guido van Rossum named the language Python after the comedy show "The complete Monty Python's Flying Circus”.

Key Features of Python

  • Is easy to learn and use, making it an ideal programming language for beginners.
  • As a High Level Language doesn't require worrying about low-level details like memory management or hardware-level operations.
  • As an interpreted language, code is executed line-by-line directly by interpreter, without the need for separate compilation, allowing code to run on different platforms and for changes to be made without restarting the program.

Basics of Python Programming

  • Python comes with an interactive interpreter.
  • Typing python in the shell or command prompt activates the python interpreter, which waits for commands with a >>> prompt.

Running Python Scripts

  • IDLE (Integrated Development and Learning Environment) is the standard Python development environment.
  • IDLE is an acronym of "Integrated Development Environment".
  • It functions properly on Unix and Windows platforms, and includes a Python shell window for interactive mode access.
  • To Run Python Scripts in IDLE, go to menu File -> New File (CTRL+N), write the code and save as add.py
  • To run Python scripts in Command Prompt, open a text editor, type the code, save as hello.py and then run python hello.py.

Python Identifiers and Keywords

  • A Python Identifier is the name given to identify variables, functions, classes, modules, or other objects.
  • Python identifiers can be a combination of uppercase and lowercase letters, digits, or an underscore.
  • They cannot start with a digit or contain special symbols like !,#, @,%,$.
  • Python keywords are reserved words that cannot be used as names for entities like variables, classes, and functions.
  • Python 3.8 has 35 keywords, an increase from the 33 keywords in Python 3.7.

Variables

  • Variables are named storage locations whose values can change over time.
  • In Python, variables are created the moment a value is assigned, without needing a specific declaration.
  • Python does not require explicit type definitions for variables.
  • Python is a dynamically-typed language.
  • Valid examples of variable assignment are a = 10, pi = 3.14, name = 'Sanjay'.

Rules and Examples for Writing Variables / Identifiers

  • Python is case sensitive; Name and name are distinct identifiers.
  • Identifiers can include uppercase and lowercase letters, digits, or _; myVariable, variable_1, and variable_for_print are valid.
  • Identifiers cannot start with a digit; variable1is valid, but 1variableis not.
  • It is not possible to use special symbols like !,#, @,%,$ in identifiers.

Python Data Types

  • Variables can store data of different types.
  • Python has data types built-in by default, categorized as basic, container, and user-defined types.
  • Basic types include int, float, complex, bool, string, and bytes.
  • Container types include list, tuple, set, and dict.
  • User-defined types include Class.
  • Integers can be expressed in binary (starts with 0b), decimal (0-9), octal (starts with 0o), or hexadecimal(starts with 0x).
  • Int can be of any arbitrary size.

Input and Output

  • print() is used to output values on the screen.
  •  input() built-in function can be used to retrieve input values from keyboard.
  • The input() function returns a string, which may need to be converted to int or float for arithmetic operations.

Operators in Python

  • Python's operators are divided into arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators.
  • Arithmetic operators include + (addition), - (subtraction), * (multiplication), / (division), % (modulus), ** (exponent), and // (floor division).
  • Comparison operators compare two operands and result in TRUE (Non-zero) or FALSE (Zero).
  • Logical operators: and, or, and not produce a result of TRUE (ONE) or FALSE (ZERO).
  • Identity operators compare objects, not for equality, but to check if they are actually the same object with the same memory location: is and is not.
  • Membership operators test if a sequence is present in an object, using in and not in.
  • Bitwise operators compare binary numbers: & (AND), | (OR), ^ (XOR),~ (NOT),<< (left shift), and>> (right shift).
  • Assignment operators are used to assign values to variables, such as  =, +=, -=.

Type Conversions

  • Mixed mode operations: Operation between int and float will yield float, Operations between int and complex will yield complex, Operations between float and complex will yield complex.
  • We can convert one numeric type to another using built-in functions.
  • The functions int(), float(), complex(), and bool() is used.

Built-in Functions

  • The print() function is also a built-in function.
  • Information about any built-in function can be accessed using help(function).
  • Commonly used built-in functions with numbers include abs(x) (absolute value), pow(x, y) (x raised to y), min(x1, x2,...) (smallest argument), and max(x1, x2,...) (largest argument).

Built-in Modules

  • Each module contains several functions.
  • Common modules include math, cmath, random, and decimal.
  • math contains mathematics functions, cmath functions for complex numbers, random functions for random number generation, and decimal for precise arithmetic operations.
  • Trigonometric functions are also in the math module.
  • To use functions of the Built-in modules, we use import statements.

Comments in Python

  • Comments are used to explain code, making it easier to read, and are ignored during execution.
  • Single-line comments begin with #.
  • Multi-line comments are written in a pair of ''' or """".

Indentation

  • Indentation is an important part of python syntax.
  • Python uses indentation to define a block of code.
  • Using wrong indentation can cause issues.
  • One common error is 'Unexpected indent'.

Control Statements

  • Python control statements can alter the execution sequence of instructions in a program.
  • Types for control statements are Decision control instruction and Repetition control instruction.
  • Colon(:) after ifelse, elif is compulsory, and statements in if block, else block, elif block have to be indented.

Decision Making Instructions

  • The if statement is used to test a specific condition; a block of code (if-block) will be executed if the condition is true.
  • The if-else statement provides a block of code for the false case of the condition.
  • The elif statement enables checking multiple conditions and executing specific blocks of statements depending upon the true condition among them.
  • Python supports nested if statements.

Repetition Control Instruction / Loops

  • 2 types of repetition control instructions are while and for Loops.
  • The For loop is used to iterate over elements of a sequence such as a string, tuple, or list.

For Loops

  • It can be used to repeat a set of statements a finite number of times and iterate through a string, list, tuple, set or dictionary.
  • In For loops, the built-in function range() is used.
  • range() function generates a sequence of integers.
  • The for loop can be terminated abruptly using break.
  • During each iteration var is assigned the next value from the list.
  • else block is optional and is executed if the loop is not terminated abruptly using break.

Loop Control Statements

  • The break statement in Python is used to exit or "break" out of loop prematurely .
  • Continue statement will skip the execution of the program block and returns the control to the beginning of the current loop to start the next iteration.
  • For the else Statement, if break does not happen and if the circuit has finished iterating over the list, else gets combined.

The pass Statement

  • The pass statement is a null statement and a placeholder for future code, preventing errors from empty code blocks.
  • Unlike comments, pass is not ignored by interpreter.

While Loops

  • A while loop to repeat a block of code as long as a specified condition is True.
  • It is especially useful when the number of iterations isn't known beforehand but depends on some dynamic condition. When the conditon becomes false on while loops, the statemnt immediately after is executed.

Functions

  • A function is a subprogram containing a set of instructions for a specific task, dividing programs into basic building blocks.
  • Functions avoid rewriting the same code, provide code re-usability, and reduce program length.
  • Functions are classified into built-in functions and user defined functions.
  • Built-in functions are pre-created and stored and can't be modified whereas user defined functions are created for specific reasons and imported.

Making User Defined Functions

  • def keyword is used to define a function.
  • function name after def keyword, followed by parentheses (where arguments are given) is used.
  • The function must end with a colon (:) and inside the function, and the program statements to be executed are added.
  • A function ends with or without return statement

Function Calling and Parameter Passing

  • Once a function is defined, it can be called from another function.
  • During Function Calling, def fun_name(Parameter1, Parameter2...Parameter n) and return [expression] is Syntax.
  • While, function is invoked, the flow jumps to the first line of the called function, executes all the statements there, and then comes back to pick up where it left off.

Parameters vs. Arguments

  • Parameters are the value(s) provided in the parenthesis when defining a function.
  • Arguments are the actual value(s) provided in function call/invoke statement.
  • Bounding of parameters to arguments is done 1:1.

Return Statement

  • The return statement exits a function and goes back to where it was called. Syntax: return [expression]

Arguments Types

  • The Argument types are Required Arguments, Keyword(named) Arguments, Default Arguments, Variable length Arguments.
  • When the function is called using required argument(s)
  • Functions can be made to recirsively loop.

Other Argument Types

  • A function can have positional-only arguments only by specifying that. Using / the arguments specified after can't be used by only positionally.

Lambda Functions

  • A lambda function is a small anonymous function that can take any number of arguments, but can only have one expression.
  • Lambda functions are defined using the lambda keyword in Python.

Modules

  • A module is a file containing Python definitions, functions, statements and instructions.
  • The standard library of Python are extended as modules.
  • Modules need to be imported to be used in a program.
  • Syntax: import module_name/ module_name.function_name(variable)
  • Some of the four ways to import modules are using import, from import , import with renaming and import all .
  • The math module has some functions like math.ceil(x), math.floor(x), math.sqrt(x), math.log(x), etc.

Studying That Suits You

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

Quiz Team

More Like This

Join the Ultimate Knowledge Challenge
9 questions
Python Data Types and Variables Quiz
10 questions
Python Keywords and Data Types
40 questions

Python Keywords and Data Types

RecordSettingComposite avatar
RecordSettingComposite
Python Data Types
30 questions

Python Data Types

MarvellousFable4043 avatar
MarvellousFable4043
Use Quizgecko on...
Browser
Browser