KEMBAR78
Data and Variable | PDF | Python (Programming Language) | Control Flow
0% found this document useful (0 votes)
4 views44 pages

Data and Variable

The document contains lecture notes for a 3-hour Python foundations course aimed at beginner programmers, covering data types, variables, and strings. It includes detailed explanations of numeric data types, string basics, string methods, and practical coding assignments, along with a quiz for assessment. The course emphasizes hands-on coding examples and problem-solving using Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views44 pages

Data and Variable

The document contains lecture notes for a 3-hour Python foundations course aimed at beginner programmers, covering data types, variables, and strings. It includes detailed explanations of numeric data types, string basics, string methods, and practical coding assignments, along with a quiz for assessment. The course emphasizes hands-on coding examples and problem-solving using Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Lecture Notes: Python Foundations - Data Types, Variables,

and Strings

Total Duration: 3 Hours


Instructor: Ashfak Yeafi
Target Audience: Beginner Programmers

Hour 1: The Building Blocks - Variables and Numeric Data


Types

Part 1: Introduction & What is a Variable? (15 mins)

 Concept: A variable is like a labeled box in computer memory where you


can store data (a value). The label is the variable name, and the content is
the value.
 Analogy: Imagine a kitchen with containers labeled "Sugar," "Flour,"
"Coffee." You can use the label to access the contents, and you can even
replace the contents of the container without changing the label.
 The Assignment Operator (=):

o In Python, = does not mean "equals" like in math. It means "assign the
value on the right to the variable on the left."
o name = "Ashfak" translates to "Take the value 'Ashfak' and store it in a

variable box labeled name."

Part 2: Numeric Data Types (20 mins)

Python has three main number types:

1. Integers (int): Whole numbers, positive or negative.

o age = 25, score = -10, count = 0


2. Floating-Point Numbers (float): Numbers with a decimal point.

o height = 5.9, pi = 3.14159, temperature = -2.5

3. Complex Numbers (complex): (Mention briefly, less common) Numbers with


a real and imaginary part.

o a = 1 + 2j

Fun Coding: Dynamic Typing (10 mins)

 Python is "dynamically typed." This means you don't have to declare the
variable type; Python figures it out based on the value you assign.
 Example: The Shape-Shifting Variable
python

# Let's see what type Python thinks our variable is


my_var = 100
print(type(my_var)) # Output: <class 'int'>

my_var = 100.5
print(type(my_var)) # Output: <class 'float'>

my_var = "I am text now!"


print(type(my_var)) # Output: <class 'str'>
print(my_var) # Output: I am text now!

The variable my_var changed its type from int to float to str!

Part 3: Basic Operations with Numbers (15 mins)

 Arithmetic Operators:

o + (Addition), - (Subtraction), * (Multiplication), / (Division - always returns

a float)
o // (Floor Division - rounds down to nearest integer), % (Modulus - returns the

remainder)
o ** (Exponentiation - e.g., 2 ** 3 is 8)

Problem & Solution: The Pizza Calculator


 Problem: You have 15 friends and you want to order pizza. Each pizza has 8
slices. How many pizzas do you need to order so everyone (including you)
gets at least 3 slices?
 Solution:
python

total_people = 15 + 1 # friends + you


slices_needed = total_people * 3
pizzas_needed = slices_needed / 8

print("You need", pizzas_needed, "pizzas.") # Output: You need 6.0 pizzas.


# But you can't buy 0.75 of a pizza! You need to round up.
import math # We need a special tool for rounding up
pizzas_to_order = math.ceil(pizzas_needed) # ceil() rounds up to the nearest
integer
print("So, you should order", pizzas_to_order, "pizzas.") # Output: So, you
should order 6 pizzas.

Hour 2: The Art of Text - String Variables

Part 1: String Basics & Creation (20 mins)

 Concept: A string (str) is a sequence of characters enclosed in quotes.


 Creation: You can use single quotes ('...'), double quotes ("..."), or triple
quotes ('''...''' or """...""" for multi-line strings).
python

name1 = 'Alice'
name2 = "Bob"
story = """This is a very long story
that spans across multiple lines
in your code."""
print(story)

Part 2: String Indexing and Slicing (25 mins)


 Concept: Each character in a string has a position, called an index.
Indexing in Python starts at 0.
 Let's use the string language = "Python"

P y t h o n

0 1 2 3 4 5

- -
-5 -4 -3 -1 (Negative Indexing)
6 2

 Indexing: Access a single character.

o print(language[0]) # Output: P

o print(language[-1]) # Output: n (Awesome, huh?)

 Slicing: Access a range of characters. [start:stop:step]

o print(language[0:2]) # Output: Py (starts at 0, goes up to but does NOT

include 2)
o print(language[2:6]) # Output: thon

o print(language[::2]) # Output: Pto (start to end, every 2nd character)

o print(language[::-1]) # Output: nohtyP (The classic way to reverse a string!)

Fun Coding: The Secret Code (15 mins)

 Let's encode and decode a secret message by shifting characters.

python

# Simple Caesar Cipher


message = "hello"
secret = "" # Start with an empty string

for char in message:


secret += chr(ord(char) + 3) # Shift each character's Unicode value by 3

print("Secret message:", secret) # Output: khoor

# Now, let's decode it


decoded = ""
for char in secret:
decoded += chr(ord(char) - 3) # Shift back by 3

print("Decoded message:", decoded) # Output: hello

Hour 3: Practice, Assignments, and Assessment

Part 1: String Methods (20 mins)

Strings have built-in superpowers called methods.


python
text = " hello World! "

print(text.upper()) # " HELLO WORLD! "


print(text.lower()) # " hello world! "
print(text.strip()) # "hello World!" (removes spaces from ends)
print(text.replace("o", "0")) # " hell0 W0rld! "
print(text.find("World")) # 9 (finds the starting index)
print("llo" in text) # True (checks if substring exists)

Problem & Solution: Username Formatter

 Problem: A user enters their name with weird capitalization and spaces.
Create a standard username: all lowercase, no spaces.
 Solution:
python

user_input = " AsHfAk YeAfI "


username = user_input.strip().lower().replace(" ", "_")
print("Your username is:", username) # Output: Your username is: ashfak_yeafi

Part 2: Coding Assignments (30 mins)

Assignment 1: The Mad Libs Generator


Create a program that asks the user for an adjective, a noun, and a verb.
Then, print a funny story using those words. (e.g., "The [adjective] [noun]
decided to [verb] today!")

Assignment 2: The Email Slicer


Write a program that asks the user for their email address and then extracts
their username and domain name.

 Example: Input: yeafi.ashfak@gmail.com


 Output:
Your username is yeafi.ashfak

Your domain is gmail.com

 Hint: Use the .split() method and indexing.

Part 3: 30-Minute Quiz (30 mins)

Python Data Types & Variables Quiz

Section A: Multiple Choice (5 x 2pts = 10pts)

1. What is the output of print(type(10/2))?


a) <class 'int'>
b) <class 'float'> (Answer)
c) <class 'str'>
2. Which operator is used for exponentiation?
a) ^
b) *
c) ** (Answer)
3. What does mystring[-1] return?
a) The first character
b) The last character (Answer)
c) It causes an error
4. The "hello".upper() method returns:
a) "HELLO" (Answer)
b) "hello"
c) "Hello"
5. What is the result of "Python"[1:4]?
a) "Pyt"
b) "yth" (Answer)
c) "thon"

Section B: Code Output (2 x 5pts = 10pts)


What is the output of the following code snippets?

6. python
7. x = 5
8. y = 2
9. result = (x + y) ** 2
print(result)

Answer: 49

10. python
11. text = "Programming is fun!"
print(text[7:9].lower() + text[-4])

Answer: isn (text[7:9] is "is", .lower() makes it "is", text[-4] is "n"`)

Section C: Short Coding (10pts)


8. Write a program that:
* Asks the user for their full name.
* Prints the name in all uppercase letters.
* Prints the length of their name (including spaces).
* Prints only their first name (assume the first name is everything before the
first space).
text
**Example Answer:**
```python
full_name = input("Enter your full name: ")
print(full_name.upper())
print("Length:", len(full_name))
first_name = full_name.split()[0] # Splits into a list and takes the first
item
print("First name:", first_name)
```

Total Quiz Points: 30

Answers:

1. b
2. c
3. b
4. a
5. b
6. 49
7. isn
8. See example code.

ChatGPT said:

Python Lecture Notes on Data Types, Variables, and


Numeric/String Operations
1. Introduction to Data Types and Variables in Python (30 minutes)

What are Variables?

 A variable is a symbolic name for a data location in memory. Variables are used to store
data in a program.
 Variables in Python don't need to be declared before use. They are created when you first
assign a value to them.

Example:

x = 10
name = "Alice"

Python Data Types

Python has several built-in data types, which are divided into categories:

1. Numeric Types: int, float, complex


2. Sequence Types: str, list, tuple
3. Mapping Type: dict
4. Set Types: set, frozenset
5. Boolean Type: bool
6. Binary Types: bytes, bytearray, memoryview

2. Numeric Data Types (45 minutes)

Python supports different numeric data types that help store numerical values:

 int: Integer numbers (e.g., 1, 42, -3)


 float: Floating-point numbers (e.g., 3.14, -0.007)
 complex: Complex numbers (e.g., 3 + 4j)

1. Integers (int)

 Represents whole numbers.

age = 25
height = -100

2. Floats (float)

 Represents decimal numbers.


pi = 3.14159
temperature = -2.5

3. Complex Numbers (complex)

 These numbers have a real and an imaginary part.

complex_number = 3 + 4j

Examples of Numeric Operations:

 Addition: 5 + 10
 Subtraction: 10 - 3
 Multiplication: 4 * 7
 Division: 8 / 4
 Exponentiation: 2 ** 3
 Modulo (remainder of division): 5 % 2

Problem 1: Write a program to calculate the area of a circle given its radius.

 Formula for the area of a circle: Area = π * radius²

Solution:

import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"The area of the circle with radius {radius} is {area}")

3. String Data Type (45 minutes)

What is a String?

 A string is a sequence of characters enclosed in single, double, or triple quotes.

Examples:

greeting = "Hello, World!"


name = 'Alice'
multiline = '''This is
a multi-line
string.'''

String Operations:

 Concatenation: Joining strings together.


first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

 Repetition: Repeating strings.

echo = "Hi! " * 3


print(echo)

 Slicing: Accessing parts of a string.

text = "Hello, Python!"


print(text[0:5]) # Outputs: Hello

String Methods:

 lower(): Converts to lowercase


 upper(): Converts to uppercase
 strip(): Removes leading/trailing whitespaces
 replace(): Replaces parts of the string

message = " Hello, Python! "


print(message.strip()) # Removes spaces
print(message.lower()) # Converts to lowercase

Problem 2: Write a program that takes a user’s name and prints a personalized
greeting message.

Solution:

name = input("Enter your name: ")


print(f"Hello, {name}! Welcome to Python programming.")

4. Fun Coding Examples (30 minutes)

Fun Example 1: Palindrome Checker

 A palindrome is a word that reads the same forward and backward (e.g., "radar").

Solution:

def is_palindrome(word):
return word == word[::-1]

word = input("Enter a word to check if it's a palindrome: ")


if is_palindrome(word):
print(f"{word} is a palindrome!")
else:
print(f"{word} is not a palindrome.")

Fun Example 2: Guess the Number Game

 The user has to guess a randomly generated number between 1 and 100.

Solution:

import random

number = random.randint(1, 100)


guess = None

while guess != number:


guess = int(input("Guess a number between 1 and 100: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")

print(f"Congratulations! You guessed the correct number: {number}")

5. Coding Assignments (45 minutes)

Assignment 1: Convert Temperature

Write a Python program that converts temperature from Fahrenheit to Celsius. The formula for
conversion is:
C=(F−32)×59C = (F - 32) \times \frac{5}{9}C=(F−32)×95

Hint: Ask the user for a Fahrenheit value and print the Celsius equivalent.

Assignment 2: Count Vowels

Write a Python program that counts the number of vowels (a, e, i, o, u) in a given string.

Hint: Use a loop and string methods to count vowels.

Assignment 3: Simple Calculator

Write a Python program to create a simple calculator that can:

1. Add
2. Subtract
3. Multiply
4. Divide
It should take two numbers and an operator (+, -, *, /) from the user and print the result.

6. Quiz Time! (30 minutes)

Quiz Questions:

1. What is the output of the following code?

x = 10
y = 2
z = x ** y
print(z)

 A) 10
 B) 100
 C) 20
 D) 1024

2. What is the result of the expression "Hello" + " " + "World"?

 A) "Hello World"
 B) "Hello"
 C) "World"
 D) Error

3. Which of the following is used to represent a complex number in Python?

 A) 3 + 4
 B) 3 + 4j
 C) 3j + 4
 D) None of the above

4. What will be the output of the following code?

a = "Python"
b = a * 3
print(b)

 A) PythonPythonPython
 B) Python
 C) PytPytPyt
 D) Error

5. Which function is used to convert a string to lowercase?


 A) lower()
 B) upper()
 C) capitalize()
 D) strip()

Quiz Answers:

1. B) 100
2. A) "Hello World"
3. B) 3 + 4j
4. A) PythonPythonPython
5. A) lower()

7. Conclusion and Recap

Key Takeaways:

 Variables in Python are used to store data, and we don't need to declare their type
explicitly.
 Data types in Python include numeric types (int, float, complex) and string types.
 String manipulation (concatenation, slicing, and using methods like lower(), strip())
is an essential skill in Python.
 Understanding basic operations with numbers and strings is the foundation for more
complex problems.

Write 3 hours unique lecture notes of Python on fundamental of Python, introduction to Python, writing
Python code, running Python code, 30 minutes 20 quiz question with answers,

Of course. Here are unique and comprehensive lecture notes for a 3-hour introductory Python
session, complete with a quiz.

Lecture Notes: Python Fundamentals - Your First Steps into Code

Total Duration: 3 Hours


Instructor: Ashfak Yeafi
Target Audience: Absolute Beginners
Hour 1: The "Why" and "What" - Introduction to Python

Part 1: Welcome & Why Python? (20 mins)

 The Big Picture: What is Programming?


o Analogy: Giving instructions to a incredibly literal, super-fast, but very dumb friend. You must
be precise and unambiguous.

o Programming is the process of creating a set of instructions that tell a computer how to perform a
task.

 Why Python? The "Swiss Army Knife" of Languages


o Readability: Its syntax is clear and looks almost like English. This reduces the "cost of learning"
and makes code easier to maintain.

o Versatility: Used in:


 Web Development (Django, Flask)

 Data Science & Machine Learning (Pandas, NumPy, TensorFlow)

 Automation & Scripting (Automate boring tasks like renaming files, web scraping)

 Software Development

 Scientific Computing

o Community: Huge, supportive community. Whatever problem you have, someone has already
solved it.

o It's Beginner-Friendly: The language itself helps you focus on learning programming concepts
rather than fighting complex syntax rules.
Part 2: Setting the Stage - The Python Ecosystem (25 mins)

 Python Interpreter: The "engine" that reads and executes your Python code. You need to have
this installed on your computer.

 Code Editor vs. IDE:


o Code Editor (e.g., VS Code, Sublime Text): A powerful text editor with features like syntax
highlighting and code formatting. Like a sophisticated word processor for code.

o IDE - Integrated Development Environment (e.g., PyCharm, Thonny): An all-in-one


powerhouse. It includes a code editor, debugger, interpreter, and other tools bundled
together. Recommendation for beginners: Start with a simple editor like VS Code.

 Live Demo: Installation Check


o Open the Command Prompt (Windows) or Terminal (Mac/Linux).

o Type python --version or python3 --version.

o If a version number (e.g., Python 3.11.4) appears, you're good to go!

Part 3: Our First Conversation with Python (15 mins)

 Mode 1: The Interactive Shell (REPL)


o REPL: Read-Eval-Print Loop. It's a conversation. You type a command, Python reads it,
evaluates it, prints the result, and loops back to wait for your next command.

o How to access: Type python or python3 in your terminal.

o Let's Try:
python

>>> print("Hello, World!")


Hello, World!
>>> 5 + 3
8
>>> name = "Ashfak"
>>> name
'Ashfak'

o Perfect for: Testing a single line of code, quick calculations, exploring how something works.

Hour 2: The "How" - Writing and Running Python Code

Part 1: Mode 2: Writing a Script (File) (20 mins)

 Concept: A script is a file (with a .py extension) containing a sequence of Python instructions.
This is how you write real programs.

 Step-by-Step:
1. Open your code editor.

2. Create a new file.

3. Type: print("My first Python script!")

4. Save the file as hello.py on your desktop. The .py extension is crucial!

Part 2: Running Your Script (20 mins)

 Method 1: Command Line (The Fundamental Way)


1. Open your Terminal/Command Prompt.

2. Navigate to where you saved the file (e.g., cd Desktop).

3. Type the command: python hello.py or python3 hello.py.

4. You should see the output: My first Python script!

 Method 2: Using the Editor's Run Button


o Most editors (VS Code, PyCharm) have a "Play" button (▶️) that will run the current file. This is
the most common method for development.

 Why this matters: The script mode allows for complexity and reusability that the interactive
shell does not.

Part 3: Syntax & Statements - The Rules of the Game (20 mins)

 Statements: An instruction that the Python interpreter can execute.


Our print("Hello") and name = "Ashfak" are statements.

 The print() Function: Your best friend for debugging. It outputs text to the screen.
o print("Hello") -> Hello

o print("Hello", "World") -> Hello World (Multiple items separated by a space)

o print("Hello\nWorld") -> Hello (The \n is a newline character)

World

 Comments: Notes for humans, ignored by Python. Use # for a single-line comment.
python

# This is a comment. It won't be executed.


print("This will run.") # This is an inline comment

 Indentation: Python uses indentation (whitespace at the beginning of a line) to define blocks of
code. This is mandatory and part of the syntax. We'll see more of this in future lectures on
loops and functions.

Hour 3: Practice and Assessment

Part 1: Let's Build Something Simple (30 mins)


Project: The Personalized Greeting Generator
We will write a script that asks for the user's name and age and prints a personalized greeting.
python

# Get input from the user and store it in variables


user_name = input("What is your name? ") # input() always gives us a string
user_age = input("How old are you? ")

# Print a greeting using the collected data


print("Hello", user_name + "!") # Using + to concatenate strings
print("You are", user_age, "years old.")

# Let's do a simple calculation.


# We need to convert the string 'user_age' to an integer (number) first.
age_in_5_years = int(user_age) + 5
print("In 5 years, you will be", age_in_5_years, "years old.")

Key Concepts Demonstrated:

 Variables (user_name, user_age)

 The input() function for user input.

 The print() function for output.

 Basic data types: str (string from input), int (integer after conversion).

 Type conversion: int(user_age) to change a string to a number.

Part 2: 30-Minute Quiz (30 mins)

Python Fundamentals Quiz (20 Questions)

Section A: Concepts (10 x 1pt = 10pts)


Circle the best answer.

1. Python is a good first language because it is:


a) Very old
b) Readable and versatile (Answer)
c) Only used for websites

2. The Python interpreter is responsible for:


a) Making the code look pretty
b) Reading and executing the code (Answer)
c) Connecting to the internet

3. What does IDE stand for?


a) Internal Development Engine
b) Integrated Development Environment (Answer)
c) International Data Exchange

4. What is the REPL best used for?


a) Writing a 1000-line program
b) Quick tests and experiments (Answer)
c) Designing graphics

5. A Python script must be saved with what file extension?


a) .txt
b) .exe
c) .py (Answer)

6. Which function is used to get input from a user?


a) print()
b) get()
c) input() (Answer)

7. Which function is used to output text to the screen?


a) print() (Answer)
b) output()
c) echo()
8. In Python, # is used to:
a) Create a variable
b) Write a comment (Answer)
c) Perform division

9. The statement name = "Alice" is an example of:


a) Printing a value
b) Assigning a value to a variable (Answer)
c) Creating a comment

10. The command to run a script named myscript.py from the terminal is:
a) run myscript.py
b) python myscript.py (Answer)
c) start myscript.py

Section B: Code Reading & Prediction (5 x 2pts = 10pts)


What is the output of the following code snippets?

11. Code:

python

print(2 + 3 * 2)

Answer: 8

12. Code:
python

food = "pizza"
print("I love " + food)

Answer: I love pizza

13. Code:
python
# print("This is a test")
print("Hello World")

Answer: Hello World

14. Code:
python

value = input("Enter a number: ")


# User types '10'
print(value * 2)

Answer: 1010 (It's a string, so it concatenates/duplicates)

15. Code:
python

value = int("10")
print(value * 2)

Answer: 20 (Now it's an integer, so it does math)

Section C: True or False (5 x 1pt = 5pts)


16. Python uses curly braces {} to define code blocks. (False)
17. Indentation in Python is only for readability and is optional. (False)
18. The = symbol is used to check if two values are equal. (False)
19. The input() function returns a string. (True)
20. You can write a Python program without using the print() function. (True)

Total Quiz Points: 25

Answer Key:

1. b

2. b
3. b

4. b

5. c

6. c

7. a

8. b

9. b

10. b

11. 8

12. I love pizza

13. Hello World

14. 1010

15. 20

16. False

17. False

18. False

19. True

20. True
Lecture Notes: Introduction to Python Programming

Part 1: Fundamentals of Python (1 Hour)

1. What is Python?

 Python is a high-level, interpreted programming language, known for its readability and
simplicity.
 It was created by Guido van Rossum and first released in 1991.
 Python is a general-purpose language used in many domains such as web development,
data analysis, artificial intelligence, automation, and more.

2. Key Features of Python

 Simple and Easy to Learn: Python's syntax is clean and easy to understand.
 Interpreted Language: Python code is executed line-by-line, without the need for a
separate compilation step.
 Dynamically Typed: Python does not require explicit variable declarations.
 Cross-Platform: Python code can run on various platforms such as Windows, Linux, and
macOS without modification.
 Extensive Standard Library: Python has a large collection of modules that help perform
common tasks.

3. Python Applications

 Web Development: Frameworks like Django, Flask.


 Data Science: Libraries like pandas, numpy, matplotlib.
 Automation: Writing scripts to automate tasks.
 Machine Learning/AI: Libraries like TensorFlow, Scikit-Learn.
 Game Development: Pygame for building simple games.

Part 2: Introduction to Python (30 Minutes)

1. Setting Up Python

 Installation: Python can be downloaded from python.org. Make sure to check the option
"Add Python to PATH" during installation.
 IDE Options: You can use various IDEs like PyCharm, VS Code, or simple text editors
such as Sublime Text or Notepad++.
 REPL (Read-Eval-Print Loop): The Python interpreter allows you to interactively
execute Python commands.
2. Python Syntax Basics

 Variables and Data Types:


o Integer (int): Whole numbers (e.g., 5, -3, 100)
o Float (float): Decimal numbers (e.g., 3.14, -0.5)
o String (str): Sequence of characters (e.g., "Hello", "Python 101")
o Boolean (bool): True or False
o List (list): Ordered collection (e.g., [1, 2, 3])
o Tuple (tuple): Immutable ordered collection (e.g., (1, 2, 3))
o Dictionary (dict): Key-value pairs (e.g., {"name": "Alice", "age": 25})

Example:

x = 10 # Integer
name = "Python" # String
is_active = True # Boolean
pi = 3.14 # Float

3. Basic Operators in Python

 Arithmetic Operators:
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o // (Floor Division)
o % (Modulo)
o ** (Exponentiation)

Example:

a = 10
b = 3
print(a + b) # Output: 13
print(a / b) # Output: 3.3333

 Comparison Operators:
o == (Equal to)
o != (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)

Example:

a = 10
b = 3
print(a > b) # Output: True

4. Control Structures

 If-Else Statement:
 x = 10
 if x > 5:
 print("Greater than 5")
 else:
 print("Less than or equal to 5")

 Loops:
o For Loop: Iterates over a sequence (like a list, string, or range).
o for i in range(5):
o print(i)

o While Loop: Repeats as long as a condition is True.


o x = 0
o while x < 5:
o print(x)
o x += 1

Part 3: Writing and Running Python Code (1 Hour)

1. Writing Your First Python Program

Create a new file called hello.py:

print("Hello, World!")

 This program simply prints the message "Hello, World!" to the console.

2. Running Python Code

 Using the Command Line:


o Open the terminal/command prompt.
o Navigate to the directory where the Python file is saved.
o Run the file by typing:
o python hello.py

 Using an IDE:
o In your IDE, you can run the Python file by clicking on the Run button or
pressing the shortcut key (usually F5 or Ctrl+Shift+F10).

3. Error Handling and Debugging

 Python provides error messages that help identify problems in your code.
 Example of a Syntax Error:
 print("Hello, World!) # Missing closing quote

This will give an error like:

SyntaxError: EOL while scanning string literal

 Try-Except Block for handling errors:


 try:
 a = 1 / 0
 except ZeroDivisionError:
 print("Cannot divide by zero!")

4. Functions in Python

 Functions allow us to reuse code and make programs more modular.


 def greet(name):
 return f"Hello, {name}!"

 print(greet("Alice")) # Output: Hello, Alice!

Part 4: 30-Minute Quiz (20 Questions)

1. What is the correct way to declare a variable in Python?

 a) var x = 10
 b) x = 10
 c) int x = 10
 d) variable x = 10

Answer: b) x = 10

2. Which of the following is a valid Python data type?

 a) int
 b) string
 c) bool
 d) All of the above

Answer: d) All of the above

3. How do you add a comment in Python?

 a) // This is a comment
 b) /* This is a comment */
 c) # This is a comment
 d) -- This is a comment
Answer: c) # This is a comment

4. What does the following Python code print?

x = 5
print(x == 5)

 a) True
 b) False
 c) 5
 d) Error

Answer: a) True

5. Which of the following is used to define a function in Python?

 a) function
 b) def
 c) func
 d) define

Answer: b) def

6. What is the output of the following code?

x = [1, 2, 3]
print(x[1])

 a) 1
 b) 2
 c) 3
 d) Error

Answer: b) 2

7. How can you check the type of a variable in Python?

 a) type(variable)
 b) check(variable)
 c) is_type(variable)
 d) var_type(variable)

Answer: a) type(variable)

8. What is the correct syntax for a for loop in Python?

 a) for i = 0 to 10:
 b) for i in range(10):
 c) for i in 0..10:
 d) for i from 0 to 10:

Answer: b) for i in range(10):

9. Which of the following is NOT a valid Python operator?

 a) +
 b) -
 c) **
 d) :=

Answer: d) :=

10. What does the following code output?

print(10 / 3)

 a) 3
 b) 3.0
 c) 3.3333333
 d) Error

Answer: c) 3.3333333

11. Which function is used to accept input from the user in Python?

 a) input()
 b) read()
 c) scanf()
 d) get_input()

Answer: a) input()

12. What is a tuple in Python?

 a) A mutable ordered collection


 b) A immutable ordered collection
 c) A key-value pair
 d) A list that can't change

Answer: b) A immutable ordered collection

13. How do you define a dictionary in Python?


 a) dict = {1, 2, 3}
 b) dict = [1, 2, 3]
 c) dict = (1, 2, 3)
 d) dict = {"a": 1, "b": 2}

Answer: d) dict = {"a": 1, "b": 2}

14. Which statement is used to exit a loop in Python?

 a) exit
 b) break
 c) stop
 d) end

Answer: b) break

15. How do you create a comment in Python?

 a) // comment
 b) /* comment */
 c) # comment
 d) <!-- comment -->

Answer: c) # comment

16. What will the following code print?

x = 5
x += 3
print(x)

 a) 8
 b) 5
 c) 3
 d) Error

Answer: a) 8

17. Which of the following will throw an error?

 a) 10 / 2
 b) "hello" / 2
 c) 10 // 2
 d) 10 % 2

Answer: b) "hello" / 2
18. What is the correct way to write a list in Python?

 a) [1, 2, 3]
 b) (1, 2, 3)
 c) {1, 2, 3}
 d) 1, 2, 3

Answer: a) [1, 2, 3]

19. What is the result of 10 % 3?

 a) 3
 b) 1
 c) 2
 d) 10

Answer: b) 1

20. What does print(len("Python")) output?

 a) 5
 b) 6
 c) 7
 d) Error

Answer: b) 6

ChatGPT said:

Lecture Notes: Preparing the Machine Environment for Python Development


Objective:

In this lecture, we'll walk through setting up your machine for Python development, including
the installation of Python, libraries, package management, IDEs, and environment configuration.

1. Installing Python

1.1 Checking for Python

Before installing Python, it’s important to check if it’s already installed on your machine.

For Windows:

 Open Command Prompt (search for cmd).


 Type python --version or python -V.

For macOS/Linux:

 Open Terminal.
 Type python3 --version or python3 -V.

If Python is not installed, proceed to installation.

1.2 Downloading Python

 Visit the official Python website.


 Choose the version suitable for your system (Windows, macOS, or Linux).
 Download the installer.

1.3 Installing Python

 For Windows: Run the installer. Ensure to check the box “Add Python to PATH” before
clicking "Install Now."
 For macOS/Linux: Follow the installation instructions on the website, or use a package
manager like brew for macOS:
 brew install python3

For Linux, use the respective package manager, for example:

sudo apt install python3

1.4 Verifying Installation


Once Python is installed, verify it again by running python3 --version or python --version
in your terminal or command prompt.

2. Setting Up Python Package Management

2.1 Installing pip

pip is the package installer for Python. It is typically included in the Python installation, but if
it's missing, you can install it by following these steps:

 For Windows/Mac/Linux:
 python3 -m ensurepip --upgrade

2.2 Using pip

You can now use pip to install and manage Python libraries. For example:

pip install numpy

To check installed packages:

pip list

2.3 Virtual Environments

It is a best practice to use virtual environments for Python projects. This ensures dependencies
are isolated and do not conflict with system packages.

 Create a virtual environment:


 python3 -m venv myenv

 Activate the virtual environment:


o For Windows:
o .\myenv\Scripts\activate

o For macOS/Linux:
o source myenv/bin/activate

 Deactivate the virtual environment:


 deactivate

3. Python Libraries & Frameworks

3.1 Installing Common Libraries


The following libraries are essential for Python development, especially for data science,
machine learning, and general programming:

 NumPy: Numerical operations.


 Pandas: Data manipulation and analysis.
 Matplotlib: Plotting and data visualization.
 Scikit-learn: Machine learning algorithms.
 TensorFlow / PyTorch: Deep learning frameworks.

Install libraries using pip:

pip install numpy pandas matplotlib scikit-learn tensorflow

3.2 Managing Dependencies

 Requirements File: In a project, it’s a good practice to save all dependencies in a


requirements.txt file:
 pip freeze > requirements.txt

To install dependencies from the file:

pip install -r requirements.txt

4. Integrated Development Environments (IDEs)

4.1 Choosing an IDE

To improve your coding efficiency, it’s crucial to choose a good IDE. Some popular ones for
Python are:

 Visual Studio Code (VS Code): Free, open-source, highly customizable, and supports
Python.
 PyCharm: Comprehensive Python IDE with features like debugging, testing, and project
management.
 Jupyter Notebook: Interactive development environment, great for data science and
analysis tasks.

4.2 Setting Up VS Code for Python

1. Install VS Code: Download it from here.


2. Install Python Extension: In VS Code, go to Extensions (Ctrl+Shift+X), search for
"Python," and install it.
3. Configure Python Interpreter: After installing the extension, select the Python
interpreter by pressing Ctrl+Shift+P, then choose Python: Select Interpreter and
select your Python environment.
4.3 Setting Up Jupyter Notebook

1. Install Jupyter:
2. pip install notebook

3. Start Jupyter by running the following command in your terminal:


4. jupyter notebook

5. Version Control with Git

5.1 Installing Git

Git is essential for version control. To install it:

 For Windows: Download Git from Git for Windows.


 For macOS/Linux: Use Homebrew (macOS) or apt (Linux):
 brew install git # macOS
 sudo apt install git # Linux

5.2 Configuring Git

After installation, configure Git with your user name and email:

git config --global user.name "Your Name"


git config --global user.email "your_email@example.com"

5.3 Cloning a Repository

You can clone a repository to your local machine using:

git clone https://github.com/username/repository.git

6. Debugging and Testing

6.1 Debugging

Python comes with a built-in debugger pdb. To use it, add this line in your code:

import pdb; pdb.set_trace()

Alternatively, most IDEs like VS Code and PyCharm have built-in debuggers for a more user-
friendly experience.

6.2 Writing Tests


Unit tests are important for ensuring your code works as expected. Python has a built-in testing
framework unittest:

 Example of a basic test case:


 import unittest

 def add(a, b):
 return a + b

 class TestAddition(unittest.TestCase):
 def test_add(self):
 self.assertEqual(add(1, 2), 3)

 if __name__ == "__main__":
 unittest.main()

7. Documentation and Code Quality

7.1 Writing Docstrings

Good documentation is crucial for understanding code. Python supports docstrings to document
functions and classes:

def add(a, b):


"""
This function adds two numbers.

Parameters:
a (int): The first number.
b (int): The second number.

Returns:
int: The sum of the two numbers.
"""
return a + b

7.2 Linting and Formatting

To maintain code quality, use linters and formatters:

 Flake8: Linter for Python code.


 pip install flake8

 Black: Code formatter for Python.


 pip install black

You can integrate these tools with your IDE for automatic checking.
Conclusion

By the end of this lecture, you should be comfortable with setting up Python on your machine,
managing dependencies using pip and virtual environments, using IDEs for development, and
understanding the tools available for debugging, testing, and maintaining code quality.

Next steps involve applying these concepts in projects, ensuring that your development
environment is productive and efficient. Happy coding!

Write unique lecture notes of Python on preparing Machine environment set

Of course. Here are unique and comprehensive lecture notes focused solely
on setting up a professional machine learning environment in Python.

Lecture Notes: Building Your ML Workshop - Environment


Setup

Topic: Preparing a Robust Machine Learning Development Environment


Instructor: Ashfak Yeafi
Philosophy: "A craftsman is only as good as their tools. A messy workshop
leads to messy results." This lecture is about building a clean, organized, and
powerful workshop for your Data Science and ML projects.

1. The "Why": Beyond Simple Installation

Why is a proper setup so crucial?

 Reproducibility: Your code should run the same way on your laptop, your
colleague's desktop, and a cloud server. Environment management ensures
this.
 Dependency Hell: Project A needs Scikit-learn v1.0, but Project B needs
v1.2. Without isolation, they conflict and break.

 Cleanliness: Avoid polluting your system-wide Python installation. Keep


project-specific dependencies separate.

 Professional Practice: This is the standard workflow in industry and


research. Learning it early is a significant career advantage.

2. The Toolbox: Core Components

We will install and use three key tools:

1. Python & Pip: The core language and its package installer.

2. Conda (via Miniconda): A powerful package manager and environment


manager. It handles Python and non-Python (e.g., C++ libraries)
dependencies brilliantly, which is common in ML.

3. VS Code: A lightweight but powerful code editor with incredible Python


support.

4. Git: Version control system (essential, but we'll focus on setup).

3. Step-by-Step Setup Guide

Step 1: Install the Base System - Miniconda


 Why Miniconda over Anaconda? Anaconda comes with 150+ pre-installed
packages (bloated). Miniconda is a minimal installer that gives you just
Python, Conda, and the essentials. You then install only what you need,
keeping things lean.

 Action:
1. Go to the Miniconda documentation .

2. Download the installer for your OS (Windows, macOS, or Linux).

3. Run the installer.


 Windows: Use the graphical installer. Crucial: Check the box that says
"Add Miniconda3 to my PATH environment variable." If you miss this, you'll
have to do it manually later.

 macOS/Linux: Use the bash script in your terminal.

4. Verify the installation. Open a new Anaconda Prompt (Windows) or


Terminal (macOS/Linux) and type:
bash

conda --version

You should see a version number (e.g., conda 23.11.0).

Step 2: Your First Isolated Environment

Let's create an environment named ml-bootcamp running Python 3.10.

 Action: In your Conda prompt/terminal, run:

bash

conda create -n ml-bootcamp python=3.10

o create: The command to make a new environment.

o -n ml-bootcamp: Names the environment ml-bootcamp.


o python=3.10: Specifies the Python version.

 Activate the Environment:


o To use the environment, you must activate it. This changes your terminal's
context.

bash

conda activate ml-bootcamp

Notice your prompt now shows (ml-bootcamp), indicating you are working
inside this isolated workshop.

 Deactivate the Environment:


bash

conda deactivate

The (ml-bootcamp) disappears, and you are back in the "base" environment.

Step 3: Installing Core ML Packages

With your ml-bootcamp environment activated, let's install the essential


libraries.

The Core Quartet:

1. NumPy: The foundation for numerical computation. Everything else builds


on this.

2. Pandas: For data manipulation and analysis (working with tables).

3. Matplotlib: For basic plotting and visualization.

4. Scikit-learn: The go-to library for traditional machine learning algorithms.


Installation Command:
We'll use conda install for complex libraries (like SciPy) and pip install for
others, as Conda handles non-Python dependencies better.
bash

# Using conda for these is recommended as it manages underlying C/Fortran


libraries well
conda install numpy pandas scikit-learn matplotlib

# To use pip for a specific package inside a conda environment, you can do:
# pip install package-name

Verify Installations:
Start a Python shell in your activated environment and try to import them:
bash

python
python

>>> import numpy as np


>>> import pandas as pd
>>> import sklearn
>>> print("All imports successful!")
All imports successful!
>>> exit()

Step 4: Setting Up the Code Editor (VS Code)

1. Install VS Code: Download from code.visualstudio.com .

2. Install the Python Extension: Open VS Code, go to the Extensions tab


(Ctrl+Shift+X), search for "Python" (by Microsoft), and install it.

3. Select Your Python Interpreter:


o Open your project folder in VS Code.

o Open a .py file.

o Press Ctrl+Shift+P (Command Palette).


o Type "Python: Select Interpreter."

o Choose the one that points to your ml-bootcamp environment (e.g., Python
3.10.x ('ml-bootcamp': conda)).

Now, VS Code is using your isolated environment! Any package you


install via the terminal (with the env activated) will be available here.

4. The Grand Finale: The "Hello World" of ML

Let's test our entire setup by running a classic first script.

1. In VS Code, create a new file called test_environment.py.

2. Paste the following code:


python

# test_environment.py
# This script tests if our ML environment is set up correctly.
import sys
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

print(f"[✓] Python Version: {sys.version}")


print(f"[✓] NumPy Version: {np.__version__}")
print(f"[✓] Pandas Version: {pd.__version__}")

# Load a classic dataset


print("\n[ ] Loading Iris dataset...")
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target
print(f"[✓] Data shape: {df.shape}")
# Do a simple ML train-test split
print("[ ] Performing train-test split...")
X_train, X_test, y_train, y_test = train_test_split(df[iris.feature_names],
df['target'], test_size=0.2)
print(f"[✓] Training samples: {X_train.shape[0]}, Test samples:
{X_test.shape[0]}")

# Train a simple model


print("[ ] Training a Random Forest model...")
model = RandomForestClassifier()
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f"[✓] Model trained! Test accuracy: {accuracy:.2f}")

print("\n🎉 Your machine learning environment is fully operational! 🎉")

3. Run the script:


o Right-click in the editor and select "Run Python File in Terminal".

o Or, with your ml-bootcamp env activated in a terminal, run python


test_environment.py.

If you see a success message with an accuracy score at the end,


congratulations! Your professional ML workshop is officially open for
business.

5. Best Practices & Pro-Tips

 One Environment per Project: Always create a new Conda environment


for each major project to avoid conflicts.

 Export Your Environment: You can share your exact setup with others by
exporting it to a file.
bash
# Activate the environment you want to export
conda activate ml-bootcamp
# Export to a YAML file
conda env export > environment.yml

A collaborator can then recreate it with:


bash

conda env create -f environment.yml

You might also like