0% found this document useful (0 votes)
3 views23 pages

Python SecA

The document provides an introduction to programming with Python, covering algorithms, flowcharts, and the basics of Python including installation, syntax, data types, and operators. It emphasizes the importance of indentation, keywords, comments, and variables in Python programming. Additionally, it explains how to take user input and perform type casting.
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)
3 views23 pages

Python SecA

The document provides an introduction to programming with Python, covering algorithms, flowcharts, and the basics of Python including installation, syntax, data types, and operators. It emphasizes the importance of indentation, keywords, comments, and variables in Python programming. Additionally, it explains how to take user input and perform type casting.
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

Programming using Python

Course Code: DAL1003


Section A

Algorithm and Flowchart - Introduction and components.

Introduction to Python and Installation on various Operating Systems.

Overview – IDEs (Jupyter, PyCharm, Visual Studio, Colab, etc.), PEP style guide

Python Basics – keywords, Importance of indentation, scripting, comments,


DocString, Data-types in Python.

Variables in Python – Rules of declaration and usage, Typecasting

Operators in Python – Assignment, Logical, Arithmetic etc., Taking User Input

Online Book: https://automatetheboringstuff.com/#toc


What is an Algorithm?

An algorithm is a precise and finite procedure for solving a problem or performing a


computation, consisting of well-defined instructions that take input data and produce
output(s) as a result.

● A step-by-step procedure or formula for solving a problem.


● To provide a clear set of instructions for solving a particular problem.
● Algorithms can be reused and adapted for different problems.
● Finite, well-defined, and effective.
● Helps in optimizing performance and resources.
● Provides structured methods to solve problems.

When implementing an algorithm, it’s essential to:


1. Clearly define the inputs and outputs
2. Ensure each step is well-defined and unambiguous
3. Use a suitable programming language or representation (e.g., pseudocode, flowcharts)
4. Test and iterate the algorithm to ensure correctness and efficiency
Flowchart

● A visual representation of an algorithm or process.

● To depict the flow of control and data within a system.

● Symbols used to represent different types of actions or


decisions.

● Provides a clear, visual representation of processes.

● Facilitates communication among team members.

● Helps in identifying and troubleshooting issues.

Flowcharts: https://youtu.be/vBtGO9pXfrQ?feature=shared
Flowchart - Symbols

Process Symbol represents a step in a process. This is the most common component of a
flowchart.
Terminal Symbol indicates the beginning or end of a flowchart. This symbol usually has the text
“Start” or “End”.
Flow lines indicate the process’ direction. Each flowline usually connects two blocks.
Decision Symbol indicates a step that decides the next step in a process. This is commonly a
Yes/No or True/False question.
Introduction to Python

What matters is that you learn Programming and not a Programming Language?
This distinction is a subtle but important one. Programming is the way of thinking that’s required.
It’s the process of breaking down a problem into logical steps and then systematically putting
them in the right order.

To write code, you need a programming language.

Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991. Python is a programming language that lets you work more quickly and integrate your
systems more effectively. A computer needs to know what the command is. In Python, we would
use the built-in function print() for output. This is one of the basic Python words, and it is
followed by parentheses (). The parentheses, or brackets, and the fact that print is written in
lowercase indicate that this is a function.

print("Hello World") v/s print # without ()


Introduction to Python

The most recent major version of Python is Python 3


- Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
- Python has a simple syntax similar to the English language.
- Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
- Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.

Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.

Usage:
- Python can be used on a server to create web applications.
- Python can connect to database systems. It can also read and modify files.
- Python can be used to handle big data and perform complex mathematics.
- Python can be used for rapid prototyping, or for production-ready software development.
Python Installation

Getting the Python language is the easy part. Go to python.org and choose the ‘Downloads’ tab.
You will see a button to download the latest version of Python for your operating system. You
can download and install this on your computer.

https://www.python.org/downloads/

It is possible to write Python in an Integrated Development Environment, such as IDLE, Thonny,


Pycharm, Netbeans or Eclipse which are particularly useful when managing large collections of
Python files.

Python source files use the ".py" extension and are called "modules."
Example: Python module hello.py

Python Enhancement Proposals (PEP) - Style Guide for Python Code


https://peps.python.org/pep-0008/#indentation
Python IDEs
Python Basics - Importance of Indentation

Indentation refers to the spaces at the beginning of a code line.


Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.
The number of spaces is up to you as a programmer, the most common use is four, but it has to
be at least one.

>>> var1 = 89.11


>>> var2 = True

Syntax Error:
>>> var1 = 89.11
>>> var2 = True # extra spaces in the front causes error.

Note: You have to use the same number of spaces in the same block of code, otherwise Python
will give you an error.
Python Basics - Keywords

Python keywords (35 in total) are reserved words that have a special meaning to the interpreter. They
are used to define the syntax of the programming language and cannot be used as variable names,
function names, or identifiers.

Overall, Python keywords are an essential part of the language’s syntax and are used to define the
structure and behavior of Python programs.

Additionally:
True: This keyword is used to represent a boolean true. If a statement is true, “True” is printed.
False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed.
None: This is a special constant used to denote a null value or a void. It’s important to remember, 0, any
empty container(e.g. empty list) does not compute to None.
Python Basics - Comments

Comments can be used to explain Python code.


Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Comments starts with a #, and Python will ignore them:


# This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:
print("Hello, World!") # This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent
Python from executing code:
# print("Hello, World!")
# var1 = 59
print("Good, Morning!")
Python Basics - Comments - DocString

Comments can also be multi-lined using DocString.

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank
line, followed by a more elaborate description. The summary line may be used by automatic
indexing tools; it is important that it fits on one line and is separated from the rest of the
docstring by a blank line. The summary line may be on the same line as the opening quotes or
on the next line. The entire docstring is indented the same as the quotes at its first line.

"""
This is a multi-line comment

Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
Python Variables

Variables are containers for storing data values having a name ( also identifier ).
A variable is created the moment you first assign a value to it.
Variables do not need to be declared with any particular type, and can even change type after
they have been set.

Rules of variable declaration:


- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- Can only contain alphanumeric 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.

>>> var1 = “hello” >>> 2myvar = "John" # invalid variable


>>> _var2 = 13.91 >>> my-var = "John" # invalid variable
>>> is_adult = True >>> my var = "John" # invalid variable
>>> x, y = "Orange", "Banana" >>> f%Name = "Henry" # invalid variable
>>> x = y = z = 98.13 >>> True = True # invalid variable
Python Variables

Assigning Single value to Single Variable:


play_cards = 73
color = ‘red’
is_happy = True

Assigning Single value to Multiple Variables:


x = y = z = 21
name1 = name2 = “Ironman”

Assigning Multiple values to Multiple Variables:


a, b, c = 41, ‘hello’, False
name, age, marks, dept = ‘Hulk’, 29, 88, ‘’CSDA’’

# testing all the values assigned using different variations of print()


print(color)
print(color + ‘ ’ + name1 + ‘ ’ + dept) # string concatenation / joining
print(name, age, marks, dept)
print(a, c)
print(x, y)
Python Basics - Data Types

int - holds signed integers of non-limited length.


num1 = 5
num2 = -81 # int can be negative or positive
print(num1, 'is of type', type(num1))

float - holds floating decimal points and it's accurate up to 15 decimal places.
num3 = 2.0
num4 = -91.47 # float can also be negative or positive
print(num2, 'is of type', type(num2))

complex - holds complex numbers.


num5 = 1+2j
print(num3, 'is of type', type(num3))

str - string, it is a sequence of characters represented by either single or double quotes.


name = 'Chandler'
full_name = “Tom Cruise”

bool - boolean, holds either True or a False value only.


is_heavy = True # Note: T in True must be capitalized
is_old = False # Note: F in False must be capitalized
Python Basics - Type Casting

We can use the type() function to know which class a variable or a value belongs to.
print(type(num2))

Type Conversion/Casting is the process of converting one type of number into another.

var1 = 981
var1 = float(var1) # int to float: returns 981.0
var1 = str(var1) # int to string: returns ‘981’
var1 = bool(var1) # int to boolean: returns True

print(var1) # prints value of var1


print(type(var1)) # mind the braces, they must open and close in pairs

Type Casting: https://www.youtube.com/watch?v=Qtq83lAoogM


Python - Operators

Python operators are symbols used to perform specific operations on one or more operands.
These operands can be variables, values, or expressions. The operands used with the operator
are evaluated according to their precedence, which defines the order in which operations are
performed.
Arithmetic Operators: These operators are used for basic mathematical operations like addition,
subtraction, multiplication, and division. For x = 21 and y = 5,
+ Addition x+y 26

- Subtraction x-y 16

* Multiplication x*y 105

/ Division x/y 4.2

** Exponentiation / Raise to power x ** y 4084101

// Floor / Integer Division x // y 4

% Modulus / Remainder x%y 1


Python - Operators

Comparison Operators: These operators are used to compare values and evaluate conditions.
Returns either True or False value. For x = 21 and y = 5,

== is equal to x == y False

!= is not equal to x != y True

> is greater than x>y True

< is less than x<y False

>= is greater than or equal to x >= y True

<= is less than or equal to x <= y False


Python - Operators

Logical Operators: These operators are used to combine conditions and evaluate logical expressions.
and for logical AND c1 and c2 Returns True only if both c1 AND c2 condition is True

or for logical OR c1 or c2 Returns True if any c1 OR c2 condition is True

not for logical NOT not c2 Returns True if c2 is False and vice versa

Assignment Operators: These operators are used to assign values to variables.


Python - Operators - Precedence

In Python, operator precedence is as follows:

1. Parentheses / Bracket ()
2. Exponentiation **
3. Multiplication, Division, Floor Division, Modulus *, /, //, %
4. Addition, Subtraction +, -
5. Comparison Operators ==, !=, >, <, >=, <=
6. Logical Operators and, or, not
print(100 + 5 * 3 ** 2 // 5)
If two operators have the same precedence, the expression is evaluated from left
to right. Example: print(5 + 4 - 7 + 3)
Python - Taking input from the user

To take input from the user in Python, you can utilize the built-in input() function. This function
stops the program and waits for the user’s input, then returns it as a string.

char = input("Enter a character: ")

time_input = input("Enter time (HH:MM:SS): ")

user_input = input("Enter something: ")


print("You entered:", user_input)

#If you need to convert the input to a different data type (e.g., integer or
float), you can use int() or float() functions accordingly (Type-Casting).

num1 = int(input("Enter first number: "))


num2 = float(input("Enter second number: "))
print("First Number Entered:", num1)
print("Second Number Entered:", num2)

You might also like