W6 - 👨🏫 Lecture - Introduction to Python (A Transition from C)
Video: https://youtu.be/ZEQh45W_UDo
Video: https://youtu.be/EHi0RDZ31VA
#CS50x #Python #Computer_Science
Read more here
Related:
- ℹ️ IT Automation with Python - Google Professional Certificate (MOC)
- ℹ️ CS50's Introduction to Artificial Intelligence with Python (MOC)
Table of Contents:
A) Transitioning from C to Python
A.1) Introduction to Python
- [[Python]] is a modern, [[high-level language]], offering:
- Abstractions over low-level details (e.g., memory management, pointers).
- Ease of use: More readable and concise syntax.
- Extensive ecosystem: Libraries for various tasks (image processing, face recognition, etc.).
- Moving from C to Python reduces complexity:
- No need to explicitly compile code.
- Simpler syntax for the same functionality.
A.2) Simplifying "Hello, World" - Differences Between C and Python
Simplified Syntax: Python eliminates the need for repeated template code (e.g., no main()
or curly braces).
- In C, printing "hello, world" required:
#include <stdio.h>
int main(void) {
printf("Hello, world\n");
}
In Python, the same result is achieved with:
print("Hello, world")
More Differences:
- No need to include libraries explicitly (e.g.,
<stdio.h>
in C). - No
main()
function is required. - Syntax is cleaner—no semicolons (
;
) or curly braces ({}
). - New lines (
\n
) are handled automatically inprint()
.
Summary: Differences Between C and Python
Aspect | C | Python |
---|---|---|
Syntax for Hello World | Requires #include , main() , semicolons, printf() |
Simplified to print("Hello, world") |
Compilation | Requires clang and manual compilation steps. |
Directly run with python hello.py . |
Libraries | Must include libraries (e.g., #include <stdio.h> ). |
Functions like print() work without explicit imports. |
Semicolons | Required. | Not required. |
Newline Character | Explicit with \n . |
Implicit in print() . |
Quotes for Strings | Double quotes required for strings. | Supports single or double quotes. |
Memory Management | Manual (malloc , free ). |
Automatic (managed by Python). |
A.2.1) Compilation vs Interpretation
-
C: Requires compilation (e.g., using
make
orclang
) before running.
-
Python: Is an [[Interpreted language]], removing the compile step
Example: Running Python Code
- Create a file (e.g.,
hello.py
). - Run it directly with:
python hello.py
Note: Code is executed line-by-line using the [[python interpreter]]
A.3) Practical Demonstration: Python’s Simplicity for Problem Solving
A.3.1) Implementing a Spell Checker in Python (Comparison with C)
Example of re-implementing Problem Set 5's spell checker using Python.
- C: Implementing a dictionary for a spell checker.
- Requires implementing a hash table.
- Manual memory allocation (
malloc
/free
).
- Python: Implementing a dictionary for a spell checker.
-
File Overview:
dictionary.py
: Replacesdictionary.c
.speller.py
: Replacesspeller.c
.
-
Implementing
dictionary.py
:
# Global variable: a set to store words
words = set()
# Check if a word is in the dictionary
def check(word):
return word.lower() in words
# Load the dictionary into memory
def load(dictionary):
with open(dictionary) as file:
words.update(file.read().splitlines())
return True
# Get the size of the dictionary
def size():
return len(words)
# No unload needed in Python; memory is managed automatically
def unload():
return True
- Running the Program:
- Run
speller.py
onholmes.txt
:
- Run
python speller.py texts/holmes.txt
- Example output:
Python Advantages: Python's built-in data types simplify tasks.
- Ease of Use:
- Functions like
len()
simplify tasks. - No need to manually manage memory.
- Functions like
- Efficiency in Development:
- Example: Building a dictionary in Python takes significantly fewer lines of code.
- Rich Libraries:
- Functions and tools readily available (e.g.,
splitlines()
for file handling).
- Functions and tools readily available (e.g.,
Python Trade-offs:
- Python is slightly slower.
- Python may use more memory due to its dynamic and interpreted nature.
A.3.2) Image Processing with Python (using Pillow (PIL))
Python makes image manipulation simple with libraries like Python Imaging Library also known as [[PIL (Pillow)]].
A.3.2.1) Example1: Blurring an Image
- Code (
blur.py
):
from PIL import Image, ImageFilter
before = Image.open("bridge.bmp")
after = before.filter(ImageFilter.BoxBlur(10))
after.save("out.bmp")
- Command:
python blur.py
- Result: The image
bridge.bmp
is blurred and saved asout.bmp
.
A.3.2.2) Example2: Edge Detection
- Easily apply edge detection with
ImageFilter.FIND_EDGES
.
-
Code (
edges.py
)from PIL import Image, ImageFilter before = Image.open("bridge.bmp") after = before.filter(ImageFilter.FIND_EDGES) after.save("out.bmp")
-
Result: Detects edges in
bridge.bmp
and saves the output.
A.4) DEMO: Face Recognition with Python (AI trained models)
Using Libraries
-
Python's ecosystem includes libraries like face_recognition.
-
Install with:
-
Copy:
pip install face_recognition
Detecting Faces
- Code (
detect.py
):import face_recognition # Load image image = face_recognition.load_image_file("office.jpg") face_locations = face_recognition.face_locations(image) # Process detected faces for face in face_locations: print(face)
Recognizing Specific Faces:
Compare a known face with faces in an image,
- Code (
recognize.py
)
import face_recognition
Load group and target images
group_image = face_recognition.load_image_file("office.jpg")
target_image = face_recognition.load_image_file("toby.jpg")
Encode faces
group_encodings = face_recognition.face_encodings(group_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
Compare and highlight
results = face_recognition.compare_faces(group_encodings, target_encoding)
for i, match in enumerate(results):
if match:
print(f"Match found at position {i}")
```
Output:
- Detect faces in
office.jpg
. - Identify Toby specifically and highlight his face in a new file.
A.5) Python vs. C: When to Use Each?
Why Python?
- Advantages:
- Simplicity and fewer lines of code.
- Rich ecosystem of libraries.
- Readable and intuitive syntax.
- High-level abstractions save development time.
- Disadvantages:
- Slower performance than C.
- Higher memory usage due to dynamic memory management.
Aspect | C | Python |
---|---|---|
Performance | Faster, more efficient with memory. | Slower due to abstraction overhead. |
Ease of Coding | Requires more boilerplate code. | Concise and easier to write. |
Use Case | Embedded systems, performance-critical tasks. | Rapid prototyping, data analysis, and high-level tasks. |
Python’s design emphasizes simplicity and productivity. While it trades some speed and efficiency compared to lower-level languages like C, it empowers programmers to accomplish tasks more quickly and with less code. As CS50 transitions into higher-level concepts, Python exemplifies how abstractions can streamline problem-solving without sacrificing power.
B) Comparing Scratch and C to Python (Learn Python's Basics)
B.1) Functions in Python
- Definition: Functions in Python are similar to actions or verbs in Scratch and C, enabling reusable tasks in programs.
- Example Comparison:
-
In Scratch: Using a "say" block to display text.
-
In C:
#include <stdio.h> int main(void) { printf("hello, world\n"); return 0; }
-
In Python:
print("hello, world")
-
B.2) Libraries in Python
-
Usage:
-
In C, libraries like
stdio.h
orcs50.h
are included using#include
.
-
In Python, libraries are imported using
import
.
-
-
Fine-grained Importing:
- Instead of importing the entire library, specific functions can be imported:
from cs50 import get_string
- This approach optimizes memory usage and performance.
- Instead of importing the entire library, specific functions can be imported:
B.3) Variables and Data Types in Python
Variable Declaration:
- In Scratch:
-
Variable Declaration:
-
In C:
int counter = 0;
-
In Python:
counter = 0
-
Note: Differences from C,
- No need to specify data types (int
, float
, etc.).
- No need to manage memory manually.
Incrementing Variables:
- In Scratch:
-
Incrementing Variables:
-
In C:
counter = counter + 1; // Or: counter += 1 Or: counter++
-
In Python:
counter += 1 #but counter++ is not available
-
-
Available Data Types in Python:
- Primitive Types:
bool
:True
,False
int
: Integer valuesfloat
: Floating-point numbersstr
: Strings
- Advanced Types:
list
: Similar to arrays but more flexible.tuple
: Immutable ordered collection.dict
: Dictionaries (hash tables).set
: Collections with unique elements.range
: was a built-in function that returned a list in Python 2. …and it’s a datatype in Python 3: it is an immutable sequence.
- Primitive Types:
B.4) Input and String Concatenation in Python
In Scratch
-
C Version:
#include <cs50.h> #include <stdio.h> int main(void) { string answer = get_string("What's your name? "); printf("hello, %s\n", answer); return 0; }
-
Python Version:
from cs50 import get_string answer = get_string("What's your name?") print("hello, " + answer)
Note: Python: String Concatenation:
-
Method1: Using
+
to join strings:print("hello, " + answer)
-
Method2: Using a comma to separate arguments:
print("hello,", answer) #(Adds a space automatically between arguments.)
-
Method3: Using f-strings (preferred method):
print(f"hello, {answer}") #format string
Note: Simplifying Input:
- The CS50
get_string()
function can be replaced by Python’s built-ininput()
:answer = input("What's your name?") print(f"hello, {answer}")
B.4.1) Example: A Simple Calculator
-
C Implementation:
#include <cs50.h> #include <stdio.h> int main(void) { int x = get_int("x: "); int y = get_int("y: "); printf("%i\n", x + y); return 0; }
-
Python Implementation:
from cs50 import get_int x = get_int("x: ") y = get_int("y: ") print(x + y)
Error1: need to convert string user input as an integer
Note: Replacing get_int()
with input()
:
- Problem:
input()
treats user input as a string.
- Solution: Convert input to an integer using
int()
:x = int(input("x: ")) y = int(input("y: ")) print(x + y)
Error2: they protection from get_int
and get_float
from cs50
-
Example: run the calculator with
input()
andint()
conversionx = int(input("x: ")) y = int(input("y: ")) print(x + y)
-
If a user enters
cat
,
-
Python raises an error because
cat
is not convertible to an integer.
Tips: Importing Libraries in Python
- Import specific functions:
- also valid
But what happens if you have your own functions and they are named the same as some libraries?
You can do the following trick:
-
Import the whole library:
import cs50 x = cs50.get_int("x: ")
-
use
cs50.get_int()
to specify which function to useimport cs50 x = cs50.get_int("x: ")
B.5) Conditionals in Python
Conditionals in Python allow for decision-making in programs, analogous to the "if-else" blocks in Scratch or the "if-else" statements in C. However, Python simplifies the syntax and enforces indentation to ensure readable code.
-
Scratch:
-
C:
if (x < y) { printf("x is less than y\n"); }
- Requires:
- Parentheses around conditions.
- Curly braces for blocks. <-------------
- Explicit
\n
for newlines. - Semicolons to terminate statements.
- Requires:
- Python:
if x < y: print("x is less than y")
- Simplifications:
- No parentheses around conditions unless grouping is required.
- No curly braces—indentation determines the block. <-------------
- Colons (
:
) signify the start of a block. - No need for
\n
or semicolons.
- Simplifications:
Explanation:
elif
replaceselse if
in Python, saving keystrokes.- Indentation (4 spaces or a tab) is required to indicate the body of the condition.
Example: Conditionals - Compare Integers in Python
Three-Way Comparison (if, elif, else):
from cs50 import get_int
x = get_int("What's x? ")
y = get_int("What's y? ")
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
Example: Conditionals - String Comparison in Python
-
C Limitation:
if (s == t) { printf("Same\n"); } else { printf("Different\n"); }
- Compares memory addresses of strings (
char*
), not their content. - Two identical strings in different memory locations are considered "different."
- Compares memory addresses of strings (
-
Python Simplification:
s = input("Enter first string: ") t = input("Enter second string: ") if s == t: print("Same") else: print("Different")
- Python's
==
operator compares the content of strings, not memory addresses.
- Python's
Example: Conditionals - Handling Case Insensitivity with Strings
Let's try to impement one of our C programs, but now in Python,
C Version:
#include <cs50.h>
#include <stdio.h>
int main(void) {
char c = get_char("Do you agree? ");
if (c == 'Y' || c == 'y') {
printf("Agreed\n");
} else if (c == 'N' || c == 'n') {
printf("Not agreed\n");
}
}
Python Version:
Problem with copying the C approach: Users may input strings with varying capitalizations (e.g., "Yes", "yes", "YES"). A robust program should account for this.
- New Python Approach: check in a collection of values
if s in ["y", "yes", "Y", "YES"]: print("Agreed") elif s in ["n", "no", "N", "NO"]: print("Not agreed")
- Use the
in
keyword to check if a value exists in a list - This approach becomes cumbersome as the number of variations increases.
- Use the
- String Methods:
- Python strings are objects with built-in methods.
- Example:
s.lower()
converts a string to lowercase.
- Comparison to C:
-
C: Use
tolower()
from thectype.h
library:
c char c = tolower(s);
-
Python: Use the method directly on the string object:
python s = s.lower()
-
Note: find the documentation here,
-
Improved Python Approach: use Lowercasing as a standard input from user with
.lower()
s = input("Do you agree? ").lower() if s in ["y", "yes"]: print("Agreed") elif s in ["n", "no"]: print("Not agreed")
-
Chaining Method Calls:
-
Python allows chaining methods for concise code:
s = input("Do you agree? ").strip().lower()
-
strip()
removes leading/trailing spaces. -
lower()
converts input to lowercase.
-
"Agree Program" in Python vs "Agree Program" in C
C Version:
#include <cs50.h>
#include <stdio.h>
int main(void) {
char c = get_char("Do you agree? ");
if (c == 'Y' || c == 'y') {
printf("Agreed\n");
} else if (c == 'N' || c == 'n') {
printf("Not agreed\n");
}
}
Python Version:
s = input("Do you agree? ").lower()
if s in ["y", "yes"]:
print("Agreed")
elif s in ["n", "no"]:
print("Not agreed")
- Strings are objects with built-in methods (e.g.,
.lower()
).
B.6) Loops in Python (dealing with Strings and Functions)
Loops in Python allow us to repeat actions, similar to Scratch and C. However, Python introduces some key differences that make loops more concise and intuitive.
While Loops in Python
-
Repeat Three Times
-
Scratch: Repeat block.
-
C: Using a
while
loop:int i = 0; while (i < 3) { printf("meow\n"); i++; }
-
Python: Simplified
while
loop:i = 0 while i < 3: print("meow") i += 1
-
-
Infinite Loops:
-
Scratch: Repeat forever
-
C:
while (true) { printf("meow\n"); }
-
Python:
while True: print("meow")
- Note:
True
is capitalized in Python.
- Note:
-
For Loops in Python
- C: Using a
for
loop:
-
Using a
for
Loop in Python: Python simplifies thefor
loop compared to C:for i in [0, 1, 2]: print("meow")
Use:
range()
: Instead of manually specifying numbers:for i in range(3): print("meow")
range(3)
generates numbers from 0 to 2.- No need to declare
i
or manually increment it.
-
_
in Loops: If you don't use the loop variablei
:for _ in range(3): print("meow")
_
signals that the variable is unused.
Example: Loops - String Manipulation in Python
-
Uppercasing a String:
-
In C:
for (int i = 0; i < strlen(str); i++) { str[i] = toupper(str[i]); }
-
In Python:
before = input("Before: ") after = before.upper() print(f"After: {after}")
-
- Iterating Over a String: Strings in Python are iterable:
- Use
end=""
in theprint()
function to avoid automatic newlines. This is known as a [[named parameter]].before = input("Before: ") for c in before: print(c.upper(), end="") print()
[[Named Parameters]]: The end
Parameter in print()
:
- By default,
print()
ends with a newline (\n
). - Override this using the
end
parameter:print("hello", end="") print("world") # Prints "helloworld"
Example: using Functions and Loops together in Python (create a main function)
let's improve our code by using functions,
-
Basic Function Definition:
-
Python uses
def
to define functions:def meow(): print("meow")
-
Call the function:
meow()
-
Note: if the function is below the logic where it is called, it will cause issues
- Adding a
main()
Function: Python does not require amain()
function, but it’s conventional to include one:
- Note: in Python,
main()
needs to be called as-well, otherwise we won't see it's execution,
__name__
Consider our meow.py
program, the best way to ensure the correct execution of main()
is like this:
def main():
meow()
def meow():
print("meow")
if __name__ == "__main__":
main()
The line if __name__ == "__main__":
is a common construct in Python that ensures a particular block of code is executed only when the script is run directly, rather than being imported as a module in another script.
Here's what it means:
-
__name__
:- This is a special built-in variable in Python.
- When a Python file is run,
__name__
is set to"__main__"
. - When a Python file is imported into another script,
__name__
is set to the name of the file/module (without the.py
extension).
-
The Conditional Check:
- The condition
if __name__ == "__main__":
checks if the script is being executed directly. - If
True
, it means the script is not being imported but is run directly by the Python interpreter.
- The condition
-
Purpose:
- It is used to organize code. Typically, this block contains code that should only run when the script is executed directly (e.g., test code, example usage, or the main entry point of the program).
-
Example:
# my_script.py
def greet():
print("Hello, World!")
if __name__ == "__main__":
greet()
-
When you run
python my_script.py
:__name__
is set to"__main__"
, sogreet()
will be executed, and "Hello, World!" will be printed.
-
When you import this script in another file:
# another_script.py
import my_script
- In this case,
__name__
inmy_script.py
is not"__main__"
(it's"my_script"
), so the code inside theif __name__ == "__main__":
block will not execute.
Key Takeaway: This pattern is useful for making Python files reusable as both standalone scripts and importable modules.
- Parameterizing Functions:
- Pass arguments to make functions reusable:
def meow(n): for _ in range(n): print("meow") meow(3)
- Pass arguments to make functions reusable:
- Default Arguments:
- Define default values for parameters:
def meow(n=3): for _ in range(n): print("meow") meow() # Defaults to 3 meow(5) # Overrides default
- Define default values for parameters:
Handling Numbers in Python (Truncation, Floating-Point Precision and Integer Overflow)
Python simplifies and enhances number operations compared to C.
-
Integer Division and Truncation:
-
In C: Integer division truncates fractional parts:
int x = 1, y = 3; float z = x / y; // Result: 0 (integer division)
-
In Python: Integer division automatically results in a float:
x = 1 y = 3 z = x / y # Result: 0.3333...
-
-
Floating-Point Precision:
- Python still has floating-point precision issues due to hardware limitations.
- Example:
z = 1 / 3 print(f"{z:.50f}") # Prints 50 decimal places
- Solution: Use libraries like
decimal
for higher precision.
-
Integer Overflow:
- In C: Overflow occurs when exceeding the fixed bit size.
- In Python: Integers automatically scale with memory, preventing overflow.
C) Introducing New Python Concepts
Example: Error Handling with Exceptions
Python introduces a robust mechanism to handle errors using exceptions.
Let's first write some buggy code, the calculator works fine with numbers,
but is the user inputs something else, the program shows an error,
Note: we got an [[ValueError]], we can use this value and define [[exceptions]] and handle this issue.
-
Handling Value Errors:
- Example: Invalid input causing a
ValueError
.
try: x = int(input("Enter an integer: ")) except ValueError: print("Not an integer!")
- Example: Invalid input causing a
-
Custom Input Handling:
- Using a loop to repeatedly prompt for valid input:
def get_int(prompt): while True: try: return int(input(prompt)) except ValueError: print("Not an integer!")
- Note: CS50-Style Input:
- Replicating CS50's
get_int()
:
def get_int(prompt): while True: try: return int(input(prompt)) except ValueError: pass # Silently retry
- Replicating CS50's
Loops and Patterns in Python (Mario Pyramids)
-
1D Patterns:
- Building a Column:
for i in range(3): print("#")
- Printing a row of characters:
print("?" * 4) # Outputs: ????
Equivalent:
-
2D Patterns:
- Printing a 3x3 grid:
for i in range(3): for j in range(3): print("#", end="") print() # Moves to the next row
- Printing a 3x3 grid:
- Efficient 2D Patterns:
- Combining ideas to simplify nested loops:
for i in range(3): print("#" * 3) # Prints a row of 3 hashes
- Combining ideas to simplify nested loops:
Dynamic Patterns with User Input
-
Prompting for a Height:
- Using a loop to validate input:
while True: try: height = int(input("Height: ")) if height > 0: break except ValueError: pass
- Using a loop to validate input:
-
Building a Column:
for i in range(height): print("#")
-
Building a Row:
print("#" * height)
-
Building a Grid:
for i in range(height): print("#" * height)
Lists in Python
Lists in Python are flexible, dynamic, and come with built-in methods for common operations.
-
Key Features:
- Lists can grow and shrink dynamically.
- They are more like [[linked lists]] than arrays in C but are easier to use.
- No need for manual memory management.
-
Creating a List:
scores = [72, 73, 33] # Create a list with three values.
-
Operations:
-
Calculate Average:
average = sum(scores) / len(scores) print(f"Average: {average}")
-
Empty Lists:
scores = [] # Start with an empty list.
-
Appending to a List:
scores.append(100) # Add 100 to the end of the list.
- Concatenating Lists:
scores += [90] # Add 90 to the end of the list.
-
-
Advantages Over C:
- Automatically resizes without the need for
malloc()
or manual memory allocation. - Methods like
append()
andlen()
make list operations much easier.
- Automatically resizes without the need for
Note: documentation
Example: Searching in Lists
Python simplifies linear search with the in
operator.
-
Manual Search: notice
else
is associated to thefor
loopfor name in names: if name == "David": print("Found") break else: print("Not found")
-
Simplified Search: linear search is used by Python
if "David" in names: print("Found") else: print("Not found")
Dictionaries in Python
[[Dictionaries]] are a collection of key-value pairs and are equivalent to [[hash tables]] in C.
Read documentation:
- Creating a Dictionary:
people = {
"Carter": "+1-617-495-1000",
"David": "+1-617-495-1000",
"John": "+1-949-468-2750"
}
-
Dictionary: The entire structure is a dictionary (
{}
). -
Key-Value Pairs: Each
name
is a key, and the correspondingnumber
is its value. -
Accessing Values: To get David's number:
print(people["David"]) # Outputs: +1-617-495-1000
-
Creating a List of Dictionaries:
-
List: The outer structure is a list (
[]
). -
Dictionaries: Each item in the list is a dictionary (
{}
) with keys like"name"
and"number"
. -
Flexible: This structure is useful when you have multiple entries and each entry could potentially have a different set of fields or more complex data.
-
Accessing Values: To get Carter's number:
print(people[0]["number"]) # Outputs: +1-617-495-1000
-
Checking for Keys: List of Dictionaries
or simplify like this:
-
Checking for Keys: Single Dictionary
-
Adding or Updating Entries:
people["Eli"] = "+1-555-123-4567" # Add a new entry. people["David"] = "+1-555-987-6543" # Update an existing entry.
-
Removing Entries:
del people["John"] # Remove John's entry.
-
Iterating Through a Dictionary:
for name, number in people.items(): print(f"{name}: {number}")
Advantages of Python Dictionaries
- Efficient Lookup:
- Python dictionaries are optimized for fast lookups.
- Use
in
to check for keys directly.
- Flexible Data Storage:
- Can store any type of data as values.
- Supports nested structures (e.g., a dictionary of lists or a list of dictionaries).
- Built-In Methods:
items()
: Iterate over key-value pairs.keys()
: Get all keys.values()
: Get all values.
Comparison: Lists vs. Dictionaries
Feature | Lists | Dictionaries |
---|---|---|
Data Storage | Ordered collection | Key-value pairs |
Access Method | Index-based (e.g., 0) | Key-based (e.g., "name") |
Usage | Sequential operations | Lookup and associations |
Performance | Slower for lookups | Fast for key-based lookups |
Takeaways: |
- Use lists for ordered collections or sequential data.
- Use dictionaries when associating keys with values (e.g., phonebooks, configurations).
- Python provides built-in methods to simplify common tasks, saving time and reducing code complexity.
Command-Line Arguments in Python (sys.argv
)
- What it is: Python provides the
sys.argv
list in thesys
module to handle command-line arguments passed to a program.
Read documentation:
-
Comparison to C: Unlike C (where
argc
andargv
are part ofmain()
), Python'sargv
is part of thesys
library and must be imported explicitly. -
Example:
import sys if len(sys.argv) == 2: # Check if exactly 2 arguments (script + 1 input) are provided print(f"Hello, {sys.argv[1]}!") # Access the argument at index 1 else: print("Hello, world!")
-
Key Details:
sys.argv[0]
: Name of the script being run (e.g.,greet.py
).- Additional arguments (e.g.,
argv[1]
) are the ones provided after the script name. - Command:
python greet.py David
→ Output:Hello, David!
Exiting Programs with sys.exit()
-
What it is: The
sys.exit()
function allows you to terminate a program and optionally specify an exit status. -
Use Case: Helpful for error handling or when input requirements are not met.
-
Example:
import sys if len(sys.argv) != 2: print("Missing command-line argument") sys.exit(1) # Exit with a non-zero status to indicate an error print(f"Hello, {sys.argv[1]}!") sys.exit(0) # Exit with 0 (success)
Having Fun Using External Python Libraries
Python offers a rich ecosystem of libraries.
- Command: Use
pip install <library_name>
to install third-party Python packages. - Examples:
pip install cowsay
pip install qrcode
- These libraries extend Python’s functionality without requiring manual implementation of complex features.
a. cowsay
Library
- What it does: Generates ASCII art of a cow (or other characters) saying custom messages.
- How to use it:
import cowsay name = input("What's your name? ") cowsay.cow(f"Hello, {name}!")
b. qrcode
Library
-
What it does: Generates QR codes for URLs or other data.
-
How to use it:
import qrcode img = qrcode.make("https://youtu.be/xvFZjo5PgG0") # Create QR code img.save("qr.png", "PNG") # Save as an image file
-
Result: Generates a
qr.png
file containing the QR code, which can be scanned to access the link.
Key Takeaways: Comparing Python to C
-
Python vs. C:
- Python simplifies tasks like handling command-line arguments, file I/O, and creating graphical output (e.g., QR codes).
- Fewer lines of code are required in Python compared to C.
-
Python Libraries:
- Python has a wide range of built-in and third-party libraries for various use cases.
- Libraries like
sys
,cowsay
, andqrcode
streamline tasks like argument parsing, ASCII art generation, and QR code creation.
-
Ease of Use:
- Python eliminates much of the boilerplate code required in C, such as managing memory or handling strings.
Y) Learn more Python Here
Enroll here
Notes: ℹ️ CS50's Introduction to Python (MOC)
Related: ℹ️ IT Automation with Python - Google Professional Certificate (MOC)
Related: ℹ️ CS50's Introduction to Artificial Intelligence with Python (MOC)
Z) 🗃️ Glossary
File | Definition |
---|