0% found this document useful (0 votes)
15 views11 pages

Programming Fundamental

Uploaded by

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

Programming Fundamental

Uploaded by

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

PROGRAMMING FUNDAMENTALS

3.1 What is a Computer Program?


A computer program is a set of instructions that tells the computer what to do, step by step, to solve a problem. A computer
program gives the computer instructions to complete a task.
How does it work?
Input: The computer waits for some information or instructions (like typing a number or pressing a button).
Processing: The computer follows the instructions, step by step.
Output: It gives the result, like showing an answer on the screen.
Small programs may use one set of instructions, called an algorithm, while big programs can use multiple algorithms.
The program and the data it works on are both stored in the computer’s main memory to make the process faster.

Types of Computer Programs:


• Interactive Programs: These programs require input from the user or another program, like a web browser.
• Batch Programs: These programs work by running a list of commands one by one, like when a printer handles
multiple print jobs in a queue.
Computer programs are written using programming languages, which have specific rules and keywords.
High level Language: We use high-level programming languages to write computer programs because they are easier for
humans to read, write, and understand. High-level languages save us time, help us spot mistakes easily, and make our
programs run on different computers without much trouble.
Compiler: A compiler translates the whole code from a high-level
programming language into machine code before the program runs.
Programs written in languages like C++ and Java use a compiler.
Interpreter: An interpreter translates code written in a high-level
programming language into machine code line-by-line as the code
runs. Programs written in Python and JavaScript use an interpreter.
3.2 What is Python?
Python is a popular and easy-to-learn high-level programming language. It was created in 1992 and is used for building
software, data analysis, machine learning, and even web development.
Why Python is Popular:
Easy to Learn: Python’s writing rules (syntax) are similar to English, making it simple to read and understand.
Open Source: Python is free to use, and there’s plenty of help available online from other developers.
Wide Use: Python is used in various fields, from building websites to analyzing big data.
Python is also used to build games and create animations. Because it’s easy to write and understand, many beginners choose
Python as their first programming language.

3.3 Python IDEs (Integrated Development Environments)


Writing and executing Python programs, needs a program called an IDE (Integrated Development Environment). One
popular IDE is called IDLE, which can be downloaded from the official Python website.
Another option is using online IDEs like Replit, where installing Python is not required on computer system. Code can be
directly written and executed in the browser, and to see the output instantly, a button called run is pressed.
For example, in Replit, we can assign values to variables, write code to print those values, and see the result immediately
on the screen.

3.4 Turtle Graphics


Turtle Graphics is a fun way to learn Python by creating simple drawings. With just a few commands, we can create all
kinds of shapes. It comes pre-installed with Python, so we don’t need to install anything extra. By writing commands, we
can control a "pen" (called a turtle) to draw shapes on the screen.
Turtle Graphics is especially helpful for beginners because it makes learning fun by
combining programming with drawing.
For example, consider the following code:
1. import turtle
2. turtle.Screen()
3. turtle.screensize(200, 150, "coral")
4. turtle.dot(10, "Blue")
5. turtle.circle(50)
6. turtle.pencolor("Blue")
7. turtle.circle(-50)
What Does This Code Do?
1. import turtle: This line tells the computer to load the Turtle Graphics tool so that we can use it to draw shapes and
lines.
2. turtle.Screen(): This command opens a canvas where all the shapes and lines will appear (like a blank piece of paper).
3. turtle.screensize(200, 150, "coral"): This command sets the width, height and the background color of the canvas.
4. turtle.dot(10, "Blue"): This draws a dot that is 10 pixels wide and colored blue.
Note: The dot is always placed in the middle of the screen at the start.
5. turtle.circle(50): This draws a circle with a radius of 50 pixels in counterclockwise direction.
6. turtle.pencolor("Blue"): This changes the pen color to blue. From now on, any shape or line drawn will be in blue.
7. turtle.circle(-50): This draws another circle of same radius, but in the clockwise direction because of the negative
sign (-). Since we changed the pen color to blue earlier, this second circle will be drawn in blue.
Drawing a Car like Shape:
1. Drawing the Body of the car:
o turtle.pendown(): This command tells the turtle to put the "pen" down so it can start drawing lines on the screen
o turtle.forward(100): The turtle moves forward by 100 pixels, drawing a horizontal line.
o turtle.left(90): The turtle turns left by 90 degrees, ready to draw a vertical line.
o turtle.forward(25): The turtle moves forward 25 pixels, drawing a short vertical line.
o turtle.left(90): The turtle turns left again by 90 degrees.
o turtle.forward(25): It moves forward 25 pixels, drawing another horizontal line.
o turtle.right(90): The turtle turns right by 90 degrees.
o turtle.forward(25): It moves forward 25 pixels, drawing another vertical line.
o turtle.left(90): The turtle turns left by 90 degrees again.
o turtle.forward(50): It moves forward 50 pixels, continuing the shape.
o turtle.left(90): The turtle turns left again.
o turtle.forward(25): It draws another 25-pixel line.
o turtle.right(90): Turns right by 90 degrees again.
o turtle.forward(25): Moves forward 25 pixels to complete the current side of the shape.
o turtle.left(90): Turns left again.
o turtle.forward(25): Finally, it moves forward 25 pixels to complete the bottom part of the shape.

2. Moving the Turtle (Without Drawing)


o turtle.penup(): Lifts the pen up so the turtle can move without drawing a line.
o turtle.left(90), turtle.forward(25): The turtle turns left by 90 degrees and moves forward 25 pixels.
o turtle.pendown(): The turtle puts the pen down again, ready to draw.

3. Drawing the Wheels:


First Circle
o turtle.pencolor("Blue"): The turtle’s pen color is now changed to blue, meaning any future drawing will be in blue.
o turtle.circle(-10): This draws a small circle with a radius of 10 pixels.
o turtle.penup(): Lifts the pen again so the turtle can move without drawing.
o turtle.right(90), turtle.forward(10): The turtle moves right and forward by 10 pixels.
o turtle.dot(5, "Blue"): It draws a small blue dot with a diameter of 5 pixels inside the circle

Second Circle
o turtle.back(10)
o turtle.left(90)
o turtle.forward(50): The turtle moves back and adjusts its position to draw the second circle.
o turtle.circle(-10): Draws another circle (similar to the first one).
o turtle.penup()
o turtle.right(90)
o turtle.forward(10): The turtle moves to position itself for another dot.
o turtle.dot(5, "Blue"): Draws another small blue dot inside the second circle.

3.5 Python Libraries


A library in Python is like a collection of tools or pre-written code that helps we do specific tasks easily. Instead of writing
long instructions, we can use a library to do the work for we with just a few simple commands.
For example:
The Turtle library helps we draw shapes.
The datetime library helps we work with dates and times, like finding out
today’s date or calculating someone’s age.
Instead of manually installing and managing libraries, we can use a package
manager like Pip. It simplifies the process of installing libraries and ensures
all necessary components are included. To install a library, we just type a
command like this: Pip install datetime
Examples:
1. Displaying the Current Date and Time: Using the datetime library, we can
display the current date and time easily.
2. Extracting Specific Information: We can extract specific information, like
the year or day of the week, using the {string format time} strftime()
function. For example, using '%A' will give we the day name, while '%B'
will return the month name.

3.6 Python Variables


Variables are containers for storing data values that can be used later in the program. A variable is created the moment first
value is assigned to it.
For example, if we solve an equation multiple times, we can save the result in a variable instead of recalculating it.
Naming Variables: Variable names:
• Can include letters and numbers but cannot start with a number.
• Are case-sensitive. (e.g., Num and num are different).
• Should not contain spaces; use underscores (e.g., temp_var).
Semantics
It's important to write code in the correct order because if the sequence changes, it can lead to errors known as logical bugs.
These bugs can be hard to spot, so using a technique called dry-run (running through the code on paper) can help we find
problems.
Example: Swapping Values
# Initial values
1. x=5
2. y = 10
# Swapping using a temporary variable
3. temp = x
4. x=y
5. y = temp
# Check the swapped values using print
6. print("x =", x) # Output: x = 10
7. print("y =", y) # Output: y = 5
To swap two variables x and y using a temporary variable temp, the correct order of operations is crucial. Changing the
order may lead to unexpected results.

3.7 Python Input/Output (I/O)


The Python Shell is interactive and allows we to enter commands and see results right away. The print() function displays
output based on what’s inside the parentheses. Any extra spaces we add will show up in the output.
We can get input from the user using the input() function, which stores the data in a variable for later use. For example:
country = input("Enter your country: ")
print(country)
The input() function treats everything as a string. If
we want to use a number, we need to convert it using
the eval() function. This function evaluates the expression and can convert strings to integers.
Example: Using eval()
When adding two numbers entered as strings, we will concatenate them instead of adding. Using eval() will treat the input
as numbers.

3.8 Operators in Python


3.8.1 Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. Here are the basic arithmetic operators in Python:
1. Addition (+): Adds two numbers. Example: 5 + 2 results in 7.
2. Subtraction (-): Subtracts the second number from the first. Example: 5 - 2 results in 3.
3. Multiplication (*): Multiplies two numbers. Example: 5 * 2 results in 10.
4. Division (/): Divides the first number by the second and will always return a float. Example: 5 / 2 results in 2.5.
5. Floor Division (//): Divides and rounds down to the nearest whole number. Example: 5 // 2 results in 2.
6. Modulus (%): Returns the remainder of the division. Example: 5 % 2 results in 1.
7. Exponentiation (**): Raises the first number to the power of the second. Example: 5 ** 2 results in 25.
Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is =. Here’s how it works:
Assignment (=): Assigns the value on the right to the variable on the left.
Example: x = 5 means x now holds the value 5.
The assignment operator can be used in Python with arithmetic operators, as well. e.g. i = i + 1 can also be written as i +=1,
i = i - 2 as i -=2, i = i*3 as i*=3, etc. These operators are called compound operators.
3.8.2 Bitwise Operators
Bitwise operators in Python are used to manipulate individual bits of binary numbers.
Operator Name Description Example
Compares each bit of two numbers and sets the result 5 & 3 --> 0101 & 0011 = 0001 (binary)
& AND = 1 (decimal)
to 1 only if both bits are 1.
Compares each bit of two numbers and sets the result 5 | 3 --> 0101 | 0011 = 0111 (binary) =
| OR 7 (decimal)
to 1 if either bit is 1. If both bits are 0, the result is 0.
Compares each bit of two numbers and sets the result 5 ^ 3 --> 0101 ^ 0011 = 0110 (binary)
^ XOR = 6 (decimal)
to 1 if the bits are different (one is 1, the other is 0).
Inverts all the bits of the number, meaning it flips each ~5 --> ~0101 = 1010 (binary)
~ NOT = -6 (decimal)
bit (1 becomes 0, and 0 becomes 1).
Left Zeros are pushed in from the right, and bits on the left 5 << 1 --> 0101 << 1 = 1010 (binary)
<< = 10 (decimal)
shift fall off.
Right Shift right by pushing copies of the leftmost bit in from 5 >> 1 --> 0101 >> 1 = 0010 (binary)
>> = 2 (decimal)
shift the left, and let the rightmost bits fall off

3.8.3 Membership Operators


Membership operators in python checks if a value is in an object:
• in: Returns true if the value exists. • not in: Returns true if the value does not exist.
3.8.4 Comparison Operators Operator Description Syntax
== Equal to: True if both operands are equal a == b
Comparison operators help compare != Not equal to: True if operands are not equal a != b
values. For instance, in a login program, > Greater than: True if the left operand is greater than a>b
we would compare the entered password the right
using “is equal (= =)” operator with the < Less than: True if the left operand is less than the a<b
saved password. If they match, the user is right
logged in; if not, the user is prompted to >= Greater than or equal to: True if left operand is a >= b
try again. greater than or equal to the right
3.8.5 Logical Operators <= Less than or equal to: True if left operand is less than a <= b
or equal to the right
These operators combine multiple
conditions:
• and: True only if all conditions are true.
• or: True if at least one condition is true.
• not: Negates the outcome.
Using logical operators helps manage complex conditions in your
code.
3.8.6 Conditional Statements
Conditional statements in Python allow us to make
decisions in our code based on certain conditions. In
simple terms, they help we choose what part of the code
to run depending on whether a condition is true or false.
To check if a number is even or odd, we can use an if
statement.
For more complex conditions, we can use if, elif, else
statements. This allows us to check multiple conditions, like treating zero as a special case.
IF-ELSE
The if-else statement allows us to make decisions in our program based
on conditions. For example, if we want to check if a number is even, we
can use an if statement to evaluate a condition and the else statement to
handle any other possible outcomes.
Example:
This code checks whether the number is even or odd. If the number is divisible by 2 (i.e., the remainder when divided by 2
is 0), it prints "even"; otherwise, it prints "odd."
IF-ELIF-ELSE Statements
Sometimes, there are more than two possible outcomes. For
example, some people treat zero as neither even nor odd, which
means we now have three possibilities. To handle multiple
conditions, we use elif (short for else-if) along with the if-else
statement.
Figure 3.20 represents the code for multiple conditions.
3.9 Iteration and Loop
Computer programs often require executing the same task multiple times, which is where iteration comes into play. Instead
of writing repetitive code for each execution, we can utilize loops to simplify our code.
For Loop
The for loop is one of the most commonly used loops in Python. It
allows us to execute a block of code a specific number of times by
defining a starting point, a terminating condition, and optionally a
step size.
Syntax: for variable_name in range (initial_value, last_value, increment/decrement)
Example: This code snippet uses the print statement five times.
The loop variable i starts at 0 and increments by 1 each iteration.
We can customize the starting point, terminating condition, and step
size of for loop. For instance:
In Fig 3.23 loop starts from 10, stops before 20, and increments by 2.
The terminating condition is exclusive, meaning it won’t include the
terminating value.

3.10 Lists
Imagine a scenario where a teacher has to enter the test scores of 25 students into a computer. If we used variables for each
student, we would need to create 25 variables to store their marks. As the number of students increases, this becomes
impractical because you would have to remember and manage a lot of variable names.
As we scale up our programs, managing multiple variables can become difficult. Python provides a more efficient
way to handle such scenarios by using a list. A list is a data structure that can store multiple values under a single name and
can easily be changed (mutable).
Defining a List
A list in Python is defined by assigning a name and using square brackets [ ] to enclose the values. For example:
odd_nums= [1, 3, 5, 7, 9] Here, odd_nums is a list containing five odd numbers.
Printing a List
To print a list, simply pass its name to the print() function: print(odd_nums) This would display the entire list.
Accessing elements of a List
To access a specific value in the list, use its index. Python indexing starts from 0, so to print the third value (which is 5), we
write: print(odd_nums[2]) # Output: 5
Useful Functions for Lists
Python provides several built-in functions to work with lists:
Function Description Example
len() Returns the number of elements in the list. len(odd_nums) # Output: 5
min() Returns the smallest element in the list. min(odd_nums) # Output: 1
max() Returns the largest element in the list. max(odd_nums) # Output: 9
sum() Returns the sum of all elements in the list. sum(odd_nums) # Output: 25
insert() Inserts an element at specific index odd_nums.insert(3, 6) # Output: [1,3,5,6,7,9]
index() Returns the position of a number in the list. In case odd_nums.index(4) # Output: 7
of multiple occurrences, the first match is returned.
append() Appends (Add) an element to the end of the list. odd_nums.append(11) #Output[1,3,5,6,7,9,11]
Generating Random Numbers in a List
Python provides a module (library) called random that has built-in functions to generate random numbers. One of these
functions is randint(), which generates a random integer between two specified values. To use this function, we first need
to import the random module by using the import keyword at the beginning of our program.
import random
rnd_nums = []
for _ in range(10):
rnd_nums.append(random.randint(1, 99))
print(rnd_nums)
Each time this code runs, it generates 10 new random numbers between 1 and 99.
Searching an Element in a List
In Python, you can easily search for an element in a list using several methods. Here are some simple and effective ways:

• Using the in Keyword (Membership Operator): The easiest way to check if an element exists in a list is by using
the in keyword. It checks if the element is present in the list and returns True if found, otherwise False.
Example:
my_list = [10, 20, 30, 40, 50]
num = 30
if num in my_list: L = [10, 20, 30, 40, 50]
print(your number is in the list") print(30 in L)
else:
print(your number is in not the list")

• Using a for Loop: You can manually search for an element in a list by iterating through the list using a for-loop.
Example:
my_list = [10, 20, 30, 40, 50]
element = 30
for item in my_list:
if item == element:
print(element is in the list")
break
else:
print(element is not in the list")

3.11 Functions in Python


As our programs get longer and more complex, it can become difficult to manage all the logic and keep track of different
parts of the code, especially if multiple algorithms are involved. Functions in Python help solve this problem by breaking
the program into smaller, manageable pieces. Each piece, or function, performs a specific task and can be reused whenever
needed.
What is a Function?
A function is a block of code designed to perform a particular task. Function can be called from the main program whenever
that specific task needs to be done. This makes the code more organized and easier to understand.
Defining a Function
In Python, functions are defined using the def keyword, followed by the function's name and parentheses (). A function can
return data as a result. Example: def my_name( ):
print("This line is printed when my_name() is called.")
Calling Functions
We can call a function by using its name followed by parentheses: my_name ( )
Why Use Functions? Benefits of Using Functions
1. Code Reusability: Define a task once and use it repeatedly.
2. Organization: Break down large programs into smaller, manageable sections.
3. Clarity: Makes code easier to read and understand by isolating specific tasks.
4. Flexibility: Functions can accept different inputs (arguments) to perform the same task in various ways.
5. Maintainability: Easier to update and fix bugs in a function rather than in scattered code.
Functions make our code more efficient and organized. Instead of repeating the same code, you define it once in a function
and use it wherever needed by calling the function.
For example, if you need to draw lines multiple times in a program, you can create a draw_line() function and call it
whenever necessary. This reduces redundancy and keeps your code cleaner.
Functions make your code more readable and easier to maintain.
Global and Local Variables in Python
Global variables are variables which are defined inside the main program and are accessible throughout the program and
inside every function.
Local variables are variables which are initialized inside a function and belong only to that particular function. It cannot
be accessed anywhere outside the function.
Function Arguments and Parameters:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
Arguments and parameters allow us to pass data into the functions. This makes functions more versatile.
Example: def draw_line(length): Function Parameter
print("-" * length) Function Argument
draw_line(10) # Draws a line of length 10.
Returning Values
Functions can also return a result instead of just performing an action. This is useful when you need to use the result of a
function in other parts of your program. Use the return keyword to send a value back from a function.
def sum_list(my_list): # defining a function with a parameter
return sum(my_list) # returning the sum of a list
result = sum_list([1, 2, 3]) # the function is called with an argument and stored in result variable
print(result) # Prints 6

3.12 Debugging in Python


Debugging refers to the process of finding and fixing errors or bugs in your code. A bug is an unexpected error that can
cause the program to behave incorrectly. Some bugs are simple to locate, but in complex programs it may require tools and
techniques like debugging.
Manual Debugging (Dry Running Code)
When a bug is relatively simple, you can manually trace the program’s logic by inspecting the code line by line. However,
for larger programs, manually checking each part of the code becomes tedious and difficult. This is where debugging tools
come into play.
Debugging in Python IDLE
Python IDLE provides a built-in debugger that allows you to step
through your code and examine the state of your program at each
step. To activate debugging in IDLE:
1. Go to the Debug menu.
2. Select Debugger.
3. You'll see a "DEBUG ON" message in the shell.
Once the debugger is on, running your program opens a Debug
Control window. This window helps you observe how the program
progresses, showing the variables and their values after each step.
Debugger Buttons
• Go: Continues execution until the next breakpoint.
• Step: Executes the code line-by-line. Every time you press it, the next line of code will execute.
• Over: Skips over function calls and continues execution without stepping into the function. This way, the function
is fully executed and value is returned but the debugger skips it.
• Out: Exits the current function and resumes execution at the next line after the function call.
You can also use checkboxes in the debugger to monitor Global and Local variables, or see the Stack of functions being
executed.
Breakpoints
A breakpoint is a place in the code, where the execution of the program stops to allow us to examine a particular instruction.
This allows us to inspect the state of our program at critical points. To set a breakpoint in Python IDLE:
1. Right-click on a line of code and choose Set Breakpoint.
2. The line will be highlighted in yellow to indicate it's a breakpoint.
When the program runs, it will stop at the breakpoint, allowing you to examine variable values and determine if the bug
exists there. To remove a breakpoint, right-click the line again and select Clear Breakpoint.
Python Debugger (pdb)
Python also includes a command-line debugger called pdb. To use it, you can run your script from the command prompt
with using this command: python -m pdb program_name.py
This will run the program in the debugger, allowing you to step through the code and set breakpoints using commands like:
• break line_number: Sets a breakpoint at the specified line.
• step: Steps through the code line by line.
• next: Executes the current line and moves to the next line.
• continue: Runs the program until it hits a breakpoint.
Using pdb allows for debugging in environments without a graphical interface, making it useful for remote servers or
command-line tools.
pdb in IDLE Shell: Debugging can also be done in IDLE shell by importing the pdb module at the beginning of the code.
To set a breakpoint in the code (where you want the execution to pause), use pdb.set_trace() function.
When the program hits this line, it will stop, allowing us to inspect the state of the program. We can then execute the code
line-by-line to see how it behaves.
import pdb
def add(a, b):
result = a + b
return result
pdb.set_trace() # Set a breakpoint here
x=5
y=3
sum_result = add(x, y)
print(sum_result)
Debugging Commands in IDLE shell:
Once the debugger is active, several commands can be used to control the execution:

• step (or s): Move to the next line of code and stop.
• continue (or c): Resume execution until the next breakpoint.
• next (or n): Execute the current line and stop at the next line in the same function.
• list (or l): Display the current line of code and its surroundings.
• print (or p): Inspect the value of a variable or expression.
• quit (or q): Exit the debugger and stop the program.
Print Statements for Debugging
Another simple method to debug is by using print statements. By placing print statements at key points in your program,
you can display variable values and see how they change throughout execution. This can help trace bugs without needing
to use a debugger.
Using assert for Debugging
The assert statement is a built-in Python tool that checks if a condition is true.
If the condition is false, Python raises an AssertionError. This is useful for
catching bugs based on logical errors or incorrect assumptions in the code.
Example:
assert x > 0, "x must be positive"
If x is not positive, the program will stop and display an error message, helping
you catch bugs early.

You might also like