Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Notes On Python

Uploaded by

danielsarbah08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Notes On Python

Uploaded by

danielsarbah08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

PYTHON

Python is a popular general-purpose programming language known for its readability and ease
of use. It is a versatile language used in various domains, including web development, data
science, and machine learning.

Syntax
Syntax refers to the rules that define how a program is structured. It is essentially the grammar
of the language, specifying how elements like keywords, operators, and expressions are
arranged to create valid code. Proper syntax is essential for the python interpreter to understand
and execute your program.

Below are some the rules in python;

1. Indentation-based structure: python utilizes indentation to delineate blocks of code,


eschewing traditional braces {} found in languages like C, C++ or Java. This enforces
readability and encourages consistent coding practices.
2. Statement termination: while statements typically end with a newline character,
semicolons can be used to separate multiple statements on the same line, facilitating
concise code construction.
3. Comments: comments are initiated with the # symbol and extend to the end of the line.
This allows developers to annotate code for clarity and documentation purposes.
4. Case sensitivity: python distinguishes between lowercase and uppercase identifiers,
adhering to a case-sensitive convention. For instance, ‘variable’ and ‘Variable’ would
be treated as distinct entities.
5. String definition: strings can be defined using either single ‘ or double “ quotes, offering
flexibility in string declaration.

Semantics
Semantics deals with the meaning of your python code. While syntax ensures the code is
grammatically correct, semantics determines what the code actually does. It focuses on the
program’s logic and how it translates the written instructions into meaningful actions.

In simpler terms, syntax is about how you write the code, while semantics is about what the
code does.
Comments
Comments are non-executable statements in Python code that are used for documentation and
explanation purposes. They provide additional context, explanations, or reminders to both the
programmer and other collaborators.

Types of Comments

1. Single-line comments: Single-line comments start with the ‘#’ symbol and extend to
the end of the line. They are used for brief explanations or annotations.
Example;
#this is a single-line comment
2. Multi-line comments: although Python does not have a built-in syntax for multi-line
comments, you can use triple quotes “”” or ‘’’ to create multi line strings as a
workaround
Example;
“””
This is a
multi-line comment
“””

Common Uses

1. Documentation: Comments are often used to document code by providing explanations


for complex algorithms, functions, or classes.
2. Clarifications: comments can clarify the intent or purpose of certain code segments,
making it easier for others (yourself) to understand.
3. TODOs and Reminders: comments can serve as reminders for future improvements,
optimizations, or bug fixes using placeholders like ‘TODO’ or ‘FIXME’
4. Debugging: comments can be used to temporarily disable or comment out code during
debugging or testing phases
Variables

Variables are symbolic names given to values or memory locations that can be manipulated or
referenced in a program. They serve as placeholders for data that can change during the
execution of a program.

In python, variables are dynamically typed, meaning you do not need to declare the type of a
variable before assigning a value to it. The type of a variable is inferred at runtime based on
the value assigned to it.

Here is a simple example in python:

x=5
name = “Owusu”

In the above example, ‘x’ and ‘name’ are variables. ‘x’ holds an integer value ‘5’, while ‘name’
holds a string value ‘”Owusu”’. You can later change the value of a variable as below;

x = 10

the value of ‘x’ is now changed to ‘10’. Variables are fundamental to programming as they
enable developers to store and manipulate data, making programs more flexible and powerful.

Rules for naming variables in Python

1. Use descriptive names: choose names that reflect the purpose or meaning of the
variable. This enhances code readability and comprehension.
2. Start with a letter or underscore: variable names must begin with a letter (a-z, A-Z) or
an underscore (_). They cannot begin with a number or any other special character.
3. Followed by letters, digits or underscores: after the initial character, variable names
may consist of letters, digits (0-9), or underscores (_). They cannot contain spaces or
special characters.
4. Case-Sensitive: python is case-sensitive, so ‘my_variable’, ‘My_variable’, and
‘MY_VARIABLE’ are considered distinct variables.
5. Avoid keywords: variable names cannot be the same as python keyword or reserved
words such as ‘if’, ‘else’, ‘for’, ‘while’, ‘def’, ‘class’, etc
6. Use snake case or camel case: for multi-word variable names, use snake_case or
camelCase. For example, ‘my_variable’, ‘myVariable’ etc
Input

The ‘input()’ function is used to prompt the user to input during program execution.
When ‘input()’ is called, it displays a prompt (if provided) and waits for the user to enter a
value followed by pressing the Enter key.The ‘input()’ function always returns a string,
regardless of the type of input entered by the user.
The general syntax for using ‘input()’ is;

variable_name = input(“prompt message”)

example:

name = input(“enter your name: “)

age = input(“enter your age: “)

When using the ‘input()’ function in Python, the input provided by the user is always returned
as a string. However, it's common in programming to require input in different data types such
as integers, floats, or booleans. Therefore, it's often necessary to convert the input string to the
desired data type. This process is known as type conversion or casting.

1. Converting Input to Integer:


If you expect the user to input an integer, you can use the ‘int()’ function to convert the
input string to an integer data type. This is useful for numerical operations.
Example;
age = int(input(“enter your age: “))
2. Converting Input to Float:
If the input is expected to be a floating-point number, you can use the ‘float()’ function
to convert the input string to a float data type.
Example;
weight = float(input(“enter your weight (in kg): “))
Output

The ‘print()’ function is used to display output to the console or standard output. ‘print()’ can
accept zero or more arguments, separated by commas.

The general syntax for using ‘print()’ is;

print(“message goes here”) or

print(value)

example:

print(“hello, world!”)

print(my_variable)

Concatenation

Concatenation refers to the operation of joining two or more strings together to create a single
string. It's a fundamental string manipulation technique used in programming.

In Python, strings can only be concatenated using the ‘+’ operator or the str.join() method.
To concatenate a string with a number, use the comma ‘,’. Another way of concatenation is the
use of f-string which is only supported in python 3.6 and above.

Example;

1. print(“hello “ + “world”)
2. name = “Kofi”
print(“hey “ + name)
3. print(“the answer is “, 45)
4. results = 10 + 4
print(“the results is“, results)
5. area = length * breadth
print(f”the area of the rectangle is {area}”)
6. name = “Ama”
age = 24
print(f”hello {name} you are {age} years old”)
Control Structure

Control structures are programming constructs that enable developers to control the flow of
execution in a program. They determine the order in which instructions are executed based on
specified conditions or criteria.

Types of Control Structures

1. Sequential Execution: In sequential execution, statements are executed in the order


they appear in the code, from top to bottom. This is the default behaviour in most
programming languages unless specified otherwise by control flow structures.
Syntax;
Statement1
Statement2
Statement3

StatementN

Example:
Num1 = 3
Num2 = 4
Results = Num1 + Num2
print(Results)

2. Conditional Statements: these structures allow the program to make decisions based
on conditions. Common conditional statements include ‘if’, ‘elif’ (else if), and ‘else’.
i. If statements
if condition:
#code block executed if condition is true
ii. If – else statements
if condition:
#code block executed if condition is true
else:
#code block executed if condition is false
iii. If – else if – else
if condition:
#code block executed if condition is true
elif condition:
#code block executed if another_condition is true
else:
#code block executed if none of the above
conditions are true
3. Loops: loops are used to execute a block of code repeatedly as long as a specified
condition is true. Python supports ‘for’ loops and ‘while’ loops.
i. For loop
for item in items:
#code block executed for each item in the items
ii. While loop
while condition:
#code block executed as long as condition is true

Purpose of Control Flow

1. Execution Flow: Control structures determine the sequence in which instructions are
executed, allowing programs to perform tasks in a specific order.
2. Decision Making: Conditional statements enable the program to make decisions based
on conditions, altering the execution path accordingly.
3. Repetition: Loops facilitate repetitive execution of a block of code, reducing
redundancy and improving efficiency.

You might also like