Lab1 Python
Lab1 Python
Shehab Alward
LAB 1
What is programing?
Programming is the process of designing, writing, testing, and maintaining computer
programs.
What is a program?
A computer program is a set of instructions (statements ) that tells a computer what to do, and a
programmer is someone who writes these instructions in a programming language that a computer
can understand.
Programming languages have their own rules and syntax, similar to grammar and vocabulary in human
languages. They allow programmers to write sets of instructions, called code, that the computer can
execute. These instructions can range from simple tasks like adding numbers to complex operations
like building software applications or websites.
Programming languages are used to create different types of software, including operating systems,
applications, games, and websites. Some commonly used programming languages include Java,
Python, C++, JavaScript, and Ruby.
3. Large standard library: Python comes with a comprehensive standard library that provides a
wide range of modules and functions for various tasks, such as file I/O, networking,
mathematics, and more. This rich library ecosystem helps simplify development by providing
ready-to-use solutions for common programming tasks.
4. Third-party libraries and frameworks: Python has a vibrant ecosystem of third-party libraries
and frameworks that extend its capabilities. Popular libraries like NumPy, Pandas, and
Matplotlib are widely used for data analysis and scientific computing. Additionally,
frameworks like Django and Flask are popular for web development.
Python is used in a wide range of applications, including web development, data analysis, scientific
computing, artificial intelligence, machine learning, automation, and more. Its simplicity and
versatility have contributed to its popularity among developers worldwide.
1. Writing the program: A programmer writes the program using a programming language. They
define the logic, algorithms, and specific instructions to achieve a desired outcome. This
involves using the syntax and rules of the chosen programming language to create a set of
instructions.
2. Compiling or interpreting: Depending on the programming language, the program may need
to be either compiled or interpreted. Compiling involves converting the human-readable code
into a format that the computer can directly understand and execute. Interpreting involves
reading and executing the code line by line as it's encountered.
3. Execution: Once the program is compiled or interpreted, the computer starts executing the
instructions. It reads the instructions one by one and performs the actions specified, such as
calculations, data manipulation, or interacting with devices like the keyboard or the screen.
4. Flow control: Programs often include flow control mechanisms such as loops, conditionals,
and functions. These control the order in which instructions are executed based on certain
conditions. Loops allow for repetition, conditionals enable decision-making, and functions
allow for reusable blocks of code.
5. Input and output: Programs can interact with the user or other external entities through input
and output operations. Input can be received from sources like the keyboard, mouse, or files,
while output can be displayed on the screen or saved to files or other devices.
6. Termination: The program continues executing instructions until it reaches the end or
encounters specific instructions to stop. At that point, the program terminates, and its
execution comes to a halt.
ENG. Shehab Alward
Programmers use a variety of tools and techniques to create programs, including integrated
development environments (IDEs), text editors, debuggers, and version control systems (VCS) .
They work with teams of developers, project managers, and other stakeholders to create software
that meets the needs of their users.
What is an IDE?
An IDE (Integrated Development Environment) is a software application that provides a
comprehensive environment for software development. It combines several tools and features into a
single user interface, aiming to enhance the efficiency and productivity of programmers. Here's an
overview of what an IDE typically includes:
1. Code Editor: An IDE includes a code editor that allows programmers to write, edit, and manage
their source code. The editor provides features like syntax highlighting, code completion, and
indentation, which help in writing code accurately and efficiently.
2. Compiler/Interpreter: Many IDEs come with built-in compilers or interpreters for different
programming languages. These tools convert the human-readable code into machine-
readable instructions or execute the code directly, providing immediate feedback on any
errors or issues.
3. Debugging Tools: IDEs often provide debugging tools that assist programmers in finding and
fixing errors in their code. They enable stepping through the code line by line, inspecting
variables, setting breakpoints to pause execution, and examining the program's state during
runtime.
4. Build and Automation Tools: IDEs can integrate with build tools that automate the process of
compiling, linking, and packaging the software. They enable tasks such as building executable
files, managing dependencies, and running tests without needing to rely on command-line
tools separately.
5. Version Control: IDEs often include features for version control, allowing programmers to
manage their code repositories using systems like Git or SVN. These features enable tasks like
committing changes, branching, merging code, and resolving conflicts directly within the IDE.
6. Project Management: IDEs provide tools to organize and manage projects effectively. They
allow programmers to create, open, and save projects, manage project files and directories,
and navigate between different files and components of the project.
7. Integrated Documentation: Some IDEs offer integrated documentation tools that provide easy
access to programming language documentation, libraries, and APIs. This helps programmers
quickly look up information and usage examples without leaving the IDE.
8. Additional Features: IDEs may include various additional features, such as code refactoring
tools (automated code restructuring), code templates or snippets for faster coding, code
analysis tools for identifying potential issues, and integration with external tools and plugins
to extend functionality.
Overall, an IDE brings together multiple development tools and features into a unified environment,
simplifying and streamlining the software development process. It provides a convenient and efficient
ENG. Shehab Alward
workspace for programmers to write, test, debug, and manage their code, ultimately improving their
productivity and making the development process more convenient and efficient.
1. PyCharm: PyCharm is a powerful IDE developed by JetBrains. It offers a wide range of features,
including code completion, debugging tools, version control integration, and support for web
development frameworks like Django and Flask. There is a community edition available for
free, as well as a professional edition with additional features.
2. Visual Studio Code (VS Code): VS Code is a lightweight and versatile IDE developed by
Microsoft. It has excellent Python support through various extensions, providing features like
code completion, linting, debugging, and integrated terminal. It's free and highly
customizable.
4. Spyder: Spyder is an IDE designed specifically for scientific computing with Python. It provides
features like a variable explorer, debugging, code analysis, and integration with scientific
libraries such as NumPy and Matplotlib. Spyder is free and open-source.
5. Atom: Atom is a customizable and hackable text editor that can be turned into a Python IDE
using various community-developed packages. It offers features like code autocompletion,
syntax highlighting, and multiple panes for editing. Atom is free and open-source.
print("Hello, World!")
Syntax
• Statement end
• Indentation and block of codes
Comments
In programming languages, comments are portions of code that are ignored by the compiler or
interpreter and are used to provide explanatory notes or documentation within the code. Comments
are not executed as part of the program and do not affect its behavior. They are solely meant for
human readers, including other programmers who may need to understand or work with the code.
ENG. Shehab Alward
1. Documentation: Comments can be used to explain the purpose, functionality, or behavior of code
segments. They provide additional information to help other developers understand the code.
2. Code readability: Well-placed comments can make the code more readable and understandable
by adding context or clarifying complex logic.
3. Temporary code removal: Comments can be used to temporarily disable sections of code without
deleting them. This is useful during debugging or when experimenting with alternative code.
4. Annotations and reminders: Comments can serve as reminders or to-do lists for future
improvements, bug fixes, or enhancements to the code.
In Python, there are different types of comments:
1. Single-line comments: These comments start with a hash symbol (#) and extend until the end
of the line. They are used to add comments or explanations on a single line.
Example:
2. Multi-line comments (docstrings): These comments span multiple lines and are enclosed within
triple quotes (""" or '''). They are typically used for documenting functions, classes, or modules.
Docstrings have a special significance in Python and can be accessed at runtime to provide help
or generate documentation.
Example:
"""
This is a multi-line comment or docstring in Python.
It can span multiple lines and is typically used for documentation.
"""
or
'''
This is another way to create a multi-line comment or docstring in Python.
'''
Example:
def add_numbers(a, b):
"""
This function adds two numbers and returns the result.
Parameters:
- a: First number
- b: Second number
Returns:
- The sum of a and b
"""
return a + b
ENG. Shehab Alward
4- Inline comments:
Example:
Variables
In programming languages, variables are used to store and manipulate data. A variable is a named
location in memory that holds a value. It acts as a container for data that can be referenced and
modified throughout the program.
1. Declaration: Variables are typically declared with a specific name and optionally assigned an
initial value.
2. Assignment: Variables can be assigned values using the assignment operator (=) to store data
in the variable.
3. Data Types: Variables have a specific data type associated with them, which determines the
kind of data they can store (e.g., integers, strings, booleans).
4. Memory Storage: Variables occupy memory space to store their values. The size of the
memory allocated depends on the data type of the variable.
5. Value Retrieval: The value stored in a variable can be retrieved by referencing the variable's
name in the code.
6. Value Modification: Variables can be updated or modified by assigning a new value to them.
7. Scope: Variables have a scope, which defines the portion of the code where the variable is
accessible. Variables can have global scope (accessible throughout the program) or local scope
(accessible only within a specific block or function).
8. Naming Conventions: Variables have naming rules and conventions. Typically, they should
have meaningful names that describe the data they represent. Variable names may contain
letters, digits, and underscores, but they must start with a letter or an underscore.
Example :
name = "Ali"
age = 25
ENG. Shehab Alward
Examples
name = "Saeed"
my_name = "Saeed"
_name = "Saeed"
myName2 = "Saeed"
NAME= "Saeed"
Variable names with more than one word can be difficult to read. There are several techniques you
can use to make them more readable:
• Camel Case : Each word, except the first, starts with a capital letter:
myVariableName = "John"
Data types
In Python, there are several built-in data types that are used to represent different kinds of values.
Here are some commonly used data types in Python:
1. Numeric Types:
• float: Represents floating-point numbers with decimal places (e.g., 3.14, -0.5, 2.0).
ENG. Shehab Alward
2. Boolean Type:
• bool: Represents either True or False, used for logical operations and conditions.
3. Sequence Types:
• list: Represents an ordered collection of elements (e.g., [1, 2, 3], ['a', 'b', 'c']).
• tuple: Represents an ordered, immutable collection of elements (e.g., (1, 2, 3), ('a',
'b', 'c')).
4. Mapping Type:
• dict: Represents a collection of key-value pairs (e.g., {'name': 'Alice', 'age': 25}).
5. Set Types:
6. None Type:
You can find the type of a variable using the type function as follow:
age = 10
print(type(age))
Variables do not need to be declared with any particular type, and can even change type after they
have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable casting
In Python, variable casting, also known as type casting or type conversion, refers to the process of
changing the data type of a variable from one type to another. This allows you to perform operations
or assignments that require compatible data types.
Python provides several built-in functions that facilitate type casting. Here are some commonly used
casting functions:
num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0
• bool(x): Converts x to a Boolean value. The resulting Boolean value is False if x is falsy (e.g.,
zero, empty string, empty list) and True otherwise.
num_int = 10
num_bool = bool(num_int)
print(num_bool) # Output: True
It's worth noting that some type conversions may result in loss of precision or data. For example,
converting a floating-point number to an integer will truncate the decimal part, potentially leading to
loss of information.
• Additionally, Python also supports implicit type conversions, where the interpreter
automatically converts variables between compatible types. For example, when performing
arithmetic operations between different numeric types, Python will automatically cast the
operands to a common type.
num_int = 10
num_float = 3.14
Explicitly casting variables using the built-in casting functions can be useful when you want to ensure
specific data types or when you need to convert user input or data from one format to another.
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Print function:
The print() function in Python is used to display output to the console or terminal. It takes one or more
arguments, which can be strings, numbers, variables, or expressions, and prints them as text.
Printing a string
print("Hello, World!")
name = "Ali"
age = 25
print("My name is", name, "and I am", age, "years old.")
x = 10
y = 20
z = 30
print(x, y, z, sep=", ")
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Escape characters
Escape characters in Python are special characters that are used to represent certain non-printable or
special characters within string literals. They are preceded by a backslash (\) to indicate their special
meaning. Here are some commonly used escape characters in Python:
• \n new line
• \t tap
• \\ Backslash
• \' Single Quote
• \" Double Quote
print(r'C:\some\name')
Input function
1. Basic input:
This prompts the user to enter their name and stores the input in the name variable. It then prints
a greeting using the entered name.
2. Numeric input:
In this example, the input() function is used to prompt the user to enter their age. The input is
converted to an integer using int() since input() returns a string by default. The program then
performs some calculations with the entered age and displays the result.
3. Multiple inputs:
4. Evaluating expressions:
1- SyntaxError: These errors occur when the code violates the syntax rules of the Python language.
It usually indicates a mistake in the code structure or formatting.
Example:
2- IndentationError: These errors occur when there are issues with the indentation of the code.
Python relies on consistent indentation to define code blocks.
Example:
3- NameError: These errors occur when a name or variable is referenced before it is defined or
outside of its scope.
ENG. Shehab Alward
Example:
Example:
# Attempting to concatenate a string and an integer
x = "Hello"
y = 5
print(x + y) # TypeError: can only concatenate str (not "int") to str
5- IndexError: These errors occur when trying to access an element of a sequence (like a list or a
string) using an invalid index.
Example:
# Accessing an element at an index that is out of range
my_list = [1, 2, 3]
print(my_list[5]) # IndexError: list index out of range
6- ValueError: These errors occur when a function receives an argument of the correct type but an
inappropriate value.
Example:
# Converting a string to an integer, but the string contains non-
numeric characters
x = int("abc") # ValueError: invalid literal for int() with base 10: 'abc'