0% found this document useful (0 votes)
2 views4 pages

Cheat Sheet For Sharing

The document provides an overview of programming concepts including flowcharts, data structures (lists, tuples, dictionaries, arrays, sets), control flow (if-else statements, loops), and functions. It also covers file handling, logical operators, and various built-in functions in Python. Additionally, it includes examples of using libraries like Numpy and Pandas for data manipulation and mathematical operations.

Uploaded by

ashmalshahzad415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Cheat Sheet For Sharing

The document provides an overview of programming concepts including flowcharts, data structures (lists, tuples, dictionaries, arrays, sets), control flow (if-else statements, loops), and functions. It also covers file handling, logical operators, and various built-in functions in Python. Additionally, it includes examples of using libraries like Numpy and Pandas for data manipulation and mathematical operations.

Uploaded by

ashmalshahzad415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Flowchart Create a List: File Writing

Flowcharts are visual diagrams to represent logic using shapes. list1 = [1, 2, 3, 4] To write to a file:
Start/End → Oval Accessing List Elements: with open('file.txt', 'w') as f:
Decision → Diamond print(list1[1]) # Output: 2 f.write("Hello, World!")
Process/Action → Rectangle List Methods: Important Functions
Arrows → Flow direction list1.append(5) # Adds 5 at the end General Built-in Functions
list1.insert(1, 10) # Adds 10 at index 1 min() → Returns the smallest value.
list1.pop(1) # Removes element at index 1 nums = [5, 10, 3, 7]
del list1[1] # Deletes element at index 1 print(min(nums)) # Output: 3
list1.remove(3) # Removes first occurrence of 3 max() → Returns the largest value.
2. Tuples (Ordered, immutable) print(max(nums)) # Output: 10
Create a Tuple: sum() → Returns the sum of elements.
tuple1 = (1, 2, 3)
print(sum(nums)) # Output: 25
Accessing Tuple Elements:
Pseudo Code len() → Returns the length of a list, string, or any iterable.
print(tuple1[0]) # Output: 1
Basic structured programming logic in plain language: print(len(nums)) # Output: 4
Concatenating Tuples:
START print(len("Hello")) # Output: 5
tuple1 += (4, 5)
INPUT number print(tuple1) # Output: (1, 2, 3, 4, 5) abs() → Returns the absolute value.
IF number % 2 == 0 THEN 3. Dictionary (Key-Value pairs) num = -10
PRINT "Even Number" my_dict = {'name': 'Ashmal', 'age': 25} print(abs(num)) # Output: 10
ELSE Operations: round() → Rounds a number to the nearest integer (or
PRINT "Odd Number" print(dict1["name"]) #value of key "name" specified decimal places).
ENDIF dict1["city"] = "New York" #Adds/updates key "city" pi = 3.14159
END del dict1["name"] # deletes key-value pair of key "name" print(round(pi, 2)) # Output: 3.14
Logical Operators for key, value in dict1.items(): sorted() → Returns a sorted list.
Logical operators are used to combine conditional statements. print(key, value) # prints all key-val pairs nums = [5, 1, 7, 3]
Logical operators used in conditions: print(dict1.keys()) # keys only print(sorted(nums)) # Output: [1, 3, 5, 7]
and → Logical AND print(dict1.values()) #values only type() → Returns the type of a variable.
or → Logical OR print(dict1.items()) #key-value pairs print(type(nums)) # Output: <class 'list'>
not → Logical NOT Iterating through a Dictionary: String Functions
a = Trueless for key, value in dict1.items(): lower() → Converts string to lowercase.
b = False print(key, value) text = "HELLO"
print(a and b) # False 4. Arrays (Similar to lists, better for large numeric data) print(text.lower()) # Output: hello
print(a or b) # True Using array library: upper() → Converts string to uppercase.
print(not a) # False import array print(text.upper()) # Output: HELLO
Print forms: arr = array.array('i', [1, 2, 3]) # 'i' for integers
strip() → Removes leading/trailing spaces.
print(f"My age is {age}") print(arr[0])
text = " hello "
print(“My age is ”, age) 5. Set (Unique unordered elements)
print(text.strip()) # Output: hello
Boolean Variables Create a Set:
split() → Splits string into a list.
Boolean variables can be used to represent logical values. set1 = {1, 2, 3}
text = "apple,banana,cherry"
Boolean variables store True or False. Set Operations:
print(text.split(',')) # Output: ['apple', 'banana', 'cherry']
is_valid = True set1.add(4) # Adds value 4
set2 = {3, 4, 5} replace() → Replaces parts of a string.
is_ready = False
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5} combines all text = "I like apples"
print(type(is_valid)) # Output: <class 'bool'>
elements print(text.replace("apples", "bananas")) # Output: I like bananas
If-Else Statement
print(set1.intersection(set2)) #Output: {3, 4} shows common List Functions
Conditional statements to make decisions based on conditions.
elements append() → Adds an item to the end of the list.
num = 10
if num > 0: print(set1.difference(set2)) # Output: {1, 2} Gets only set 1 fruits = ['apple', 'banana']
print("Positive") elements fruits.append('cherry')
elif num == 0: Libraries print(fruits) # Output: ['apple', 'banana', 'cherry']
print("Zero") Numpy extend() → Adds multiple items to the list.
else: Importing Numpy: fruits.extend(['orange', 'grape'])
print("Negative") import numpy as np print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange', 'grape']
For Loop Creating Arrays: pop() → Removes and returns an item by index.
Used for iteration over sequences (list, range, etc.). arr = np.array([1, 2, 3]) fruits.pop(1) # Removes 'banana'
#Range-based loop: print(arr) print(fruits) # Output: ['apple', 'cherry', 'orange', 'grape']
for i in range(5): Slicing and Indexing: remove() → Removes an item by value.
print(i) # 0, 1, 2, 3, 4 1D Array: arr = np.array([10, 20, 30, 40]) fruits.remove('cherry')
#IIterating over a list: 2D Array: arr = np.array([[1, 2], [3, 4]]) print(fruits) # Output: ['apple', 'orange', 'grape']
fruits = ['apple', 'banana', 'cherry'] arr1 + arr2 # Addition
index() → Returns the index of the first matching value.
for fruit in fruits: arr1 * arr2 # Multiplication
print(fruits.index('orange')) # Output: 1
print(fruit) np.mean(arr) # Mean
count() → Counts occurrences of a value.
Range Function np.sum(arr) # Sum
np.max(arr) # Maximum nums = [1, 2, 2, 3]
The range() function generates a sequence of numbers, often
np.min(arr) # Minimum print(nums.count(2)) # Output: 2
used in loops.
arr.reshape(2, 3) # Change shape to 2x3 reverse() → Reverses the list.
Basic range():
INDEXING: nums.reverse()
for num in range(1, 6):
arr[1] # Access element at index 1 print(nums) # Output: [3, 2, 2, 1]
print(num) # Output: 1, 2, 3, 4, 5
Reverse range(): arr[1, 2] # Access element in row 1, column 2 sort() → Sorts the list in ascending order.
for num in range(10, 0, -1): # Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 arr[:, 1] # Access all rows, column 1 nums.sort()
print(num) SLICING: print(nums) # Output: [1, 2, 2, 3]
While Loop sequence[start:end:step] Dictionary Functions
Repeats until the condition is false: sequence[1:4] # Items from index 1 to 3 keys() → Returns all keys.
count = 0 sequence[:4] # Items from the beginning to index 3 my_dict = {'a': 1, 'b': 2}
while count < 5: sequence[2:] # Items from index 2 to the end print(my_dict.keys()) # Output: dict_keys(['a', 'b'])
print(count) sequence[::2] # Every second element values() → Returns all values.
count += 1 sequence[::-1] # Reversed sequence print(my_dict.values()) # Output: dict_values([1, 2])
Nested Loops Pandas items() → Returns key-value pairs as tuples.
Loops inside another loop: Importing Pandas:
print(my_dict.items()) # Output: dict_items([('a', 1), ('b', 2)])
for i in range(3): import pandas as pd
get() → Retrieves a value by key.
for j in range(2): Creating a DataFrame:
print(my_dict.get('a')) # Output: 1
print(f"i={i}, j={j}") From Dictionary:
update() → Updates dictionary with key-value pairs.
Functions data = {"A": [1, 2, 3], "B": [4, 5, 6]}
data = pd.DataFrame(data) my_dict.update({'c': 3})
Reusable blocks of code:
From CSV: print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
def greet(name):
data = pd.read_csv("file.csv") pop() → Removes a key-value pair by key.
return f"Hello, {name}!"
Accessing Columns: my_dict.pop('b')
print(greet("Ashmal"))
print(df['Name']) # Access 'Name' column print(my_dict) # Output: {'a': 1, 'c': 3}
Functions
Matplotlib Math Functions
Void Function: Does not return any value.
def greet(): Importing Matplotlib: math.sqrt() → Square root.
print("Hello!") import matplotlib.pyplot as plt math.pow() → Power of a number.
greet() # Output: Hello! Basic Plot: math.floor() → Rounds down to the nearest integer.
Value-Returning Function: Returns a value. x = [1, 2, 3, 4] math.ceil() → Rounds up to the nearest integer.
def add(a, b): y = [10, 20, 25, 30]
import math
return a + b plt.plot(x, y)
print(math.sqrt(16)) # Output: 4.0
print(add(10, 5)) # Output: 15 plt.title("Line Plot")
print(math.pow(2, 3)) # Output: 8.0
Function with Multiple Parameters: plt.show()
print(math.floor(3.7)) # Output: 3
def multiply(a, b, c): File Reading
print(math.ceil(3.7)) # Output: 4
return a * b * c To read files:
Numpy Functions
print(multiply(2, 3, 4)) # Output: 24 with open('file.txt', 'r') as f:
np.mean() → Average value.
Data Structures content = f.read()
print(content) np.median() → Median value.
1. Lists (Ordered, mutable)
np.std() → Standard deviation. print(numbers[1:4]) # Output: (20, 30, 40) *****
np.sum() → Sum of array elements. # Reverse the Tuple *****
print(numbers[::-1]) # Output: (50, 40, 30, 20, 10) *****
np.max() & np.min() → Max and min in array.
4. Slicing a Numpy Array 6. Hollow Square
import numpy as np
import numpy as np rows = 5
arr = np.array([1, 2, 3, 4, 5])
arr = np.array([0, 1, 2, 3, 4, 5]) for i in range(rows):
print(np.mean(arr)) # Output: 3.0
# Basic Slicing if i == 0 or i == rows - 1:
print(np.median(arr)) # Output: 3.0
print(arr[1:4]) # Output: [1 2 3] print("*" * rows)
print(np.std(arr)) # Output: 1.414
# Step Size else:
print(np.sum(arr)) # Output: 15
print(arr[::2]) # Output: [0 2 4] print("*" + " " * (rows - 2) + "*")
print(np.max(arr)) # Output: 5
# Reverse the Array Output:
print(np.min(arr)) # Output: 1
print(arr[::-1]) # Output: [5 4 3 2 1 0] *****
Pandas Functions
Advanced Slicing (2D Numpy Array) * *
df.describe() → Summary statistics.
import numpy as np * *
df.head() → Displays first rows. matrix = np.array([[1, 2, 3], * *
df.tail() → Displays last rows. [4, 5, 6], *****
df.info() → Info about data types and nulls. [7, 8, 9]]) 7. Hollow Triangle
df['column'].mean() → Column average. # Access specific rows/columns rows = 5
import pandas as pd print(matrix[0, :]) # Output: [1 2 3] (1st row) for i in range(1, rows + 1):
data = {'A': [1, 2, 3], 'B': [4, 5, 6]} print(matrix[:, 1]) # Output: [2 5 8] (2nd column) if i == 1 or i == rows:
df = pd.DataFrame(data) # Subset of matrix print("*" * i)
print(df.describe()) # Summary statistics print(matrix[0:2, 1:3]) # Output: [[2 3], [5 6]] else:
print(df.head()) # First rows print("*" + " " * (i - 2) + "*")
print(df['A'].mean()) # Average of column A Action Syntax Example Output Output:
Indexing in Python *
Indexing is used to access individual elements in sequences **
Access 1st sequence[0] nums[0] 1
like lists, strings, tuples, and arrays. element **
Indexing Rules * *
*****
Index starts at 0: The first element has index 0, the second Access sequence[-1] nums[-1] 6
8. Pyramid
element has index 1, and so on. last
element rows = 5
Negative indexing: You can access elements from the end using
for i in range(1, rows + 1):
negative indices. -1 refers to the last element. print(" " * (rows - i) + "*" * i)
Out of range error: Accessing an index outside the sequence Slice first sequence[:3] nums[:3] [1, 2, 3] Output:
range raises an IndexError. 3
*
elements
Indexing Examples **
1. Indexing in a List ***
fruits = ['apple', 'banana', 'cherry', 'date'] Slice all sequence[2:] nums[2:] [3, 4, 5, 6] ****
# Positive Indexing except first
*****
2
print(fruits[0]) # Output: apple 9. Hollow Diamond
print(fruits[2]) # Output: cherry rows = 5
# Negative Indexing Reverse sequence[::-1] nums[::-1] [6, 5, 4, 3, 2, 1] # Upper half
print(fruits[-1]) # Output: date the for i in range(1, rows + 1):
sequence
print(fruits[-3]) # Output: banana if i == 1:
2. Indexing in a String print(" " * (rows - i) + "*")
text = "hello" Every 2nd sequence[::2] nums[::2] [1, 3, 5] else:
# Positive Indexing element print(" " * (rows - i) + "*" + " " * (2 * i - 3) + "*")
print(text[0]) # Output: h # Lower half
Right-Angled Triangle
print(text[4]) # Output: o for i in range(rows - 1, 0, -1):
rows = 5
# Negative Indexing if i == 1:
for i in range(1, rows + 1):
print(text[-1]) # Output: o print(" " * (rows - i) + "*")
print("*" * i)
print(text[-3]) # Output: l else:
Output:
3. Indexing in a Tuple print(" " * (rows - i) + "*" + " " * (2 * i - 3) + "*")
*
numbers = (10, 20, 30, 40) Output:
**
print(numbers[1]) # Output: 20 *
***
print(numbers[-2]) # Output: 30 **
****
4. Indexing in a Numpy Array * *
*****
import numpy as np * *
2. Inverted Right-Angled Triangle
arr = np.array([10, 20, 30, 40]) * *
rows = 5
print(arr[0]) # Output: 10 * *
for i in range(rows, 0, -1):
print(arr[-1]) # Output: 40 * *
print("*" * i)
Slicing in Python **
Output:
Slicing is used to access a subset of elements from a sequence *
*****
(like list, string, tuple, or array). 10. Number Pyramid
****
Slicing Syntax rows = 5
***
Sequence[start:stop:step] for i in range(1, rows + 1):
**
start: Starting index (inclusive). Default is 0. print(" " * (rows - i) + " ".join(str(x) for x in range(1, i + 1)))
*
stop: Ending index (exclusive). Default is the length of the Output:
3. Equilateral Triangle
sequence. 1
rows = 5
step: Step size (how many indices to skip). Default is 1. 12
for i in range(1, rows + 1):
Slicing Rules 123
print(" " * (rows - i) + "*" * (2 * i - 1))
1234
start is inclusive and stop is exclusive. Output:
12345
Omitting start starts the slice at the beginning. *
11. Checkerboard Pattern
Omitting stop includes elements until the end. ***
rows = 6
*****
Negative step slices the sequence in reverse order. cols = 6
*******
Omitting step means step size is 1. *********
for i in range(rows):
Slicing Examples for j in range(cols):
4. Diamond
1. Slicing a List if (i + j) % 2 == 0:
rows = 5
numbers = [0, 1, 2, 3, 4, 5, 6] print("*", end="")
# Upper half
# Basic Slicing else:
for i in range(1, rows + 1):
print(numbers[1:5]) # Output: [1, 2, 3, 4] print(" ", end="")
print(" " * (rows - i) + "*" * (2 * i - 1))
# Omitting start or stop print()
# Lower half
print(numbers[:4]) # Output: [0, 1, 2, 3] (Start from 0) Output:
for i in range(rows - 1, 0, -1):
print(numbers[3:]) # Output: [3, 4, 5, 6] (Until end) ****
print(" " * (rows - i) + "*" * (2 * i - 1))
# Step Size ***
Output:
print(numbers[::2]) # Output: [0, 2, 4, 6] (Every 2nd element) ****
*
# Negative Step (Reverse) ***
***
print(numbers[::-1]) # Output: [6, 5, 4, 3, 2, 1, 0] ****
*****
2. Slicing a String ***
*******
text = "PythonProgramming" 12. Arrow
*********
# Basic Slicing rows = 5
*******
print(text[0:6]) # Output: Python # Upper half
*****
# Omitting start or stop for i in range(1, rows + 1):
***
print(text[:6]) # Output: Python print("*" * i)
*
print(text[6:]) # Output: Programming # Lower half
5. Square
# Step Size for i in range(rows - 1, 0, -1):
rows = 5
print(text[::2]) # Output: PtoPormig (Every 2nd character) print("*" * i)
for i in range(rows):
# Negative Step (Reverse) Output:
print("*" * rows)
print(text[::-1]) # Output: gnimmargorPnohtyP *
Output:
3. Slicing a Tuple **
*****
numbers = (10, 20, 30, 40, 50) ***
*****
# Basic Slicing ****
***** 7. Membership Operators 13. \xhh - Hexadecimal Character
**** Check if an element is in a sequence in Represents a character in hexadecimal format.
*** print('a' in 'apple') # Output: True print("\x48\x65\x6C\x6C\x6F") # Output: Hello
** not in 14. Raw Strings (r"" or R"")
* print('x' not in 'apple') # Output: True Disables escape sequences, printing them as literal text.
13. X Pattern 8. Identity Operators print(r"Hello\nWorld") # Output: Hello\nWorld
rows = 5 Check if two variables point to the same object is 15. \N{name} - Named Unicode
for i in range(rows): x = [1, 2, 3]
Inserts a named Unicode character.
for j in range(rows): y=x
print("\N{BLACK HEART SUIT}") # Output: ♥
if i == j or i + j == rows - 1: print(x is y) # Output: True
print("*", end="") is not Escape Meaning Example Output
else: x = [1, 2, 3] Sequence
print(" ", end="") y = [1, 2, 3]
print() print(x is not y) # Output: True \n New line print("Hello\nWorld") Hello
Output: 9. String Formatting Operators World
* * Combine or format strings.
** Modulus Formatting: %
\t Horizontal print("Hello\tWorld") Hello (tab
* print("Age: %d" % 25) # Output: Age: 25 Tab space)Wo
** f-Strings (Python 3.6+): f"" rld
* * age = 25
14. Heart print(f"Age: {age}") # Output: Age: 25 \\ Backslash print("\\") \
for row in range(6): str.format()
for col in range(7): print("Age: {}".format(25)) # Output: Age: 25
if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) \’ Single print('It\'s') It’s
10. Ternary Operators
or (row - col == 2) or (row + col == 8): Quote
Conditional expressions inside print().
print("*", end="")
x = 10
else: \” Double print("\"Hello\"") “Hello”
y = 20
print(" ", end="") Quote
print("x is greater" if x > y else "y is greater") # Output: y is
print()
greater
Output: \r Carriage print("Hello\rWorld") World
11. Assignment Operators
*** *** Return(rew
Perform assignments while printing values.
* * * rite)
x=5
* *
x += 10
* * \b Backspace print("Hell\bWorld") HellWorld
print(x) # Output: 15
* *
1. \n - New Line
**
* Inserts a new line in the output. \f Form Feed print("Hello\fWorld") Hello\fWor
print("Hello\nWorld") ld
Experiment Further:
Output: (system-d
Modify characters (e.g., use # or numbers). ependent)
Hello
Adjust rows and columns.
World
Combine shapes for creative patterns
2. \t - Horizontal Tab \v Vertical print("Hello\vWorld") Hello
1. String Concatenation: + Tab World
Inserts a horizontal tab space.
Used to combine strings.
print("Hello\tWorld")
print("Hello" + " World!") # Output: Hello World!
Output: \a Alert (Bell) print("\a") (Beep
2. String Repetition: * sound)
Hello World
Used to repeat strings.
3. \\ - Backslash
print("Hello " * 3) # Output: Hello Hello Hello
Prints a single backslash (\). \0 Null print("Hello\0World") Hello
3. Arithmetic Operators
print("This is a backslash: \\") Character World
Used to perform calculations directly in the print() statement.
Output:
Addition: +
This is a backslash: \ \uxxxx Unicode print("\u2602") ☂
print(10 + 5) # Output: 15 (16-bit)
4. \' - Single Quote
Subtraction: -
😀
Prints a single quote (') in a string enclosed by single quotes.
print(10 - 5) # Output: 5
print('It\'s a beautiful day') \uxxxxxxx Unicode print("\U0001F600")
Multiplication: * x (32-bit)
Output:
print(10 * 5) # Output: 50
It's a beautiful day
Division: /
5. \" - Double Quote \xhh Hexadeci print("\x48") H
print(10 / 5) # Output: 2.0 mal
Prints a double quote (") in a string enclosed by double quotes.
Floor Division: // Character
print("She said, \"Hello!\"")
print(10 // 3) # Output: 3
Output:
Modulus: % She said, "Hello!" \n{name} Named print("\N{BLACK ♥
print(10 % 3) # Output: 1 6. \r - Carriage Return Unicode HEART}")
Exponentiation: ** Character
Moves the cursor to the beginning of the current line. Subsequent
print(2 ** 3) # Output: 8 text overwrites the line. 1. Why do we use lists, tuples, and dictionaries? 1. Lists: A
4. Comparison Operators print("Hello\rWorld") list is a data structure in Python used to store an ordered and
Used to compare values, resulting in a True or False output. Output: mutable collection of items. It allows duplication and can store
Greater Than: > World elements of different data types. For example, [1, 2,
print(10 > 5) # Output: True 7. \b - Backspace
"apple"] is a list containing integers and a string. 2.Tuples:
Less Than: < Removes the previous character.
tuple is a data structure in Python used to store an ordered and
print(10 < 5) # Output: False print("Hello\bWorld")
immutable collection of items. It is useful for ensuring that data
Greater Than or Equal To: >= Output:
cannot be modified after creation. For example, (1, 2,
print(10 >= 10) # Output: True HellWorld
"apple") is a tuple.
Less Than or Equal To: <= 8. \f - Form Feed
Dictionaries: A dictionary is a data structure in Python that
print(5 <= 10) # Output: True Moves the cursor to the next page. Not commonly used, but its
stores data in key-value pairs. It allows quick lookups, and keys
Equality: == behavior depends on the system.
must be unique, while values can be of any type. For example,
print(10 == 10) # Output: True print("Hello\fWorld")
Output: {"name": "Alice", "age": 25} is a dictionary.
Inequality: != 2. What is the difference between global and local variables in
HelloWorld
print(10 != 5) # Output: True Functions?
5. Logical Operators 9. \v - Vertical Tab
Global Variables: Variables declared outside any function are
Combine multiple conditions. Moves the cursor down to the next vertical tab position.
called global variables. They are accessible throughout the
AND: and print("Hello\vWorld")
program, including within functions.
Output:
print(10 > 5 and 5 > 3) # Output: True Local Variables: Variables declared inside a function are called
Hello
OR: or local variables. They are only accessible within the function in
World
print(10 > 5 or 5 < 3) # Output: True which are defined and are destroyed once the function ends.
10. \a - Bell/Alert
NOT: not 3. In Pandas, what is the purpose of the fillna function?
Produces a beep sound if the system supports it.
print(not(10 > 5)) # Output: False The fillna function in Pandas is used to handle missing values
print("\a")
6. Bitwise Operators (NaN) in a DataFrame or Series. It replaces missing values with
Output: (Produces a beep sound)
Perform bit-level operations. a specified value or fills them using a method such as forward-fill
11. \0 - Null Character
AND: & or backward-fill. This helps in ensuring data completeness for
Represents the null character (ASCII value 0). Often used in
print(5 & 3) # Output: 1 analysis.
low-level programming.
OR: | 4. How does a computer store data?
print("Hello\0World")
print(5 | 3) # Output: 7 A computer’s memory is divided into tiny storage locations known
Output:
XOR: ^ as bytes. One byte is only enough memory to store a letter of the
Hello World
print(5 ^ 3) # Output: 6 alphabet or a small number. Each byte is divided into eight
12. Unicode Characters
NOT: ~ smaller storage locations known as bits. When a character is
\u for 16-bit Unicode, \U for 32-bit Unicode.
print(~5) # Output: -6 stored in memory, it converts into a numeric

😀
print("\u2602") # Unicode for umbrella ☂
Code. The numeric code is then stored in memory as a binary
Left Shift: << print("\U0001F600") # Unicode for grinning face
number A computer stores data in binary format (0s and 1s
print(5 << 1) # Output: 10 Output:
using different storage devices: Primary Memory (RAM):
Right Shift: >>
😀

Temporary storage for fast access by the CPU. Secondary
print(5 >> 1) # Output: 2
Storage (Hard Drives, SSDs): Long-term data storage.
Cache and Registers: File Handling: Python provides built-in functions to read and
High-speed storage in the CPU for immediate processing. write files.
Data is organized in files or memory locations, depending on the open(): Opens a file, returns a file object.
context. read(): Reads the contents of a file.
What is the difference between Machine Language and write(): Writes data to a file.
Assembly Language Machine Language: A low-level language Dictionaries: A collection of key-value pairs. Keys are unique,
directly understood by the computer. It uses binary code and is and values can be of any data type.
hardware-specific. For example, 11010101 represents Example:
machine-level instructions. person = {"name": "John", "age": 30}
Assembly Language: A low-level programming Classes and Objects: Python supports object-oriented
language with human-readable mnemonics. It is converted into programming (OOP). A class is a blueprint for creating objects.
machine language using an assembler. For example, MOV A, B Class: A definition of an object type.
is an assembly instruction. Object: An instance of a class.
Low Level is close to machine language. Example:
A high-level language allows you to create powerful and complex class Person:
programs without knowing how the CPU works and without def __init__(self, name, age):
writing large numbers of low-level instructions. Most high-level self.name = name
languages use words that are easy to understand. self.age = age
Program: Set of instructions that a computer follows to perform a person1 = Person("Alice", 25)
task. Programs are commonly referred to as software. Numpy: A powerful library for numerical computing. It provides
Syntax is a set of rules that must be strictly followed when writing support for arrays, matrices, and many mathematical functions.
a program. Example:
Python: A high-level, interpreted programming language known import numpy as np
for its readability, simplicity, and versatility. It supports multiple array = np.array([1, 2, 3, 4])
programming paradigms, including procedural, object-oriented,
Matplotlib: A plotting library for creating static, animated, and
and functional programming.
interactive visualizations in Python.
Interactive mode: The interpreter waits for you to type Python
Example:
statements on the keyboard. Once you type a statement, the import matplotlib.pyplot as plt
interpreter executes it.
plt.plot([1, 2, 3], [4, 5, 6])
print('Python programming is fun!')
plt.show()
Output: Python programming is fun!
Script mode: The interpreter reads the contents of a file that Seaborn: A data visualization library based on Matplotlib, which
contains Python statements. makes it easier to generate attractive and informative statistical
Variable: A named location used to store data in memory. graphics.
Variables in Python do not require explicit declaration of type and Example:
import seaborn as sns
can store values of any data type.
Data Types: In Python, data types define the kind of value a sns.scatterplot(x=[1, 2, 3], y=[4, 5, 6])
variables can hold. Common types include: Pandas: A library for data manipulation and analysis, offering
int: Integer numbers (e.g., 5, -3) data structures like Series and DataFrame. It simplifies working
float: Floating-point numbers (e.g., 3.14, -0.001) with structured data.
str: Strings (e.g., "hello", 'Python') Example:
bool: Boolean values (True or False) import pandas as pd
list: An ordered collection of items (e.g., [1, 2, 3]) df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
tuple: An ordered, immutable collection (e.g., (1, 2, 3)) Data structures are used to organize, store and manage data for
dict: A collection of key-value pairs (e.g., {'name': 'Alice', 'age': efficient access and modification.Data structures are containers
25}) storing data in a specific memory layout.
set: An unordered collection of unique items (e.g., {1, 2, 3})
Operators: Symbols used to perform operations on variables or
values. Common operators include:
Arithmetic operators: +, -, *, /, %, // (floor division), **
(exponentiation)
Comparison operators: ==, !=, >, <, >=, <=
Logical operators: and, or, not
Assignment operators: =, +=, -=, *=, /=
Control Flow: Statements that allow conditional execution of
code.
if/elif/else: Used for conditional branching.
while: A loop that runs as long as a condition is true.
for: A loop that iterates over a sequence (like a list or range).
break: Exits a loop prematurely.
continue: Skips the current iteration of a loop.
Functions: A function is a group of statements that exist within a
program for the purpose of performing a specific task. A large
task is divided into several smaller tasks that are easily
performed known as divide and conquer.
Functions are defined using the def keyword.
Example:
def greet(name):
return "Hello, " + name
Benefits of a function:
1: Simpler code
2: Code Reuse
3: Better testing
4: Faster development
Passing arguments to the function:
An argument is any piece of data that is passed into a function
when the function is called. A parameter is a variable that
receives an argument that is passed into a function.
Modules: A module is a file containing Python definitions and
statements. It helps organize code into smaller, reusable
components. You can import modules using the import
keyword.
Example:
import math
Exception Handling: Mechanisms for handling errors in a
program.
try/except: Allows you to handle errors gracefully.
Example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
List Comprehension: A concise way to create lists using a
single line of code. It uses a for loop inside square brackets.
Example:
squares = [x**2 for x in range(5)] # [0, 1, 4,
9, 16]
Lambda Functions: Anonymous functions defined using the
lambda keyword.
Example:
add = lambda x, y: x + y

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy