DEV Community

Cover image for A PEEK INTO PYTHON
ombatii
ombatii

Posted on

A PEEK INTO PYTHON

BASICS

Python is a high level language that enables us to instruct the computer on what tasks it should do, for instance you could give a computer some data and instruct it to do some complex calculations.

There are two types of computer languages; High-level languages are designed to be more easily readable and understandable by humans such as python language while low level language are difficult to read: it is represented all in zeros and ones. In reference to python, a compiler translates the entire Python code into machine code before running while an interpreter translates and does sequential execution.

When writing python codes there are "grammar" rules of python you should follow, failure to which you will get errors. The following are some of reserved words in the language that you should be careful when coding;
and del global not with
as elif if or yield
assert else import pass
break except in raise
class finally is return
continue for lambda try
def from nonlocal while
If do not follow the "grammar" rules of python here are some of errors to will get;

  1. Syntax errors: means that you have violated the “grammar” rules of Python.
  2. Logic errors: means your program has good syntax but there is a mistake in the order of the statements or perhaps a mistake in how the statements relate to one another.
  3. Semantic errors: When your description of the actions to take is syntactically flawless and in the proper order, but the program has a mistake, it is a semantic error.

Let's consider this case; Create a program that displays your name and complete mailing address formatted in the manner that you would usually see it on the outside of an envelope. Your program does not need to read any input from the user.

# Syntax error
print('Brian Ogeto')print('P.O BOX 134-567')print('Bomet-Kenya')

# Logic error
print('P.O BOX 134-567')
print('Brian Ogeto') # Logic error
print('Bomet-Kenya')

# Semantic error
print('Brian Ogeto')
print('P.O BOX 134-567')
print('Bomit-Kenya')  # Semantic error
Enter fullscreen mode Exit fullscreen mode

When encountered with this kind of error, take this steps to correct it(debugging):

  1. reading: Review your code, read it aloud to yourself, and make sure it expresses what you intended.

2.running: Experiment by altering and launching several iterations.

3.ruminating: Spend some time reflecting!? What kind of error might be causing the issue you're experiencing?

4.Retreating: At some point, it's best to take a step back, undoing any changes you've made, and return to a program that you understand and works. After that, you can begin to reconstruct.

After taking these steps,this the correct code;

print('Brian Ogeto')
print('P.O BOX 134-567')
print('Bomet-Kenya')
Enter fullscreen mode Exit fullscreen mode

The building blocks of python programs

  1. input: raw data feed into the program such as a dataset.
  2. output: this the useful information of the input you fed into the program.
  3. sequential execution: Perform statements one after another in the order they are encountered in the script.
  4. conditional execution: Check for certain conditions and then execute or skip a sequence of statements.
  5. repeated execution: Perform some set of statements repeatedly, usually with some variation.
  6. reuse Write a set of instructions once and give them a name and then reuse those instructions as needed throughout your program. Like by reusing a function you once defined it.

Variables, expressions, and statements

A variable is a name that refers to a value which could of different data types such as numeric. You could use type() function to know the data type. An assignment statement creates new variables and gives them values and we use this mathematical symbol "=" in the process.

# Assigning variable "x" the "Brian" value
x = str("Brian")
type(x)
Enter fullscreen mode Exit fullscreen mode

Be careful when assigning variables name by considering the key words in python I have discussed above, avoid them.

A statement is a unit of code that the Python interpreter can execute.
Special symbols known as operators are used to express calculations such as addition and multiplication. Operands are the values to which the operator is applied.
An expression is a combination of values, variables, and operators.

Order of operations

The acronym PEMDAS(Parentheses, Exponentiation, Multiplication and Division) will be useful way to remember
the rules when doing an task with multiple operations.

Asking the user for inputt

Use the function input() will enable you get input from the user.

Consider this task;
Create a program that reads the length and width of a farmer’s field from the user in feet. Display the area of the field in acres.

# Assigning variable "ACRE" with a value
##  AREA OF THE FIELD IN ACRES 
ACRE = 43560

# getting the size of length and width from user
length = float(input("Enter  the length of the field : ")) 
width = float(input(" Enter the width of the field : "))

# expression
area = (length * width )/ ACRE 

# statement
print("The area of the field is" , area ,"acres")
Enter fullscreen mode Exit fullscreen mode

Conditional execution

Boolean expressions

A Boolean expression is an expression that is either true or false. The operator "==" is used to compare two operands and produces True if they are equal and False otherwise:

x = 0.9
y = 0.8
x == y #False
Enter fullscreen mode Exit fullscreen mode

Other comparison operators are

x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y
Enter fullscreen mode Exit fullscreen mode

Logical operators

There are three logical operators: and, or, and not

# and
x > y and x < 1 # True
# or 
x > y and x is y # True
# not
x is not y   # True
Enter fullscreen mode Exit fullscreen mode

Conditional execution

if statement

The boolean expression after the if statement is called the condition. We end the if statement with a colon character (:) and the line(s) after the if statement are indented. If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped.

if x > 0 :
    print('x is positive integer')
Enter fullscreen mode Exit fullscreen mode

Use pass statement when the if statement does not have a body.

if x > 0 :
    pass
Enter fullscreen mode Exit fullscreen mode

Alternative execution

Used when there are two possibilities and the condition determines which one gets executed.

z = -8
if z < 0 :
     print('z is a negative number')
else :
     print('z is a positive number')
Enter fullscreen mode Exit fullscreen mode

Chained conditionals

Used when there are more than two possibilities.

if x < z:
   print('x is less than z')
elif x > z:
   print('x is greater than z')
else:
   print('x and z are equal')
Enter fullscreen mode Exit fullscreen mode

Nested conditionals

One conditional can also be nested within another.Here is a three-branch example.

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')

Enter fullscreen mode Exit fullscreen mode

Catching exceptions using try and except

Handling an exception with a try statement is called catching an exception.
Consider this example; Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input

# Inquire the input from the user
hours = input("Enter the number of hours worked:")
rate = input("Enter the rate: ")

# calculate pay computations
try:
    hours = float(hours)
    rate = float(rate)

    if hours < 0 or rate < 0:
        print("Invalid input")
    elif hours <= 40:
        pay = hours * rate
        print(f"Payment is :{pay}")
    elif hours > 40:
        pay = 40 * rate + (hours - 40) * rate * 1.5
        print(f"Payment is:{pay}")

except :
    print("Error: please enter numeric input")
Enter fullscreen mode Exit fullscreen mode

The statements in the try block are first executed by Python. If everything goes as planned, it skips the unless block and continues. In the event that an exception occurs within the try block, Python exits the try block and begins the sequence of statements within the except block.
Catching an exception typically provides you the opportunity to address the issue, try again, or at the very least, gracefully terminate the program.

Functions

A function is a named sequence of statements that
performs a computation.

Reasons to use functions

• By naming a collection of statements, you have the chance to make your program easier to read, comprehend, and debug.
• Functions can reduce the size of a program by removing repeated code. If you later decide to edit something, you only need to do so once.
• By breaking a lengthy program down into functions, you may debug each component separately before putting them all together to create a functional whole.
• Functions with good design are frequently helpful for many programs. One can be reused after being written and tested.

Function calls

  • When you define a function, you specify the name and the sequence of statements.
  • The argument is a value or variable that we are passing into the function as input to the function. It is expressed inside parentheses.
  • A function “takes” an argument and “returns” a result called the return value. Example of a function
print("I am learning functions")

Enter fullscreen mode Exit fullscreen mode

Built-in functions

Python provides a number of important built-in functions that we can use without needing to provide the function definition.Here are examples;
print():Enables one display an output

print("FUNCTION")
Enter fullscreen mode Exit fullscreen mode

type():Enables one to know the data type of a value.

print(type("FUNCTION"))
Enter fullscreen mode Exit fullscreen mode

len(): Enables one to know the lenght of a value.

x = 'FUNCTION'
len(x)
Enter fullscreen mode Exit fullscreen mode

Type conversion functions

int can convert floating-point values to integers

int('89')
Enter fullscreen mode Exit fullscreen mode

float converts integers and strings to floating-point numbers.

float("67")
Enter fullscreen mode Exit fullscreen mode

str converts its argument to a string.

str(678)
Enter fullscreen mode Exit fullscreen mode

Random numbers

Pseudorandom numbers enables one regenerate the same output of the codes.
The random module provides functions that generate pseudorandom numbers.
The random function is only one of many functions that handle random numbers.
The randint function takes the parameters low and high, and returns an integer between low and high (including both).

The random module also provides functions to generate random values from continuous distributions including Gaussian, exponential, gamma

import random
x = [random.randint(5, 10) for i in range(10)]
random.choice(x)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • random.randint(5, 10) generates a random integer between 5 and 10 (inclusive).
  • x = [random.randint(5, 10) for i in range(10)] creates a list of 10 random integers between 5 and 10.
  • random.choice(x) picks a random element from the list x

Adding new functions

A function definition specifies the name of a new function and the sequence of statements that execute when the function is called.

defis a keyword that indicates that this is a function definition.
An empty parentheses after the name indicate that this function doesn’t take any arguments.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented.

Example of a function;
Write a function that takes the lengths of the two shorter sides of a right triangle as its parameters. Return the hypotenuse of the triangle, computed using Pythagoreantheorem, as the function’s result. Include a main program that reads the lengths of the shorter sides of a right triangle from the user, uses your function to compute the length of the hypotenuse, and displays the result.

import math

# Taking the lengths of two shorter sides of a right triangle 
x = float(input("Enter the first length of one of the shorter sides of the right triangle :"))
y = float(input("Enter the second length of one of the shorter sides of the right triangle :"))

def hypotenuse(x, y):
    hypotenuse = math.sqrt(x**2 + y**2)
    return hypotenuse

print(f"The hypotenuse of the triangle is {hypotenuse(x,y)}")

Enter fullscreen mode Exit fullscreen mode

Explanation:
This code calculates the hypotenuse of a right triangle using the Pythagorean theorem. The user is asked to input the lengths of the two shorter sides of the triangle, and the float() function is used to convert the input values to floating-point numbers.

The hypotenuse() function takes two arguments x and y that represent the lengths of the two shorter sides of the right triangle. Inside the function, the math.sqrt() function is used to calculate the square root of the sum of squares of x and y using the Pythagorean theorem. The result is then returned as the value of the hypotenuse variable.

Finally, the print() function is used to output the result of the hypotenuse() function call in a formatted string. This code demonstrates how functions can take arguments as input and return a value as output. The flow of the function is that the two arguments x and y are passed to the function, and then the Pythagorean theorem is used to calculate the length of the hypotenuse. Finally, the calculated hypotenuse is returned as the output of the function, which is then printed to the user.

Key words
Argument: A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
Body:The sequence of statements inside a function definition.
Low of execution: The order in which statements are executed during a program run.
Function call: A statement that executes a function. It consists of the function name followed by an argument list.
Function definition: A statement that creates a new function,specifying its name,parameters, and the statements it executes.
Parameter: A name used inside a function to refer to the value passed as an argument.
Return value: The result of a function. If a function call is used as an expression,the return value is the value of the expression.
Void function: A function that does not return a value.

To get more examples of the concepts learnt here check out my github codes().If you have any questions you can write me an email(ombati.ogeto20@students.dkut.ac.ke).

Reference
Python for Everybody by Dr. Charles R. Severance

Top comments (0)