W6 - Shorts 📚🔍- Introduction to Python (A Transition from C)
Video: https://youtu.be/mgBpcQRDtl0
Read more here
CS50 IDE: https://cs50.dev/ (Online VSCode)
CS50 Library Documentation: https://manual.cs50.io/#cs50.h
#CS50x #C #Computer_Science #VisualStudioCode
Table of Contents:
A) Introducing Python: A Transition from C
1. Overview: Python's Popularity
- Python's Popularity: Among the top programming languages today, Python has been around for over 25 years.
- Use Cases:
- Simplifies complex operations compared to C, like string manipulation and networking.
- Widely used in data science, for:
- Processing large datasets.
- Generating graphs and charts.
- Versatile for general-purpose programming tasks.
2. Python Compared to C
- Syntax:
- Inspired by C but simpler:
- No curly braces
{}
. - Indentation is crucial for defining blocks.
- No curly braces
- Minimalistic but consistent design.
- Inspired by C but simpler:
- Features:
- Removes many of C's challenges:
- Easier string manipulation.
- Simplifies memory management (e.g., no need for
malloc
or pointers).
- Suited for modern applications like web development, scripting, and data analysis.
- Removes many of C's challenges:
Key Takeaway:
Python is a beginner-friendly yet powerful language that simplifies many of C's complexities while offering robust tools for modern applications. With its concise syntax and wide adoption, Python is an essential language to learn for software development, data science, and beyond.
3. Writing Python Code
- File Structure:
- Use a
.py
file extension (e.g.,program.py
). - Syntax highlighting is supported in IDEs like CS50 IDE.
- Use a
- Execution:
- Interpreted Language:
- Unlike C, Python doesn't require compilation.
- Code runs directly in a Python interpreter, executing one line at a time.
- Comparison with C:
- C: Requires compilation (
gcc
) before running. - Python: Directly run with the
python3
command or inside an interpreter.
- C: Requires compilation (
- Interpreted Language:
4. Python Versions
- Python 3:
- Taught in CS50 and the modern standard for Python programming.
- Python 2:
- Still referenced online but outdated.
- Syntax and features may not work with Python 3.
- Key Tip:
- Always specify "Python 3" when searching for documentation or examples.
5. Getting Started
To begin writing and running Python programs:
-
Create a
.py
file in CS50 IDE. -
Open a terminal and run:
python3 program.py
-
Use the interactive Python interpreter for experimentation:
python3
B) Variables in Python: A Comparison with C
- Python simplifies variable declaration:
- No type specification.
- Initialization is required.
- No semicolons needed.
- Strings are built-in, and you can use single or double quotes flexibly.
- Dynamic typing allows variables to change types, offering flexibility for development.
1. Key Differences from C (Declaration and Initialization)
-
No Type Declaration:
- In Python, you don’t need to specify a type (like
int
,string
). - The type is determined automatically based on the assigned value.
- Example:
-
C:
int x = 54;
-
Python:
x = 54
-
- In Python, you don’t need to specify a type (like
-
Initialization Required:
- Variables must be initialized when declared.
- Python does not allow:
-
C:
int x; // Declaration without initialization.
-
Python: Not allowed. You must assign a value:
x = None # Assign `None` if you don't yet have a value.
-
2. Differences in Syntax
- No Semicolons:
- Python statements do not require semicolons.
- Adding them won’t cause errors, but omitting them makes code cleaner.
- Example:
-
C:
int x = 54;
-
Python:
x = 54
-
3. Strings in Python
-
Strings are Native in Python:
- Unlike in C, where you need libraries like
#include <cs50.h>
to work with strings, Python supports strings natively. - Example:
-
C:
string phrase = "This is CS50"; // Requires the CS50 library.
-
Python:
phrase = "This is CS50"
-
- Unlike in C, where you need libraries like
-
Single and Double Quotes:
-
Python supports both single
'
and double"
quotes for strings:-
Example:
phrase = "This is CS50" phrase = 'This is CS50'
-
-
Why This is Useful:
-
Easily include quotes inside strings:
# Double quotes outside, single quotes inside phrase = "It's a beautiful day!" # Single quotes outside, double quotes inside phrase = 'He said, "Hello, world!"'
-
-
4. Dynamic Typing (Variable are Flexible)
-
Python variables can change type dynamically:
x = 42 # x is an integer x = "CS50" # Now x is a string
-
C:
-
Variable types are fixed and cannot change:
int x = 42; x = "CS50"; // Error: incompatible types
-
D) Conditional Statements in Python: A Comparison with C
1. Basic Structure: if
Statements
-
C:
if (y < 43 || z == 15) { // Code block }
-
Python:
if y < 43 or z == 15: # Code block
Key Differences:
- Logical Operators:
||
becomesor
&&
becomesand
!
becomesnot
- No Curly Braces:
- Use a colon
:
to start a code block. - Indentation is used instead of curly braces to define the scope of the block.
- Use a colon
- Comments:
- Use
#
for comments in Python.
- Use
2. if-else
Statements
-
C:
if (y < 43 && z == 15) { // Code block } else { // Code block }
-
Python:
if y < 43 and z == 15: # Code block else: # Code block
Key Differences:
and
for Logical Conjunction:- Replace
&&
withand
.
- Replace
- Colons and Indentation:
- Use
:
afterif
andelse
. - Indent code to define blocks.
- Use
3. if-elif-else
Statements
-
C:
if (course_number == 50) { // Code block } else if (course_number != 51) { // Code block } else { // Code block }
-
Python:
if course_number == 50: # Code block elif course_number != 51: # Code block else: # Code block
Key Differences:
- No
else if
:- Use
elif
instead ofelse if
.
- Use
not
for Negation:- Replace
!=
withnot ... ==
if needed (optional for readability).
- Replace
4. Ternary (Conditional) Operator
-
C:
bool alphabetic = (char_is_letter(c)) ? true : false;
-
Python:
alphabetic = True if char_is_letter(c) else False
Key Differences:
- In Python:
- Use
value_if_true if condition else value_if_false
. True
andFalse
are capitalized.
- Use
5. User Input: native input()
function
-
C (using CS50 Library):
string name = get_string("What's your name?");
-
Python:
name = input("What's your name? ")
Key Points:
- Python's
input()
function is built-in and collects user input as a string. - CS50's
get_string
,get_int
,get_float
are rewritten in Python if you'd like to use them, butinput()
is more idiomatic in Python.
Summary of Python Features: Conditional Statements
- Logical Operators:
or
,and
,not
for||
,&&
,!
. - No Curly Braces: Use
:
and indentation to structure code. - Comments: Use
#
instead of//
or/* */
. - Ternary Operator: Simpler syntax with
value_if_true if condition else value_if_false
. - Input: Use the native
input()
function to get user input.
Python’s syntax is designed to be closer to plain English, making it easier to read and write. With practice, these differences become intuitive and second nature.
E) Loops in Python: A Comparison with C
1. while
Loops
-
C:
int counter = 0; while (counter < 100) { printf("%d\n", counter); counter++; }
-
Python:
counter = 0 while counter < 100: print(counter) counter += 1
Key Differences:
- No Type Declaration:
counter = 0
instead ofint counter = 0
. - No Parentheses: Conditions in
while
do not require parentheses. - No Semicolons: Lines in Python don’t end with semicolons.
- No
++
Operator: Usecounter += 1
instead ofcounter++
. - Automatic Newline in
print()
: Unlikeprintf
,print()
automatically adds a newline.
2. for
Loops
-
C:
for (int x = 0; x < 100; x++) { printf("%d\n", x); }
-
Python:
for x in range(100): print(x)
Key Differences:
range()
Function:range(100)
generates numbers from0
to99
(not including100
).- Syntax:
range(start, stop, step)
- Default:
start=0
,step=1
.
- Default:
- No Initialization/Condition/Increment: Python’s
for
loop uses a simplerfor x in range
syntax. - No Semicolons or Parentheses.
3. Counting by Twos
-
C:
for (int x = 0; x < 100; x += 2) { printf("%d\n", x); }
-
Python:
for x in range(0, 100, 2): print(x)
Explanation of range()
:
range(start, stop, step)
:start
: Starting number (inclusive, default is0
).stop
: Stopping number (exclusive).step
: Increment value (default is1
).- Example:
range(0, 100, 2)
generates[0, 2, 4, ..., 98]
.
Summary of Python Loop Features:
-
No Do-While Loops:
- Python lacks
do-while
loops, but you can simulate them usingwhile True
with abreak
.
- Python lacks
-
Simplified Syntax:
- No semicolons, type declarations, or increment (
++
) operators. - Indentation is used instead of curly braces.
- No semicolons, type declarations, or increment (
-
range()
is Powerful:- Handles counting, skipping, and defining ranges in a single function.
Python’s loops are cleaner and more readable than C, making them easier for beginners while remaining powerful for advanced use cases.
F) Understanding Lists in Python: A More Flexible Array
Python's lists offer a significant upgrade over arrays in C due to their flexibility, ease of use, and ability to store mixed data types. Here's an overview of how lists in Python compare with arrays in C and the powerful operations they enable.
1. Creating Lists
-
Empty List:
nums = [] # Creates an empty list # Or nums = list() # Equivalent using the `list()` function
-
Pre-Populated List:
nums = [1, 2, 3, 4] # A list with four elements
-
Using List Comprehension:
nums = [x for x in range(500)] # Generates numbers 0 through 499
2. Adding Elements to Lists
-
Appending to the End:
nums.append(5) # Adds 5 to the end of the list
-
Inserting at a Specific Position:
nums.insert(4, 5) # Inserts 5 at index 4 (5th position)
-
Concatenating with Another List:
nums += [5, 6] # Appends [5, 6] to the end of nums
-
Using Splicing:
nums[len(nums):] = [5, 6] # Another way to concatenate [5, 6] at the end
3. Removing Elements from Lists
-
Removing by Value:
nums.remove(3) # Removes the first occurrence of 3
-
Removing by Index:
nums.pop(2) # Removes the element at index 2 and returns it
-
Clearing the List:
nums.clear() # Empties the list
4. Accessing Elements
-
Indexing:
print(nums[0]) # Accesses the first element (like `nums[0]` in C)
-
Slicing:
print(nums[1:3]) # Accesses elements at indices 1 and 2 (up to but not including index 3)
-
Negative Indexing:
print(nums[-1]) # Accesses the last element
5. Length and Iteration
-
Getting the Length:
print(len(nums)) # Returns the number of elements in the list
-
Iterating with a Loop:
for num in nums: print(num) # Prints each element
-
Enumerating with Indices:
for i, num in enumerate(nums): print(f"Index {i}: {num}") # Prints index and value
6. Differences from C Arrays
-
Dynamic Size:
- Lists can grow and shrink dynamically, unlike fixed-size arrays in C.
- Memory management is handled automatically.
-
Mixed Data Types:
-
Lists can store different types of data:
mixed_list = [1, "CS50", True, 3.14]
-
-
Built-In Methods:
- Python lists come with useful methods like
append()
,insert()
,remove()
, and more.
- Python lists come with useful methods like
7. Advanced Features: List Comprehension
List comprehensions allow you to create lists in a single, concise line.
-
Example: Generate squares of numbers from 0 to 9.
squares = [x**2 for x in range(10)]
-
Example: Filter even numbers.
evens = [x for x in range(20) if x % 2 == 0]
8. Summary of relevant List Functions
Function | Description |
---|---|
append(x) |
Adds x to the end of the list |
insert(i, x) |
Inserts x at index i |
remove(x) |
Removes the first occurrence of x |
pop(i) |
Removes and returns the element at index i |
clear() |
Removes all elements from the list |
len(list) |
Returns the number of elements in the list |
list(range(start, stop, step)) |
Generates a list from start to stop by step |
Python lists simplify many tasks that are cumbersome with C arrays, making them a versatile tool for programmers. They eliminate the need for manual memory management, provide flexibility, and offer a rich set of built-in functionalities.
G) Understanding Tuples in Python: Ordered and Immutable Data
Tuples in Python provide a way to store ordered, immutable data collections. They are similar to structures in C where the order matters, but the data is fixed and cannot be changed after creation. Here's how tuples work and why they are useful.
1. What is a Tuple?
- Definition: A tuple is an immutable, ordered collection of items.
- Key Features:
- Immutable: Once created, you cannot modify, add, or remove elements.
- Ordered: The sequence of elements matters.
- Use Case: Best used when data should remain constant and order is important.
2. Creating Tuples
-
Simple Tuple:
my_tuple = ("CS50", 2024) # A tuple with two elements
-
Without Parentheses (Optional):
my_tuple = "CS50", 2024 # Also a tuple
-
Empty Tuple:
empty_tuple = () # An empty tuple
-
Single-Element Tuple (Requires a Comma):
single_tuple = (42,) # A tuple with one element
3. Accessing Tuple Elements
-
Indexing:
print(my_tuple[0]) # Outputs: CS50
-
Unpacking:
course, year = my_tuple print(course) # Outputs: CS50 print(year) # Outputs: 2024
4. Example: A List of Tuples
You can store tuples inside a list for more complex data structures:
presidents = [
("George Washington", 1789),
("John Adams", 1797),
("Thomas Jefferson", 1801)
]
5. Iterating Over Tuples
You can iterate over a list of tuples and unpack their elements:
for prez, year in presidents:
print(f"In {year}, {prez} took office.")
Output:
In 1789, George Washington took office.
In 1797, John Adams took office.
In 1801, Thomas Jefferson took office.
6. Formatting with .format()
Python's print()
can format strings using the .format()
method, similar to printf
in C.
-
Example:
for prez, year in presidents: print("{1}, {0} took office.".format(prez, year))
{0}
and{1}
specify the order of arguments in.format(prez, year)
.- The order can be rearranged for flexibility.
-
Simpler Alternative:
for prez, year in presidents: print(f"{year}, {prez} took office.")
- This uses f-strings for inline variable interpolation.
7. Why Tuples?
- Efficiency: Tuples are faster than lists due to their immutability.
- Integrity: Data integrity is ensured since tuples cannot be modified after creation.
- Use Case Examples:
- Representing coordinates (e.g.,
(x, y)
in 2D space). - Storing constant data like dates or immutable records.
- Representing coordinates (e.g.,
8. Advanced Usage
-
Tuple Inside a List:
coordinates = [(0, 0), (1, 2), (2, 4)] for x, y in coordinates: print(f"x: {x}, y: {y}")
-
Returning Multiple Values from Functions:
def get_dimensions(): return 1920, 1080 # Returns a tuple width, height = get_dimensions() print(f"Width: {width}, Height: {height}")
Summary of Tuple Characteristics
Feature | Description |
---|---|
Immutable | Cannot be changed after creation. |
Ordered | Sequence of elements is fixed. |
Unpacking | Easily extract values into variables. |
Fast | More memory-efficient than lists for fixed data. |
Use Cases | Store coordinates, fixed records, or data that won't change. |
Tuples, along with lists and dictionaries, are a cornerstone of Python's flexible data handling capabilities. They provide both simplicity and power when dealing with structured and immutable data.
H) Understanding Dictionaries in Python
Dictionaries in Python provide a flexible and efficient way to associate keys with values, similar in concept to hash tables in other programming languages. Here’s a breakdown of how dictionaries work, their features, and how to use them effectively.
1. What is a Dictionary?
- Definition: A dictionary is a collection of key-value pairs where keys are unique.
- Key Features:
- Keys can be any immutable type (e.g., strings, numbers, tuples).
- Values can be any data type, including other dictionaries.
- Dictionaries are unordered (prior to Python 3.7) but maintain insertion order in Python 3.7+.
2. Creating a Dictionary
-
Empty Dictionary:
pizzas = {} # Creates an empty dictionary
-
Populated Dictionary:
pizzas = { "cheese": 9, "pepperoni": 10, "vegetable": 11, "buffalo chicken": 12 }
3. Accessing and Modifying Values
-
Access a Value:
print(pizzas["cheese"]) # Outputs: 9
-
Modify a Value:
pizzas["cheese"] = 8 # Updates the price of a cheese pizza
-
Add a New Key-Value Pair:
pizzas["bacon"] = 14 # Adds a bacon pizza
4. Iterating Over a Dictionary
a) Iterating Over Keys
for pie in pizzas:
print(pie)
# Outputs: cheese, pepperoni, vegetable, buffalo chicken, bacon
b) Iterating Over Keys and Values
for pie, price in pizzas.items():
print(f"A whole {pie} pizza costs ${price}")
Output:
A whole cheese pizza costs $8
A whole pepperoni pizza costs $10
...
5. Key Features
a) Dynamic Keys and Values
You can dynamically check or add keys:
if "vegetable" in pizzas:
print("Vegetable pizza is available")
else:
pizzas["vegetable"] = 13
b) Dictionary Methods
keys()
: Returns all keys.values()
: Returns all values.items()
: Returns all key-value pairs.
print(pizzas.keys()) # Outputs: dict_keys(['cheese', 'pepperoni', ...])
print(pizzas.values()) # Outputs: dict_values([8, 10, ...])
print(pizzas.items()) # Outputs: dict_items([('cheese', 8), ('pepperoni', 10), ...])
6. Formatting Output
a) String Concatenation
print("A whole " + "cheese" + " pizza costs $" + str(9))
b) f-Strings (Preferred)
pie = "cheese"
price = 9
print(f"A whole {pie} pizza costs ${price}")
c) Using .format()
print("A whole {} pizza costs ${}".format("cheese", 9))
7. Unordered Nature of Dictionaries
- Order Caveat:
- Pre-Python 3.7: Keys and values are unordered.
- Python 3.7+: Dictionaries maintain insertion order.
Example:
pizzas = {"vegetable": 11, "cheese": 8}
for pie, price in pizzas.items():
print(pie, price)
Order might vary in older Python versions but is consistent in Python 3.7+.
8. Dictionary Use Cases
- Data Lookup: Associating a name with a phone number or item prices with names.
- Data Storage: Storing structured data (e.g., JSON-like formats).
- Dynamic Data: Adding or removing items on the fly without fixed sizes.
Summary Table: How to use Dictionaries
Feature | Syntax/Method | Description |
---|---|---|
Create Empty Dictionary | pizzas = {} |
Initializes an empty dictionary. |
Access a Value | pizzas["cheese"] |
Accesses the value for the key "cheese". |
Add/Update Key-Value | pizzas["bacon"] = 14 |
Adds/updates key-value pair. |
Check Key Existence | "cheese" in pizzas |
Returns True if "cheese" is a key. |
Iterate Over Keys | for pie in pizzas: |
Loops through dictionary keys. |
Iterate Over Items | for pie, price in pizzas.items(): |
Loops through key-value pairs. |
Dictionary Methods | .keys(), .values(), .items() |
Retrieves keys, values, or both. |
Dictionaries in Python provide a flexible and intuitive way to manage key-value pairs without the manual effort required in languages like C. They are a fundamental data structure that significantly simplifies many common programming tasks!
J) Python Functions and main()
In Python, functions are highly flexible, eliminating many of the restrictions and requirements we faced in C. Here's a detailed explanation and examples to help you understand Python's approach to functions and the optional main()
construct.
1. Defining a Function
- Functions in Python are defined using the
def
keyword. - You don’t need to specify the return type or parameter types.
Example: A Simple Function
def square(x):
return x * x
print(square(5)) # Output: 25
2. Key Differences from C
- No Return Type: No need to declare
int
,float
, etc., for the return type. - No Parameter Types: Python dynamically infers the type of
x
. - Optional Main Function: Python doesn't require a
main()
function but supports one for organizing larger programs.
3. Advanced Function Examples
a) Using Python’s Exponentiation Operator
Python introduces the **
operator for exponentiation.
Example:
def square(x):
return x ** 2
print(square(5)) # Output: 25
b) A Convoluted Square Function
You can implement the square operation in creative ways. For example:
def square(x):
result = 0
for _ in range(x):
result += x
return result
print(square(5)) # Output: 25
While not efficient, this demonstrates how Python allows flexibility in function logic.
4. Optional main()
Function
Although Python doesn't require a main()
function, you can use one for structure, especially in larger programs. Use the following construct to define and call main()
explicitly:
Example: Using main()
def main():
print("This is the main function.")
print(f"Square of 5 is: {square(5)}")
def square(x):
return x ** 2
# Ensuring the script runs `main()` only when executed directly
if __name__ == "__main__":
main()
__name__
: A built-in variable that equals"__main__"
when the script is executed directly.- Purpose: Prevents parts of the script from running when imported as a module.
5. Why Use if __name__ == "__main__":
?
- Ensures your script behaves differently when:
- Run directly: Executes
main()
. - Imported as a module: Doesn't execute
main()
.
- Run directly: Executes
- Common in reusable libraries and multi-module projects.
6. Function Composition and Usage
Functions can be composed to build more complex programs.
Example: Composing Functions
def main():
number = 7
print(f"Square of {number}: {square(number)}")
print(f"Cube of {number}: {cube(number)}")
def square(x):
return x ** 2
def cube(x):
return x ** 3
if __name__ == "__main__":
main()
7. Summary: Functions in Python
Feature | Python Syntax | Notes |
---|---|---|
Define Function | def function_name(params): |
Use def keyword. |
No Return Type Needed | N/A | Python infers the return type. |
No Parameter Types | N/A | Dynamically typed parameters. |
Call Function | function_name(args) |
Pass arguments directly. |
Exponentiation | x ** y |
x to the power of y . |
Optional main() |
if __name__ == "__main__": |
Controls script behavior when executed. |
This flexibility makes Python functions not only easier to write but also highly adaptable to different programming paradigms.
K) Object-Oriented Programming in Python: An Introduction
Python is an object-oriented programming (OOP) language, and this paradigm focuses on objects that combine properties (data) and methods (functions). Here's a breakdown of how Python implements OOP, including creating and working with classes and methods.
1. Objects and Classes
- Objects are instances of a class, analogous to structs in C, but with additional functionality.
- Classes define the blueprint for an object, including its properties and methods.
2. Defining a Class
- Use the
class
keyword to define a class. - Inside a class, define properties and methods that belong to objects of that class.
Example:
class Student:
# Constructor (called when creating a new object)
def __init__(self, name, student_id):
self.name = name # Property: name
self.student_id = student_id # Property: ID
# Method to change the student ID
def change_id(self, new_id):
self.student_id = new_id
# Method to print student details
def display(self):
print(f"{self.name} - {self.student_id}")
3. Understanding self
- The first parameter of all methods in a class is
self
. self
represents the instance of the class. It allows methods to access and modify object properties.
4. Creating and Using Objects
To create an object (or instance) of the Student
class:
# Create a new Student object
student1 = Student("Jane", 10)
# Display initial details
student1.display() # Output: Jane - 10
# Change the student's ID
student1.change_id(11)
# Display updated details
student1.display() # Output: Jane - 11
5. Key Features of Classes and Methods
a) Constructor (__init__
)
- Automatically called when a new object is created.
- Used to initialize object properties.
Example:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
b) Defining Methods
- Methods operate on the object.
- The first parameter (
self
) ensures the method knows which object it’s working with.
Example:
def change_id(self, new_id):
self.student_id = new_id
6. Properties vs. Methods
- Properties: Variables belonging to an object (e.g.,
self.name
,self.student_id
). - Methods: Functions that perform actions on or using the object's data.
7. Full Example: Student Class
Here’s a complete example to demonstrate Python's object-oriented approach:
class Student:
# Constructor
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
# Method to change the student ID
def change_id(self, new_id):
self.student_id = new_id
# Method to display the student's details
def display(self):
print(f"{self.name} - {self.student_id}")
# Create an instance of the Student class
student1 = Student("Jane", 10)
# Display student details
student1.display() # Output: Jane - 10
# Change the student ID
student1.change_id(11)
# Display updated details
student1.display() # Output: Jane - 11
8. Key Concepts in OOP
Concept | Explanation |
---|---|
Class | Blueprint for creating objects. |
Object | Instance of a class, combining properties and methods. |
Property | Data associated with an object (e.g., self.name ). |
Method | Functions that belong to a class and operate on its objects. |
Constructor (__init__ ) |
Special method to initialize an object’s properties. |
self |
Reference to the specific object the method is called on. |
9. Extending Functionality
a) Adding More Methods
You can easily add more methods to extend the class's functionality.
Example:
class Student:
# Constructor
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
# Method to change the student's name
def change_name(self, new_name):
self.name = new_name
# Method to compare student IDs
def has_same_id(self, other_student):
return self.student_id == other_student.student_id
b) Using the New Methods
# Create two Student objects
student1 = Student("Alice", 10)
student2 = Student("Bob", 10)
# Compare their IDs
print(student1.has_same_id(student2)) # Output: True
10. Summary: OOP
Object-oriented programming in Python focuses on creating reusable, organized, and modular code through the use of classes and objects. Key features like properties, methods, and the self
parameter allow for efficient and clean programming practices.
L) Key Takeaways: Python Style, Modules, and Usage
Python emphasizes readability and style. Here's a breakdown of the important points you need to know based on the provided content:
1. Good Style in Python
-
Indentation Matters:
- Unlike C, Python uses indentation (tabs or spaces) to define code blocks, such as those within
if
statements,for
loops, and functions. - Improper indentation will cause syntax errors.
- Unlike C, Python uses indentation (tabs or spaces) to define code blocks, such as those within
-
Style Guide:
- Follow consistent indentation (usually 4 spaces per level).
- Use the CS50 style guide for best practices if you're already familiar with it.
2. Importing Modules
- Python uses
import
instead of#include
(as in C). - Modules are collections of functions and variables that you can include in your program.
Example:
import cs50 # Importing the CS50 library
x = cs50.get_int("Enter an integer: ") # Using a function from the library
3. Running Python Code
-
Pre-written Python files:
-
Save your code in a
.py
file. -
Run the code using:
python your_file.py
-
-
Interactive Mode:
- Open the Python interpreter by typing
python
in the terminal. - Enter and execute Python commands line by line.
- Open the Python interpreter by typing
4. Making Python Files Executable
To run Python files like a compiled C program (./hello
), follow these steps:
-
Add the Shebang Line:
-
At the top of your Python file, add:
#!/usr/bin/env python3
-
-
Change File Permissions:
-
Make the file executable:
chmod +x your_file.py
-
-
Run the File:
-
Execute it directly:
./your_file.py
-
5. Python Advantages
-
Interpreted Language:
- No need to compile your code; it runs line-by-line.
- Easier for debugging during development.
-
Versatile Use Cases:
- Ideal for data science, web development, and string manipulation.
6. Exploring Python Further
-
Flask:
- Python is widely used in web development with frameworks like Flask.
- Flask enables quick and flexible web app creation.
-
CS50 in Python:
- Functions like
cs50.get_int()
replicate the behavior ofget_int()
from C's CS50 library, but they're methods you call usingcs50.
.
- Functions like
Practical Example
Here’s a Python file example using the concepts:
#!/usr/bin/env python3
import cs50 # Import CS50 library
def main():
# Get user input
name = cs50.get_string("What is your name? ")
print(f"Hello, {name}!")
if __name__ == "__main__":
main() # Explicitly calling main()
Steps:
-
Save it as
hello.py
. -
Make it executable:
chmod +x hello.py
-
Run it:
./hello.py
Final Notes: Transitioning from C to Python
- Python’s flexibility and readability make it an excellent tool for beginner and advanced programmers alike.
- Modules and interactive interpreters offer versatility for experimentation and execution.
- Transitioning from C to Python simplifies many tasks but requires adapting to Python's stricter emphasis on indentation and conventions.
Z) 🗃️ Glossary
File | Definition |
---|
Uncreated files | Origin Note |
---|