0% found this document useful (0 votes)
44 views13 pages

Lab1 Python

This document discusses programming and the Python programming language. It defines programming as the process of designing, writing, testing, and maintaining computer programs. A program is a set of instructions that tells a computer what to do. Programming languages allow humans to communicate with computers by giving them instructions. The document then discusses that we will use the Python programming language, which is easy to learn, supports multiple programming paradigms, and has a large standard library. It also discusses how programs work by being written, compiled/interpreted, executed with flow control, accepting input/output, and terminating. Integrated Development Environments (IDEs) are also discussed, which provide a comprehensive software development environment with features like code editing, debugging

Uploaded by

abh939463
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views13 pages

Lab1 Python

This document discusses programming and the Python programming language. It defines programming as the process of designing, writing, testing, and maintaining computer programs. A program is a set of instructions that tells a computer what to do. Programming languages allow humans to communicate with computers by giving them instructions. The document then discusses that we will use the Python programming language, which is easy to learn, supports multiple programming paradigms, and has a large standard library. It also discusses how programs work by being written, compiled/interpreted, executed with flow control, accepting input/output, and terminating. Integrated Development Environments (IDEs) are also discussed, which provide a comprehensive software development environment with features like code editing, debugging

Uploaded by

abh939463
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

ENG.

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.

What is a programing language?


In simple words, a programming language is a way for humans to communicate with computers and
give them instructions. It's like a special language that computers can understand and follow to
perform specific tasks. Just like we use spoken or written languages to communicate with each other,
programming languages are used to tell computers what to do.

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.

What programming language will we use?


In the upcoming sections, we are going to use a programming language called python. Python is a
high-level, interpreted programming language known for its simplicity and readability. It was created
by Guido van Rossum and first released in 1991. Python emphasizes code readability and a clean
syntax, making it easier to write and understand compared to many other programming languages.

Here are some key features of Python:

1. Easy-to-learn: Python has a relatively simple and straightforward syntax, making it an


excellent choice for beginners. The language emphasizes code readability, using indentation
and whitespace to define code blocks instead of traditional braces or keywords.
ENG. Shehab Alward

2. Multi-paradigm: Python supports multiple programming paradigms, including procedural,


object-oriented, and functional programming. This flexibility allows developers to choose the
best approach for their specific needs.

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.

5. Cross-platform: Python is available on multiple platforms, including Windows, macOS, Linux,


and various other operating systems. This cross-platform compatibility allows developers to
write code on one operating system and run it on another without significant modifications.

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.

How does a program work?


Here's a simplified explanation of how a program works:

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.

Different python IDEs


There are several popular Integrated Development Environments (IDEs) that you can use with Python.
Here are some commonly used ones:

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.

3. Jupyter Notebook/JupyterLab: Jupyter Notebook is an interactive environment that allows


you to create and share documents containing live code, visualizations, and explanatory text.
JupyterLab is the next-generation user interface for Jupyter Notebook, offering a more flexible
and powerful environment. It's widely used for data analysis, scientific computing, and
prototyping.

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.

Installing the IDE and writing the first program.

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

Comments serve several purposes, such as:

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:

# This is a single-line comment in Python

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.
'''

3- Documentation comments (using docstrings):

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:

result = a + b # Calculate the sum of a and b

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.

Here are some key characteristics of variables in programming languages:

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.

Syntax of defining a variable in python

[Variable name ] [assigning parameter] [value].

A variable is created the moment you first assign a value to it.

Example :

name = "Ali"
age = 25
ENG. Shehab Alward

Rules for naming variables in Python

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.

Examples

Legal variable names:

name = "Saeed"
my_name = "Saeed"
_name = "Saeed"
myName2 = "Saeed"
NAME= "Saeed"

Illegal variable names:


1name = "Saeed"
My-name = "Saeed"
My name = "Saeed"

Multi Words Variable Names

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"

• Pascal Case : Each word starts with a capital letter:


MyVariableName = "John"

• Snake Case : Each word is separated by an underscore character:


my_variable_name = "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:

• int: Represents integer values (e.g., 5, -10, 100).

• 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:

• str: Represents a sequence of characters (e.g., "Hello", 'Python', "123").

• 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:

• set: Represents an unordered collection of unique elements (e.g., {1, 2, 3, 4}).

• frozenset: Represents an immutable set (e.g., frozenset({1, 2, 3})).

6. None Type:

• None: Represents the absence of a value or a null value.

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:

• int(x): Converts x to an integer. If x is a floating-point number, it truncates the decimal part.


If x is a string, it should contain a valid integer representation.
num_str = "10"
num_int = int(num_str)
print(num_int) # Output: 10
ENG. Shehab Alward

• float(x): Converts x to a floating-point number. If x is an integer, it adds a decimal point


with zero as the fractional part. If x is a string, it should contain a valid floating-point
representation.

num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0

• str(x): Converts x to a string representation.


num_int = 10
num_str = str(num_int)
print(num_str) # Output: "10"

• 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

result = num_int + num_float # Implicitly converts num_int to a float


print(result) # Output: 13.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.

Assigning multiple values to multiple variables

Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

Assigning Single value to multiple variables


x = y = z = "Orange"
ENG. Shehab Alward

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.

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

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!")

printing multiple variables

name = "Ali"
age = 25
print("My name is", name, "and I am", age, "years old.")

printing multiple values seperatd by ( , )

x = 10
y = 20
z = 30
print(x, y, z, sep=", ")

printing without a new line

print("Hello", end=" ")


print("World!")

printing multi line string


print("""
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
ENG. Shehab Alward

You can also use the + operator to output multiple variables:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

if the variables are numeric values the + work as mathematic operator


x = 5
y = 10
print(x + y)

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

Printing a raw string

print(r'C:\some\name')

Input function
1. Basic input:

name = input("Enter your name: ")


print("Hello, " + name + "!")

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:

age = int(input("Enter your age: "))


next_year = age + 1
print("Next year, you will be", next_year, "years old.")
ENG. Shehab Alward

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:

values = input("Enter three values, separated by spaces: ")


a, b, c = values.split()
print("You entered:", a, b, c)
Here, the user is asked to enter three values separated by spaces. The split() method is used to
split the input string into individual values, which are then assigned to variables a, b, and c. The
program then displays the entered values.

4. Evaluating expressions:

expression = input("Enter a mathematical expression: ")


result = eval(expression)
print("Result:", result)
In this example, the user is prompted to enter a mathematical expression as a string.
The eval() function is used to evaluate the expression and store the result in the result variable.
The program then displays the computed result.

Types of Errors in Python.


In Python, there are several types of errors that can occur during the execution of a program. Here
are some common types of errors along with examples:

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:

# Missing colon at the end of the if statement


if x > 5
print("x is greater than 5")

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:

# Inconsistent indentation within a code block


def my_function():
print("This is inside the function")
print("This is also inside the function") # IndentationError here

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:

# Referencing an undefined variable


x = 5
print(y) # NameError: name 'y' is not defined

4- TypeError: These errors occur when an operation or function is applied to an object of an


inappropriate type.

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'

You might also like