Python Comments
Comments can be used to make the code more readable.
Single-Line Comments
#
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your comment
inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code
Debugging
Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the
process of tracking them down is called debugging.
high-level language:
A programming language like Python that is designed to be easy for humans to read and write.
low-level language:
A programming language that is designed to be easy for a computer to run; also called “machine
language” or “assembly language”.
CHAPTER 2
Variables, Expressions and Statements
A variable is a name that refers to a value.
This assigns the approximate value of π to the variable pi.
Variable Naming Rules
❌ Invalid Variable Names:
76trombones → Cannot start with a number.
more@ → Contains an illegal character @
✅ Valid Variable Names:
my_variable
total_sum
_private_var
Python Keywords
Python reserves certain words for its syntax. These cannot be used as variable names.
Python 3 has these keywords:
The interpreter uses keywords to recognize the structure of the program, and they cannot be used as
variable names
Expressions and Statements
Expression: A piece of code that produces a value.
Statement: An instruction that Python executes
CHAPTER 3
ORDER OF OPERATIONS
Python follows the PEMDAS rule for evaluating expressions
Parentheses > Exponents > Multiplication & Division > Addition & Subtraction.
Operators with the same precedence are evaluated from left to right (except exponentiation).
In general, mathematical operations can’t be performed on strings
Invalid String Operations 🚫
Python does not allow direct mathematical operations on strings, even if they contain numbers. The
following will result in errors:
Valid String Operations ✅
There are two exceptions, + and *.
String Concatenation (+ Operator)
The + operator performs string concatenation, which means it joins the strings by linking them end-to-
end. For example:
throatwarbler
String Repetition (* Operator)
The * operator repeats the string multiple times.
One operand must be a string, and the other must be an integer.
DEBUGGING
Three kinds of errors can occur in a program:
Syntax Error
Runtime Error
Semantic Error
Syntax Error
o “Syntax” refers to the structure of a program
o example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax
error.
o Unmatched Parentheses:
o Missing Colon in Conditional Statement:
o If there is a syntax error anywhere in your program, Python displays an error message and
quits, and you will not be able to run the program
Runtime Error
The second type of error is a runtime error, so called because the error does not appear until
after the program has started running.
Characteristics:
Detected during program execution, causing the program to terminate unexpectedly if
unhandled.
Also known as exceptions, indicating that something exceptional has occurred.
Examples:
Division by Zero:
Accessing an Undefined Variable:
Resolution: Implement error handling using constructs like try and except blocks to manage
exceptions gracefully.
Semantic Error
Errors that occur when the program runs without crashing but produces incorrect results due to flaws in
the program's logic.
Characteristics:
Program executes without throwing errors but yields unintended outcomes.
Often arise from incorrect assumptions or misunderstandings of the problem requirements.
Incorrect Loop Condition Leading to Infinite Loop:
Using the Wrong Operator:
FUNCTIONS
What Is a Function?
A function is a reusable block of code designed to perform a specific task.
Argument: The value(s) passed inside the parentheses when the function is called.
Returns a result: The output or return value after the function processes the input.
Here, type function
42 argument
Built-in Conversion Functions
Python provides built-in functions to convert values from one type to another
A. int() Function
Purpose: Converts a given value to an integer.
Error Handling
If the argument cannot be converted to an integer, Python raises a ValueError
B. float() Function
Purpose: Converts a given value to a floating-point number.
C. str() Function
Converts a given value to a string.
Math Functions
A module in Python is a file that contains a collection of related functions, variables, and classes.
Importing the Math Module
This statement creates a module object named math
The math module is built into Python and provides many mathematical functions.
Using Dot Notation
To access any function or variable within the module, you use dot notation
To call the square root function
Functions and Variables in the Math Module
Common Functions
math.sqrt(x) – Returns the square root of x.
math.floor(x) – Returns the largest integer less than or equal to x.
math.ceil(x) – Returns the smallest integer greater than or equal to x.
math.pow(x, y) – Returns x raised to the power of y.
Key Variables:
math.pi – The constant π (pi), approximately 3.14159.
math.e – The constant e (Euler's number), approximately 2.71828.
the left side of an assignment statement has to be a variable name. Any other expression on the left side
is a syntax error (we will see exceptions to this rule later).
Adding New Functions
In Python a function is defined using the def keyword:
The rules for function names are the same as for variable names
Calling a Function
To call a function, use the function name followed by parenthesis:
When you call a function:
Python jumps into the function’s code block.
It executes each statement in the block one by one.
If there is a return statement, the function will stop executing further and send back a result.
Inside the function, the arguments are assigned to variables called parameters.
Explanation:
In the second example, the function add takes two numbers, adds them, and then returns the result.
That returned value is stored in the variable result.
Why Functions?
It may not be clear why it is worth the trouble to divide a program into functions. There are several
reasons:
• Creating a new function gives you an opportunity to name a group of statements, which makes your
program easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you
only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then assemble
them into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug one, you can
reuse it
Script Mode
save code in a file called a script and then run the interpreter in script mode to execute the script. By
convention, Python scripts have names that end with .py.
TER 3
Functions