Podcast
Questions and Answers
Which of the following is NOT a type of computer language?
Which of the following is NOT a type of computer language?
- High-level structured language
- Machine language
- Natural language (correct)
- Assembly language
Assembly languages are directly executed by computers without translation.
Assembly languages are directly executed by computers without translation.
False (B)
What type of software provides an interface between the user and the computer's hardware?
What type of software provides an interface between the user and the computer's hardware?
Operating System
A ______ takes the entire source code of a program and translates it into machine code all at once.
A ______ takes the entire source code of a program and translates it into machine code all at once.
Match the following steps to their correct order in the compilation process:
Match the following steps to their correct order in the compilation process:
Which of the following is a characteristic of Object-Oriented Programming (OOP)?
Which of the following is a characteristic of Object-Oriented Programming (OOP)?
Java is OS-dependent, meaning the same code cannot run on different operating systems.
Java is OS-dependent, meaning the same code cannot run on different operating systems.
Which programming language was used to create Python?
Which programming language was used to create Python?
Colab facilitates easy ______ and provides users access to ______.
Colab facilitates easy ______ and provides users access to ______.
Match the actions to the correct keys to run the code with Google Colab
Match the actions to the correct keys to run the code with Google Colab
Which of the following is NOT a reason why Python is a popular language?
Which of the following is NOT a reason why Python is a popular language?
Variable names in Python can begin with a number.
Variable names in Python can begin with a number.
What term is used to describe when python evaluates an expression?
What term is used to describe when python evaluates an expression?
A ______ is a unit of code that has an effect, like creating a variable or displaying a value.
A ______ is a unit of code that has an effect, like creating a variable or displaying a value.
Match the operator with the functions:
Match the operator with the functions:
Given the expression 10 + 5 * 2 ** 2 - 20 // 5
, what is the correct order of operations according to Python's precedence rules?
Given the expression 10 + 5 * 2 ** 2 - 20 // 5
, what is the correct order of operations according to Python's precedence rules?
In python 3, /
operation is an int operation with integers.
In python 3, /
operation is an int operation with integers.
What is the result of 7 // 2?
What is the result of 7 // 2?
The term ______ is a representation of logical statements in Python, holding either a True
or False
value.
The term ______ is a representation of logical statements in Python, holding either a True
or False
value.
Match the operations to it meaning in Boolean expressions:
Match the operations to it meaning in Boolean expressions:
Given x = 5
, which expression will return True
?
Given x = 5
, which expression will return True
?
X=y is an equality operator rather than an assignment.
X=y is an equality operator rather than an assignment.
Given the snippet code: rst = True and True or (not False)
what will be the value for rst?
Given the snippet code: rst = True and True or (not False)
what will be the value for rst?
In Python, strings are represented using the type abbreviation ______
In Python, strings are represented using the type abbreviation ______
Match concatenation function to its description:
Match concatenation function to its description:
If var1 = 'Hello World!'
, what will print('Updated String :-', var1[:6] + 'Python')
output?
If var1 = 'Hello World!'
, what will print('Updated String :-', var1[:6] + 'Python')
output?
In Python, only double quotes can be used to encapsulate strings
In Python, only double quotes can be used to encapsulate strings
What value in var1 = 'Hello World!'
is returned, when calling var1[0]
?
What value in var1 = 'Hello World!'
is returned, when calling var1[0]
?
In Python, explicit conversion is also called ______
In Python, explicit conversion is also called ______
Match the following example to their type:
Match the following example to their type:
What is the default return type of the input()
function in Python?
What is the default return type of the input()
function in Python?
List items are unchangeable and duplicate values are not allowed.
List items are unchangeable and duplicate values are not allowed.
Lists items are accessed or accessed by which?
Lists items are accessed or accessed by which?
To remove all the elements from a list we can use ______.
To remove all the elements from a list we can use ______.
Match list example functions to it what they do:
Match list example functions to it what they do:
Which of the following is not correct about the characteristics of Tuples?
Which of the following is not correct about the characteristics of Tuples?
To print a key in a dict, use roman_numerals[0]
To print a key in a dict, use roman_numerals[0]
Does set
data type support modification or addition? (yes or no)
Does set
data type support modification or addition? (yes or no)
Identity operators are used to compare the ______
Identity operators are used to compare the ______
Match type of error to their description:
Match type of error to their description:
Flashcards
Operating System
Operating System
Software that provides an interface with the user.
Software Applications
Software Applications
Software used for specific tasks, such as word processing or spreadsheets.
Machine Languages
Machine Languages
Languages that computers can directly understand and execute, using 1s and 0s.
Assembly Languages
Assembly Languages
Signup and view all the flashcards
High-Level Languages
High-Level Languages
Signup and view all the flashcards
Compiler
Compiler
Signup and view all the flashcards
Interpreter
Interpreter
Signup and view all the flashcards
Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP)
Signup and view all the flashcards
Python
Python
Signup and view all the flashcards
Google Colab
Google Colab
Signup and view all the flashcards
Variables
Variables
Signup and view all the flashcards
Print() Function
Print() Function
Signup and view all the flashcards
Integer (int)
Integer (int)
Signup and view all the flashcards
Float (float)
Float (float)
Signup and view all the flashcards
Boolean (bool)
Boolean (bool)
Signup and view all the flashcards
String (str)
String (str)
Signup and view all the flashcards
List
List
Signup and view all the flashcards
Tuple
Tuple
Signup and view all the flashcards
Dictionary (dict)
Dictionary (dict)
Signup and view all the flashcards
Arithmetic Operators
Arithmetic Operators
Signup and view all the flashcards
Precedence
Precedence
Signup and view all the flashcards
Math Module
Math Module
Signup and view all the flashcards
Comment
Comment
Signup and view all the flashcards
Syntax Error
Syntax Error
Signup and view all the flashcards
Runtime Error
Runtime Error
Signup and view all the flashcards
Semantic Error
Semantic Error
Signup and view all the flashcards
math.e
math.e
Signup and view all the flashcards
math.pi
math.pi
Signup and view all the flashcards
type Function
type Function
Signup and view all the flashcards
Variable
Variable
Signup and view all the flashcards
input() function
input() function
Signup and view all the flashcards
Bool data type
Bool data type
Signup and view all the flashcards
reverse()
reverse()
Signup and view all the flashcards
Identity Operators
Identity Operators
Signup and view all the flashcards
Membership Operators
Membership Operators
Signup and view all the flashcards
Study Notes
- The content covers an introduction to Python programming
- It is part 1 of an "Intro to AI and Data Science" course, NGN 112, for the Spring 2025 semester.
- The course is taught by Maen Alkhader from the Department of Mechanical Engineering, College of Engineering at the American University of Sharjah.
- The material was prepared by Dr. Jamal A. Abdalla, CVE, and revised by Dr. Tamer Shanableh, CSE.
- The document was last updated on September 10th, 2024.
Table of Contents
- Computer Software and Programming Languages
- Introduction to Python
- Variables and Data Types
- Python Operations
Computer Software
- Operating systems provide an interface for the user to interact with the computer.
- Examples of operating systems include Unix, Windows, Linux, and iOS.
- Software applications include word processors like Microsoft Word, spreadsheet programs like Excel, and mathematical computation tools like MATLAB and Mathcad.
- Computer languages include machine language, assembly language, high-level structured languages, and high-level object-oriented languages like C++, Java, and Python.
- Internet browsers include Chrome, Edge, and Firefox.
- Apps include WhatsApp, Instagram, and Twitter.
Programming Languages
- Computer languages are categorized as low-level, high-level, and specialized
- Low-level languages: Machine language (binary) and Assembly language (NASM).
- High-level languages: Markup Language (HTML, XML), Query Language (SQL, SPARQL), Procedural Language (Fortran, Pascal), Functional Language (Haskell, #F), Object-Oriented Programming Language (Python, C++), and Scripting Language (JavaScript, Perl).
- Specialized languages: Domain-Specific language MATLAB, and R Language.
Machine Languages
- Machine languages consist of sequences of 1s and 0s and are the only languages directly understood by computers.
- They are defined by a computer's hardware design
- It is specific to particular computers and machine-dependent.
- It is difficult to understand for human readers
- Instructs most elementary of operations, for example, copy a number from memory to the CPU
- Machine languages are tedious and error-prone, leading to the development of Assembly Languages.
Assembly Languages
- Assembly languages use English-like abbreviations to represent elementary computer operations
- Translated to machine language before running
- Assemblers convert Assembly language into machine language, allowing for high-speed conversion.
- Assembly language is clearer to human readers than machine language but is still tedious to use, requiring many instructions for simple tasks
- Assembly Languages lead to the development of High-Level Languages
High-Level Languages
- High-level languages use single statements to accomplish substantial tasks, such as printing a variable of a specific type.
- They are translated to machine language, first converted to assembly then to machine language by compilers
- Conversion takes time
- Code instructions are understandable to humans; the language looks like everyday English
- Contain common mathematical notation
- Used in a development environment
Compiled vs. Interpreted Languages
- A compiler translates the entire source code into machine code at once
- The machine code made by compiler is saved as an executable file
- The executable file can be run multiple times without recompilation
- An interpreter processes the source code line by line or statement by statement at runtime
- The interpreter translates each line or statement into machine code and immediately executes it
Object-Oriented Programming (OOP)
- OOP is modeled after real-world items, where new variable types can be created, and these variables are considered objects.
- OOP uses objects as reusable software components without needing to implement them.
- Programs are more understandable by humans and easier to correct, modify, and maintain.
C, C++, Java, Python
- C was developed by Dennis Ritchie at Bell Laboratory (1972).
- C gained recognition as the language of UNIX.
- Development of C lead to the development of C++.
- It is widely used for developing operating systems and was used to create Python.
- C++ was developed by Bjarne Stroustrup at Bell Laboratory (1980s).
- C++ is an Extension of C with elements from a Simulation programming language (Simula 67) and is a structured and object-oriented programming language.
- Java is a product of Sun Microsystems corporate research project (1991).
- Java is based on C and C++ and is OS-independent, which allows the same code to run on Windows, Mac, and Linux.
- It was intended for intelligent consumer-electronic devices and gained popularity with the emergence of the WWW (World Wide Web).
- Java is widely used for enhancing the functionality of WWW servers.
Python
- Python is a popular structured and object-oriented programming language created by Guido van Rossum and released in 1991.
- Use cases include Machine Learning and Data Science, software development, web development, performing complex mathematics, handling big data, rapid prototyping, and system scripting.
Why Python?
- Python has features not available in a single language
- Python works on different platforms such as Windows, Mac, Linux, and Raspberry Pi
- Python has an English-like simple syntax
- Python has a compact syntax that allows developers to write shorter programs
- Python runs on an interpreter system for immediate execution and quick prototyping
- Python is a structured and object-oriented programming language
- Python is widely used for Data Science and Machine Learning
- Python’s one of the top programming languages required by employers.
Google Colab
- Colab, or "Colaboratory," allows users to write and execute Python programs in the browser without any configuration.
- It gives users access to GPUs and facilitates easy sharing
- A notebook comprises of cells, containing explanatory text or executable code with its output.
- Code cells use commands like Cmd/Ctrl+Enter to run the cell in place, Shift+Enter to run the cell and move focus to the next cell, and Alt+Enter to run the cell and insert a new code cell below it
Code and Text Cells
- There are additional options for running cells in the Runtime menu.
- Text cells can be edited by double-clicking and use markdown syntax.
- New Code and Text cells can be added using the + CODE and +TEXT buttons.
- Cells can be moved by selecting them and clicking Cell Up or Cell Down in the top toolbar.
First Program
print("Hello World!") # Print your 1st Python String
counter = 100 # Creates an integer variable
miles = 1000.0 # Creates a floating point variable
name = "Zara Ali" # Creates a string variable
print(counter)
print(miles)
print(name)
- The program prints the string "Hello World!", defines an integer variable "counter" with a value of 100, a floating-point variable "miles" with a value of 1000.0, and a string variable "name" with the value "Zara Ali." Finally, prints that counter, miles, and name variables.
Print() Function
print('Welcome to NGN112!') # Use single quotation for printing text
print("Welcome to NGN112!") # May enclose a string in double quotes
## Output: Welcome to NGN112!
print('Welcome', 'to', 'NGN112!') # Printing a List of Items (comma-separated)
## Output: Welcome to NGN112!
print('Sum = ', 1 + 2) # Printing the Value of an Expression (do not use quotations for expression)
## Output: Sum = 3
Variables and Data Types
- Python supports five basic data types, and five compound data types, each with its own operations.
- The Basic Data Types are Integer (int), Float (float), Complex (complex), Boolean (bool), and String (str)
- Compound Data Types are List (list), Tuple (tuple), Dictionary (dict), Set (set), and Range (range)
Data Type Description and Examples
Data Type | Description | Example |
---|---|---|
int | Numeric type for storing integer numbers | -100, -1, 0, 1, 101 |
float | Numeric type for storing float numbers | -110.0, -1.0, 1.0, 101.1 |
complex | Numeric type for storing complex numbers | 2j, 10j |
bool | Logical type for storing True or False | x = False |
str | Text type for storing strings and characters | "Sharjah", "UAE" |
list | Stores list of similar numeric types | x = 2, 3, 5, 10 |
tuple | Stores list of different types | x = ("orange", "banana") |
dict | Stores list of different types | x = "name" : "john", "age" : 36 |
range | Sequence type | x = range(10) |
set | Sets type stores list of different types | x = "cat", "dog" |
Python Operations
- Arithmetic operators (e.g., x + y)
- Assignment operators (e.g., x = y)
- Comparison operators (e.g., x > y)
- Logical operators (e.g., x and y)
- Identity operators (e.g., x is y)
- Membership operators (e.g., x in y)
- Bitwise operators (e.g., x & y)
Variable Names Rules
- Variable names can be as long as you like.
- They can contain both letters and numbers, for example, fall23.
- Variable names cannot begin with a number, for example, 23fall is not allowed.
- Uppercase letters are allowed.
- Keywords cannot be used as variable names.
- The underscore character can appear in a variable name.
- Illegal variable names result in a syntax error.
Assignments
- An assignment statement creates a new variable and gives it a value.
>>> message = 'And now for something completely different' #Assigns a string to a variable
>>> n = 17 #Assigns an integer to a variable
>>> pi = 3.141592653589793 #Assigns a float to a variable
Expression and Statement
- An expression is a combination of values, variables, and operators.
>>> n = 17 # assignment operator
>>> n + 25 # arithmetic operator
>>> 42 # a single value
>>> n # a variable
- Expressions are evaluated by the interpreter
- A statement is a unit of code that has an effect, such as creating a variable or displaying a value.
>>> n = 17 # assignment statement
>>> print(n) #print statement
- Statements are executed by the interpreter
int Type and Operations
- Represents integers (whole numbers) that can be positive or negative.
- Examples x=-100, x=−50, x=0, x=1, x=1000
- Integer literals (1, 82, 256) should have no commas or periods
- Basic integer operations include addition (+), subtraction (-), multiplication (), integer division (//), modulus (%), exponentiation (**), and unary negation (-). x+y, x-y, xy, x//y (result rounded down), x**y (to the power of), -x
Integer Operations
- Operations on integers must yield an integer.
- Integer division (//): 1 // 2 returns 0, and 7 // 2 returns 3.
- Remainder (%): 5 % 2 evaluates to 1 and 8 % 3 evaluates to 2,
- the operator / is not an integer operation in Python 3; it generates fractions.
int Type Operator Examples
- Example code showing the result of division and the modulus operations on the number 12345
x = 12345
print(x % 10) # remainder of division by 10 = 5
print(x % 100) # remainder of division by 100 = 45
print(x % 1000) # remainder of division by 100 = 345
print(x // 10) # regular division = 1234.5
print(x // 10) # floor division = 1234
print(x / 100) # regular division = 123.45
print(x // 100) # floor division = 123
- The following code shows how to access one digit at a time:
## access one digit at a time
x = 12345
print(x % 10) # remainder of division by 10 = 5
x = x // 10 # 12345 // 10 = 1234 (floor division)
print(x % 10) # remainder of division by 10 = 4
x = x // 10 # remainder of division by 10 = 123
print(x % 10) # remainder of division by 10 = 3
x = x // 10 # remainder of division by 10 = 12
print(x % 10) # remainder of division by 10 = 2
x = x // 10 # remainder of division by 10 = 1
print(x % 10) # remainder of division by 10 = 1
- The following code indicates how to determine if a number is even of odd
X = 101
## Find if a number is odd or even
if x % 2 == 0:
print('x = ', x, ' is even')
else:
print('x = ', x, ' is odd')
## outputs x = 101 is odd
Float Type and Operations
- Represents real numbers, distinguished from integers by decimal points
- If a number contains a decimal point, it is a float literal, for example, 12.0
- A number without a decimal is an integer literal, for example, 12
- Float operations include addition (+), subtraction (-), multiplication (*), division (/), exponentiation (**), and unary negation (-)
- Float operations have different division operators, and exponent notation is used for large or small numbers
- Example : 5.0/2.0 evaluates to 2.5
- Exponent notation: 24.3e5 is 24.3 × 10^5 or 2430000, and 48.62e-3 is 48.62 × 10^-3 or 0.04862.
Arithmetic Operations for int and float
Operator | Name | Example |
---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus | x % y |
** | Exponentiation | x ** y |
// | Floor division | x // y |
Precedence of Arithmetic Operations
- The order of operations, from highest to lowest precedence
- () Parenthesis
- ** Exponentiation
- +-, Unary operators
-
- / %, Binary arithmetic
-
- -, Binary arithmetic
- <=> >=, Comparisons
- == !=, Equality relations
- Logical not
- Logial and
- Logical or
- When items have the same precedence in an expression, the one furthest to the left should be performed first.
Boolean Type and its Operations
- Represents logical statements and have values of
True
andFalse
. - Boolean literals are
True
andFalse
with capitalized - Logical operators include
not
,and
, andor
not b # True if b is false, False if b is true
b and c # True if both b and c are true, False otherwise
b or c # True if b is true or c is true, False otherwise
- Comparison operators are used with
int
orfloat
values.
i < j, i <= j, i >= j, i > j
i == j, i != j
- Important notes: x = y is the assignment, while x == y is equality
Boolean Type Examples
- These are tables summarizing the logical operators
| Operator | Description | Example |
| -------- | --------------------------------------------------------- | -------------------- |
| and | Returns
True
if both statements have True |x < 5 and x < 10
| | or | ReturnsTrue
if one of the statements has True |x < 5 or x < 4
| | not | Reverse the result, returns False if the result is true |not(x < 5 and x < 10)
|
A | B | A and B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
A | B | A or B |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
A | not A |
---|---|
True | False |
False | True |
Bool Type Equality and Comparison Operators
Operator | Name | Example |
---|---|---|
== | Equal | x == y |
!= | Not equal | x != y |
> | Greater than | x> y |
< | Less than | x< y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Evaluate Boolean Expressions
rst = 22>-1 and 10!=(-10) or not 5<=0
rst = (22>-1) and 10!=-10 or not (5<=0)
rst = (True) and 10!=-10 or not (False)
rst = True and (10!=-10) or not False
rst = True and (True) or not False
rst = True and True or (not False)
rst = True and True or (True)
rst = (True and True) or True
rst = True or True
rst = True
str Type and its Operations
- Represents text and its values are any sequence of characters
- str operations are string catenations that apply to strings
- String literals are a sequence of characters in quotes
- Double quotes example str = "abcex3$g<8&" or str = "Hello World!"
- Single quotes example str = 'Hello World!'
'ab' + 'cd' #result: 'abcd'
'ab' + 2 #results in an error that a string with a numeric value cannot be contacted
String Access By indexing
- String content are indexed
- The first character has index 0
- The second character has index 1
- Square brackets are used to access a string at a given index
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0]) # character at index 0
print ("var2[1:5]: ", var2[1:5]) # range of characters from index 1 to (5-1)
#code output
var1[0]: H
var2[1:5]: ytho
- str Updated String example
var1 = 'Hello World!'
print("Updated String :-", var1[:6] + "Python") #[:6] is the same as [0:6]
## result: Updated String :- Hello Python
Types Conversion and Casting
- To find the type of a variable use the
type
function:
x = 1.5
print('Type of x is:', type(x)) # result: Type of x is: <class 'float'>
#To convert
int(15.3) #converts value 15.3 to type integer (value now 15)
float(8) #converts value 8 to type float (value now 8.0)
5 / 2.0 #evaluates to 2.5 (automatically casts 5 to float prior to division)
float(int(12.6)) #evaluates to 12.0
- Explicit conversion is also called "casting”
Input() Function
- The function
input()
, allows for user-defined variables - Returns a string by default.
- However, it can be converted back to an integer or float by the functions
int()
orfloat()
Code Example
## Example showing that the Input Function can returns a string
#and how the returns are different by casting for input
name = input('Enter a name: ')
print('The name is: ', name)
x= int(input("Enter an int value for x: ")) # enter 100
y = int(input("Enter an int value for y: ")) # enter 200
#The "int" converts string to type int
print ('x + y = ', x+y) # result "300"
Lists Type and Its Operations
- Type
list
stores a collection of data values. - Lists are created using square brackets.
- List items are ordered, changeable, and duplicate values are allowed. -List items are indexed where the first item has index [0]
List1 = [8, 3, 5, 5, 10, 6, 24]
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0]) #result: physics
print ("list2[1:5]: ", list2[1:5]) #result: [2, 3, 4, 5]
- Lists uses square bracket notation [ ], for slicing along with the index or indices to obtain that index or indices
List Method Example
Method | Description |
---|---|
L1.append(value) |
Adds an element at the end of the list |
L1.clear() |
Removes all the elements from the list |
L2=L1.copy() |
Returns a copy of the list |
rst=L1.count(value) |
Returns the number of elements with the specified value |
L1.extend(anotherList) |
Add the elements of a list (or any iterable), to the end of the current list |
Idx=L1.index(value) |
Returns the index of the first element with the specified value |
L1.insert(index, value) |
Adds an element at the specified position |
value = L1.pop(index) |
Removes the element at the specified position |
L1.remove(value) |
Removes the first item with the specified value |
L1.reverse() |
Reverses the order of the list |
L1.sort() |
Sorts the list. All items need to be either strings or numbers, numbers will be ordered largest to smallest |
Tuple
- Type tuple represents a collection of variables
- Tuples uses is created using parenthesis ()
- Tuples are ordered, unchangeable, and allow duplicate values.
- Can access elements of a tuple by using [] like lists
fruit = ("Orange", "banana", "orange")
print(fruit[1]) # prints banana
More on Tuples
- Tuples are unchangeable
- Tuple individual variables cannot be modified
tuple1[0] = 100 #results in an error
- List methods are similar to methods for lists except that it cannot reverse or rearrange, examples include: Returns the number of times a specified value occurs in a table Returns the index of a value in a table
cnt = myTuple.count(value)
idx = myTuple.index(value)
Dictionary Type and Operations
- A dictionary represents a collection of variables.
- A dictionary associates keys with values.
- Dictionaries are
created
using square curl parenthesis { }. - Dictionary items are ordered, changeable, and do not allow duplicate key values.
roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X': 100}
print(roman_numerals['V']) # prints 5
- Note that we always use [] to access elements (in lists, tuples and dict)
- However, in dict type, to access a 'value' you use roman numerals[key]
- Example of this is roman_numerals[['I'] not roman_numerals[0]
Values in Dictionaries
- Dictionaries can contain tuples and lists
grade_book = {
'Ali': [92, 85, 100],
'Layla': [83, 95, 79],
'Hassan': [91, 89, 82],
'Huda': [97, 91, 92]
}
#Outputs: {'Ali': [92, 85, 100], 'Layla': , 'Huda': [97, 91, 92]}
grade_book = {
'Ali': (92, 85, 100),
'Layla': (83, 95, 79),
'Hassan': (91, 89, 82),
'Huda': (97, 91, 92)
}
#Outputs:{'Ali': [92, 85, 100], 'Layla': , 'Huda': [97, 91, 92]}
#Access elements by 'Hassan'
print(grade_book['Hassan'])#Output: (91, 89, 82)
Dictionary methods
Method | Description |
---|---|
d1.clear() | Removes all the elements from the dictionary |
d1.copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and value |
d1.get(key) | Returns the value of the specified key |
d1.items() | Returns a list containing a tuple for each key value pair |
d1.keys() | Returns a dict-keys containing the dictionary's keys |
value = d1.pop(key) | Removes the element with the specified key |
d1.popitem() | Removes the last inserted key-value pair |
d1.setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
d1.update({key: value}) | Updates the dictionary with the specified key-value pairs |
d1.values() | Returns a dict-values of all the values in the dictionary |
Dictionary Update
and Insert
Function
grade_book = {
'Ali': [92, 85, 100],
'Layla': [83, 95, 79],
'Hassan': [91, 89, 82],
'Huda': [97, 91, 92]
}
print("Update Hassan's grades...")
grade_book.update({'Hassan': [100, 99, 99]})
print("Hassan's grades are: ", grade_book['Hassan'])
print() # an empty line
print('If you update a non-existing key then a new record is added...')
grade_book.update({'Tuffaha': [65, 67, 72]})
print(grade_book)
- Key can also be inserted by creating a new item:
grade_book["key"] = 10
Sets Type and Operations
- Type
set
represents a set of variables. - The
set
is created using square curl parenthesis { }. - The set items are unordered, unindexed, mutable (add or remove elements), and do not allow duplicate values.
- The element values are unchangeable.
x = {"cat", "dog", "horse"} #Set Example
print(x[0])# results in error
TypeError
: 'set' object is not subscriptable
Type Set Methods
Method | Description |
---|---|
add() | Adds an elements to the set |
clear() | Removes all the set from the function |
copy() | Returns a copy of the set |
difference() | Returns a Set containing the difference between two or more function |
difference update() | |
discard() | Remove the specified item |
intersection() | Returns a set , that is the intersction of two or more sets |
isdisjoint() | If none of the items are present in both sets, the method will return True, other wise it results in false |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
remove() | Removes the specified element |
pop() | Removes the an element from the set |
symmetric difference() | Returns Return a set with the symmetric differences of two sets |
symmetric difference update() | inserts Return a set with the symmetric differences of two sets inserts the symmetric differences from this set and another |
update() | Adds elements from a set to another set |
Identity Operators
- Identity operators are used to compare the objects if they are the same object with the same memory location.
Operator | Description | Example |
---|---|---|
is | Returns True if both variables are the same object |
x is y |
is not | Returns True if both variables are not the same object |
x is not y |
- Objects exclude integers and strings
Identity Examples
## Create two variables with the same value
x = [1, 2, 3]
y = [1, 2, 3]
## Using the identity operator "is" to compare the variables
print(x is y) # Output: False (x and y are two different objects in memory, yet with the same content)
## Create another variable referencing the same object as x
Z = X
## Using the identity operator "is" to compare z with x and y
print(x is z) # Output: True (x and z are the same object in memory)
print(y is z) # Output: False (y and z are different objects in memory)
Membership Operators
- Returns where a variable is the same based off of the description provided, or returns false
Operator | Description | Example |
---|---|---|
in | Returns if collection has variable mentioned | x in y |
not in | Returns if the variable is not mentioned | x not in y |
- Collections is set as list, tuples, strings, sets, and dictionaries
Membership Examples
#Example with a list
fruits = [‘apple’, ‘banana’, ‘orange’, ‘grape’]
print('apple' in fruits) # Output: True (since ‘apple’ is in the list)
print('kiwi' in fruits) # Output: False (since ‘kiwi’ is not in the list)``
message= ‘Hello’
print('Hello' in message) #output is true
grade_book = {
‘ali’:[1,2,3,4],
.
}
print(‘ali’ in grade_book) #output is true
Python Keywords
- Python has 35 keywords (reserved words) that cannot be used as variable names, function names or identifier names
Keyword | Keyword | Keyword |
---|---|---|
False | def | if |
Raise | del | import |
None | elif | in |
Return | else | Is |
Try | except | lambda |
While | Finally | with |
And | Global | Yield |
As | Not | Await |
Assert | or | _ |
pass | _ |
Math Module
- Built in modules can perform math operations
import math #code to import math library in python
Methods | Description |
---|---|
math.ceil() | Round number up |
Pow() | X = y |
Variable and Outputs
Constant | Description |
---|---|
“Math.e” | Returns Euler’s number (2.7182…) |
“Math.inf” | Returns a floating-point positive infinity |
“Math.nan” | |
Returns a floating-point NaN (Not a Number) value | |
“Math.PI” | Returns a math constant |
math.tau | returns tau 6.2831… |
Function Examples```
#Example importing Math
#Ex1
import math
x=2.5
y=5
rst = math.pow(x,y)
print('x^y = ', rst)
## result is 97.65
#Ex2
import math
z = 100
rst = math.sqrt(z)
print('sqrt(z) = ', rst)
## result is z=10
##Ex3
import math
r=3.4
area = math.pi * math.pow(r,2)
print('area = ', area)
Errors and Debugging
- 3 kinds of errors that arise from programming syntax, runtime and semantics
- It is important to distinguish what error arises to debug software more quickly
- A Syntax error are mistakes made when constructing a sentence.
mylist = [10,20,30]
print ('This will cause a syntax error: ')
avg = sum(mylist) divideBy 3
print('avg = ', avg)
#^^^^ syntax error : “Divide BY” is not a function
- Runtime: occurs when runtime comes across error
mylist = [10,20,30]
print ('This will cause a runtime error: ')
avg = sum(mylist) / 0
print('avg = ',
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.