19674254 Python Module 1
19674254 Python Module 1
* Since its data types are more general, Python is applicable to a much
larger problem domain
Reasons are:
def bigger_than_five(x):
if x > 5:
print("X is bigger than five")
else:
print("x is 5 or smaller")
Because indentation is required, the Python language does not need curly
braces to group code blocks like Java, C, and C#
* Many languages either require a manual compilation step before you can
run your program or can be run directly by the interpreter. Python is
actually somewhere in between these two worlds.
=> You can write your code in a text editor and execute it directly. No
additional steps like compilation and linking are necessary.
This code is not specific to a system architecture (like Intel vs ARM), but
it is faster to read and parse than plain text files. Therefore Python is
platform-independent.
Date : 17/02/2023, Friday
=> when called with a file name argument or with a file as standard
input, it reads and executes a script from that file.
=>The user doesn't have to use the complicated basic functions of the OS
but is capable of using the interactive shell which is relatively simple and
easy to understand.
The interpreter prints a welcome message stating its version number and a
copyright notice before printing the first prompt.
Once the Python interpreter is started, you can issue any command at the
command prompt
* To end the interactive session, You can either use exit() or Ctrl-D (i.e.
EOF) to exit.
2.Python IDLE - Integrated DeveLopment Environment
* To quit the Python IDLE, you can either select the window’s close box or
press the Control + D key combination.
Editing, Saving, and Running a Script
1. Select the option New Window from the File menu of the shell
window(IDLE)
OR
$ gedit/vim/vi filename.py
4. To run this file of code as a Python script, select Run Module from the
Run menu or press the F5 key. (IDLE)
OR
$ python filename.py
IPython Notebook
ref: https://ipython.org/ipython-doc/dev/notebook/notebook.html
1. Syntax: print(<expression>)
Semantics: Python first evaluates the expression and then displays its
value.
2. The syntax for a print statement with two or more expressions looks like
the following:
Syntax:
print(<expression>,..., <expression>)
Semantics:
Evaluates the expressions and displays them, separated by one
space, in the console window.
* The programmer can also ask the user for input
This function causes the program to stop and wait for the user to enter a
value from the keyboard. When the user presses the return or enter key, the
function accepts the input value and makes it available to the program.
* The input function always builds a string from the user’s keystrokes and
returns it to the program.
After inputting strings that represent numbers, the programmer must
convert them from strings to the appropriate numeric types.
Detecting and Correcting Syntax Errors
* The term syntax refers to the rules for forming sentences in a language.
Here, in this error message, Python explains that this line of code is
unexpectedly indented. There is an extra space before the word print.
- It rejects any sentence that does not adhere to the grammar rules, or
syntax, of the language.
3. This byte code is next sent to another software component, called the
Python virtual machine (PVM), where it is executed. If another error
occurs during this step, execution also halts with an error message.
Problems
1. Write a Python program that prints (displays) your name, address, and
telephone number.
2. Write and test a program that accepts the user’s name (as text) and age
(as a number) as input. The program should output a sentence containing
the user’s name and age.
3. Design => Programmers determine how the program will do its task
=> This means that analysis and design may produce a rough draft,
skeletal version, or prototype of a system for coding, and then back up to
earlier phases to fill in more details after some testing.
1. Customer Request
The customer requests for a program that computes a person’s income tax
2. Requirement Analysis
In this case, the user inputs are gross income and number of dependents.
* Here the programmer and customer may decide on the user interface of
the developing application to get a better understanding.
3. Design
Design describes how the program is going to do the task. This usually
involves writing an algorithm in ordinary English / pseudocode.
4. Implementation (Coding)
* A single run without syntax errors and with correct outputs provides just
a slight indication of a program’s correctness. Only thorough testing can
build confidence that a program is working correctly.
* Testing = > The programmer just loads the program repeatedly into the
shell and enters different sets of inputs. Some sets of inputs can reveal an
error. An error at this point, also called a logic error or a design error , is an
unexpected output.
* Test suite : Test suite is a smaller set of inputs, from which we can
conclude that the program will likely be correct for all inputs.
Basic Coding Skills
Data Types
The first two data types listed, int and float are called numeric data types,
because they represent numbers.
String Literals
* To output a paragraph of text that contains several lines, you could use a
separate print function call for each line.
OR
Escape Sequences
* We can join two or more strings to form a new string using the
concatenation operator + .
1. Keywords are reserved for other purposes and thus cannot be used for
variable names.
Eg: interestRate
5. Programmers use all uppercase letters for the names of variables that
contain values that the program never changes.
Eg: STANDARD_DEDUCTION
* The wise programmer selects names that inform the human reader about
the purpose of the data.
* Variables receive their initial values and can be reset to new values with
an assignment statement .
- When this happens to the variable name for the first time, it is called
defining or initializing the variable
- They help the programmer keeptrack of data that change over time
- They also allow the programmer to refer to a complex piece of
information with a simple name
* A comment is a piece of program text that the computer ignores but that
provides useful documentation to programmers.
* Docstring: The author of a program can include his or her name and a
brief statement about the program’s purpose at the beginning of the
program file.
This type of comment, called a docstring and is a multi-line string.
3. Precede major segments of code with brief comments that explain their
purpose. The case study program presented earlier in this chapter does this.
* Integers include 0, the positive whole numbers, and the negative whole
numbers
* The magnitude of a Python integer is vey large and is limited only by the
memory of your computer.
Floating-Point Numbers
Character Sets
* In Python, character literals look just like string literals and are of the
string type.
* Following Table shows the mapping of character values to the first 128
ASCII codes:
Problems
1. Let the variable x be "dog" and the variable y be "cat" . Write the values
returned by the following operations:
a. x + y
b. "the " + x + " chases the " + y
c. x * 4
3. Code a python program to get the upper case of input lower case letter.
4. Code a python program to get the lower case of input upper case letter.
Date: 22/2/23
Wednesday
Expressions
Eg: 5 + 3 * 2
Arithmetic Expressions
eg: –3 ** 2, 2 ** 3 ** 2
* Programmers usually insert a single space before and after each operator
to make the code easier for people to read.
Here, the less general type (int) is temporarily and automatically con-
verted to the more general type (float) before the operation is performed.
Thus, in the example expression, the value 9 is converted to 9.0 before
the multiplication.
* Input() function reads all inputs as strings and they must be converted to
appropriate numeric type, before using in arithmetic expressions.
* Note that the int function converts a float to an int by truncation, not by
rounding to the nearest whole number.
* Type conversion can be used to construct strings from numbers and
other strings.
To solve this,we use the str function to convert the value of profit to a
string and then concatenate this string to the $ symbol:
=> The interpreter checks data types of all operands before operators are
applied to those operands. If the type of an operand is not appropriate, the
interpreter halts execution with an error message.
Problems
1. An object’s momentum is its mass multiplied by its velocity. Write a
program that accepts an object’s mass (in kilograms) and velocity (in
meters per second) as inputs and then outputs its momentum.
Eg: round(6.7)
Eg: round()
- When called with just one argument, the round function exhibits its
default behavior , which is to return the nearest whole number with a
fractional part of 0.
=> A program that attempts to pass an argument of the wrong data type to
a function will usually generate an error.
For example, one cannot take the square root of a string, but only of a
number.
* When a function completes its task, the function may send a result back
to the part of the program that called that function in the first place.
Python modules
* To create a module just save the code you want in a file with the file
extension .py
def greeting(name):
print("Hello, " + name)
* You can use any Python source file as a module by executing an import
statement in some other Python source file.
import mymodule
mymodule.greeting("Jonathan")
When using a function from a module, use the syntax:
module_name.function_name
* There are several built-in modules in Python, which you can import
whenever you like.
>>> math.pi
3.1415926535897931
>>> math.sqrt(2)
1.4142135623730951
>>> help(math.cos)
Generally, the first technique of importing resources (that is, importing just
the module’s name) is preferred.
Problems
- those that perform the action until the program determines that it needs to
stop ( indefinite iteration )
Syntax:
Semantics:
*The first line of code in a loop is called the loop header. The colon (:)
ends the loop header.
The integer expression, in it denotes the number of iterations that the
loop performs. It counts from 0 to the value of the header’s integer
expression minus 1. On each pass through the loop, the header’s variable
is bound to the current value of this count.
*The loop body comprises the statements in the remaining lines of code,
below the header. These statements are executed in sequence on each pass
through the loop.
*The statements in the loop body must be indented and aligned in the
same column
Illustraion
1. WAP to implement python exponentiation operator .
Count-controlled loops
* Loops that count through a range of numbers are also called count-
controlled loops. The value of the count on each pass is often used in
computations.
Illustartion
Q. WAP to find the factorial of a number.
* To count from an explicit lower bound, the programmer can supply a
second integer expression in the loop header. When two arguments are
supplied to range, the count ranges from the first argument to the second
argument minus 1.
Q. WAP to sum all the numbers between a lower and upper limit.
Augmented Assignment
Semantics:
<variable> = <variable> <operator> <expression>
Off-by-One Error
* The error is that, the loop fails to perform the expected number of
iterations.
The programmer might intend the above loop to count from 1 through 4,
but it counts from 1 through 3.
* Note that this is not a syntax error, but rather a logic error. Logic
errors are not detected by the Python interpreter.
* you can use a third argument in the range() function, namely step
argument to specify the step value.
Problems
1. Write a loop that prints your name 100 times. Each output should begin
on a new line.
* The total number of data characters and additional spaces for a given
datum in a formatted string is called its field width.
%<field width>s
- When the field width is positive, the datum is right-justified; when the
field width is negative, you get left-justification.
- If the field width is less than or equal to the datum’s print length in
characters, no justification is added.
Syntax:
* The format information for a data value of type float has the form
%<field width>.<precision>f
27/02/2023
Monday
Synatx:
Semantics:
Problems:
2. Write a Python code to check whether a given year is a leap year or not
[An year is a leap year if it’s divisible by 4 but not divisible by 100 except
for those divisible by 400].
One-Way Selection Statements
* Syntax:
* Semantics:
Multi-Way if Statements
* Syntax:
- The multi-way if statement considers each condition until one evaluates
to True or they all evaluate to False .
- If no condition evaluates to True , then the action after the trailing else is
performed.
* Semantics:
Problems
* Syntax:
while <condition>:
<sequence of statements>
- At least one statement in the body of the loop must update a variable that
affects the value of the condition. Otherwise, the loop will continue
forever, an error known as an infinite loop.
* Semantics:
* Illustartion
* There are two input statements, one just before the loop header and one
at the bottom of the loop body.
-The first input statement initializes a variable to a value that the loop
condition can test. This variable is also called the loop control variable
- The second input statement obtains the other input values, including one
that will terminate the loop.
- This loop’s structure can be simplified if we receive the first input inside
the loop and break out of the loop if a test shows that the continuation
condition is false.
- This implies postponing the actual test until the middle of the loop.
- Python includes a break statement that will allow us to make this change
in the program.
Illustarion:
* In cases where the body of the loop must execute at least once, this
technique simplifies the code and actually makes the program’s logic
clearer.
Random Numbers