0% found this document useful (0 votes)
2 views10 pages

NOTES_Introduction to Python

The document provides an introduction to Python, covering algorithms, flowcharts, and key programming concepts. It explains the features, advantages, and disadvantages of Python, along with installation instructions and basic programming examples. Additionally, it discusses Python tokens, data types, expressions, and includes practical exercises for beginners.
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)
2 views10 pages

NOTES_Introduction to Python

The document provides an introduction to Python, covering algorithms, flowcharts, and key programming concepts. It explains the features, advantages, and disadvantages of Python, along with installation instructions and basic programming examples. Additionally, it discusses Python tokens, data types, expressions, and includes practical exercises for beginners.
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/ 10

Introduction to Python

What is an Algorithm?
An algorithm is a step-by-step procedure or set of rules to be followed for solving a problem or
performing a task. In programming, it is the logic written in plain language before coding begins.
Features:
●​ Finite: Has a definite start and end.
●​ Unambiguous: Every step must be clear.
●​ Input/output: Takes input(s), produces output(s).
●​ Effective: Each instruction is basic enough to be understood.
Example: Algorithm for Adding Two Numbers
1.​ Start
2.​ Input two numbers (a, b)
3.​ Set sum = a + b
4.​ Output sum
5.​ Stop
Extra Questions:
●​ What happens if instructions are ambiguous?
●​ How are algorithms evaluated for efficiency?
2. Flowchart
What is a Flowchart?
A flowchart is a diagrammatic representation of an algorithm or process. It uses standard
symbols to show the flow of execution.
Flowchart Symbols and Elements
Symbol Name Description

Ovals Start/Stop Drawn at the beginning/end, marks entry/exit point

Parallelogram Input/Output Denotes input (read) or output (print) operations

Rectangle Process An instruction or action (e.g., calculation,


assignment)

Diamond Decision Branches flow depending on conditions (e.g., if/else)

Arrow lines Flow Lines Show direction/order of operations

Circle Connector Connects parts of a flowchart separated by space

Example: Flowchart to Find Greater of Two Numbers


1.​ Start (Oval)
2.​ Input a, b (Parallelogram)
3.​ Is a > b? (Diamond)
○​ Yes: Output "a is greater" (Parallelogram)
○​ No: Output "b is greater" (Parallelogram)
4.​ Stop (Oval)
Common Flowchart Elements Illustration:
Extra Questions:
●​ Which symbol would you use for an assignment statement?
●​ How does a flowchart help in debugging?​

3. Differences: Algorithm vs Flowchart


Feature Algorithm Flowchart

Format Written (text/step list) Visual (symbols and arrows)

Understanding Requires logical reading Easier, visual learners can see step order

Use Good for logical breakdown Good for identifying process errors

Reusability Highly reusable as Reusable but edits may require redrawing


pseudocode

Debugging Difficult for complex steps Mistakes easily seen in process branches

Discuss:
●​ When would you prefer an algorithm over a flowchart?
●​ Can a process have both? Why?
4. About Python
●​ Developed by Guido van Rossum in 1990, named after "Monty Python's Flying Circus".
●​ High-level, portable, platform-independent, interpreted language.
●​ Uses indentation to define code blocks.
●​ Simple syntax; fewer lines to accomplish tasks compared to other languages.
●​ Free and open source.
Features
●​ Case-sensitive.
●​ Large standard libraries.
●​ Used in AI, web development, data science, scientific computing, etc.
Advantages
●​ Beginner-friendly.
●​ Embeddable in C/C++.
●​ Free and open-source.
●​ Interpreted, no compilation needed.
Disadvantages
●​ Slower execution speed.
●​ High memory consumption.
●​ Weak in mobile computing.
●​ Primitive database access.
●​ Potential runtime errors due to dynamic typing.
5. Downloading and Installing Python
●​ Download from https://www.python.org/downloads/
●​ Install and follow on-screen instructions.
●​ Confirm successful installation by running Python interactive shell.
6. Working with Python
Modes
●​ Command Line (Interactive Mode): For short commands; outputs shown instantly but
code not saved.
●​ IDLE (Integrated Development Environment): For writing, saving, editing, and running
longer programs.
Starting Python Command Line
1.​ Start → Python 3.x → Python (64-bit).
2.​ Prompt >>> appears
3.​ Example:
python
>>> print("This is my first program")
This is my first program
>>> print(40+34)
74

Exiting command line


●​ Press Ctrl+Z + Enter
●​ Or type quit() or exit()
7. Python IDLE
●​ Provides Editor window and Shell.
●​ Save scripts with .py extension.
●​ Run scripts using Run → Run Module (F5).
Practical: Writing a multi-line program in IDLE
python
print("I am working in Python 3.11 version")
print("I am working in Python IDLE")
print("Python is an interpreted language")

8. Python Tokens
●​ Smallest units in Python source code.
●​ Types:
○​ Keywords (e.g., if, else, while)
○​ Identifiers (variable/function names)
○​ Literals (data values: string, numeric, boolean)
○​ Operators (+, -, *, etc.)
○​ Punctuators (symbols like commas, parentheses)
9. Python Operators
Type Operators Example

Arithmetic +, -, *, /, //, %, ** x + y, x // y

Compariso >, <, ==, !=, >=, <= x>y


n
Logical and, or, not x and y

Assignment =, +=, -=, *=, /= x += 1

10. Data Types and Type Conversion


●​ Common types: int, float, string, boolean.
●​ Implicit conversion: done automatically (e.g., int + float = float).
●​ Explicit conversion (type casting):
python
a = "10010"
b = int(a, 2) # Convert binary string to integer
print(b) # Output: 18

d = float(a)
print(d) # Output: 10010.0

11. Statements and Expressions


●​ Statement: An instruction executed by Python (e.g., assignment, print).
●​ Expression: Combination of values and operators producing a value.
Example:
python
x = 18 + 2.3 # Constant expression
print(x) # Output: 20.3

12. Python Comments


●​ Single-line: starts with #
●​ Multi-line: enclosed in triple quotes
python
# This is a single-line comment

"""
This is a
multi-line comment
"""
13. Indentation in Python
●​ Indentation defines blocks of code.
●​ Incorrect indentation causes errors.
●​ Example:
python
name = "Sam"
if name == "Sam":
print("Hello Sam")
else:
print("Hello dude")
print("How are you?")
14. Input and Output
Input
python
name = input("Enter your name: ")
print("Hello", name)

●​ Inputs are strings by default; convert to int/float for calculations:​

python
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
print("Sum:", num1 + num2)

Output using print()


●​ Syntax: print(value1, value2, sep=' ', end='\n')​

"Let's Exercise" Section – Fully Solved


A. Choose the Correct Answer
1.​ __________ is both an interpreted language and dynamically typed language.
○​ (a) Python
2.​ ________ in Python is easy and hassle-free.
○​ (a) Programming
3.​ _______ are words that have certain/special meaning in a language.
○​ (c) Keywords
4.​ A token is the ______ entity in a Python program.
○​ (c) Smallest
5.​ The ______ nature of Python is responsible for Python's slow speed.
○​ (b) Dynamic
B. Fill in the Blanks
1.​ Running code line by line often results in slow execution.
2.​ Python is not used for purposes where speed is important.
3.​ Python programming consumes a lot of memory.
4.​ Python is commonly used in server-side programming.
5.​ Literals are the fixed values or data items used in a source code.
6.​ A statement is an instruction that a Python interpreter can execute.
7.​ The Python statement ends with the token character NEWLINE.
C. Short Answer Type Questions
1.​ Write any one feature of Python.
○​ Python is a high-level, platform-independent language that's easy to learn.
2.​ Write the code to print the output "Hello World".
print("Hello World")
3.​ Why is Python a slow language?
○​ It is interpreted and dynamically typed, making its code run slower than compiled
languages.
4.​ What are Identifiers in Python?
○​ Identifiers are names given to variables, functions or classes; e.g., age,
sumValue.
5.​ What is Float Literal?
○​ A float literal is a number that has a fractional part, like 3.14 or -2.0.
6.​ What are Relational Expressions?
○​ Expressions comparing two values using operators like >, <, ==. Output is
Boolean.
7.​ What are Floating Expressions?
○​ Expressions that result in a float (decimal) value, e.g., a / b when a and b are
integers
8.​ How to Take Input from User in Python?
○​ Use input() function, e.g., name = input("Enter your name: ")

D. Long Answer Questions – Detailed Answers


1. Advantages and Disadvantages of Python
Advantages of Python
●​ Beginner-friendly: Python’s simple and readable syntax makes it easy for beginners to
learn and write code. For instance, printing a message or performing calculations
requires very few lines, making it suitable for students and non-programmers.​

●​ Versatile: Python is used in diverse domains including web development, data science,
artificial intelligence, automation, scientific computing, and more. This flexibility allows a
Python developer to work in various industries.​

●​ Large Library Support: Python includes a vast standard library and third-party
packages (like NumPy for math, Pandas for data analysis, Flask for web apps), reducing
the need to write code from scratch.​

●​ Open Source: Python is freely available to download and use. Its source code is
accessible, and a supportive global community actively contributes to its improvement.​

Disadvantages of Python
●​ Slower Execution Speed: Python is an interpreted and dynamically typed language,
which means it runs code line-by-line at runtime. This can make Python code slower
compared to compiled languages like C or C++.​

●​ High Memory Consumption: Python’s data structures and memory management can
use more RAM than other languages, making it less optimal for memory-intensive
applications.​

●​ Weak in Mobile Computing: While Python excels in server-side and desktop


applications, it is rarely used for mobile apps due to limited mobile development
frameworks and suboptimal performance.​

●​ Primitive Database Support: Python’s standard solutions for database connectivity


(like SQLite, sqlite3) are not as advanced as dedicated database connectors in Java
(JDBC) or C# (ADO.NET), making complex enterprise database integration challenging.​
2. What are Python Tokens?
Definition:​
Python tokens are the smallest units of a Python program. Every statement or instruction is
made up of various tokens. Python recognizes the following types:
●​ Keywords: Reserved words with special meaning (e.g., if, for, while, True, None).
They cannot be used as variable names.​

●​ Identifiers: User-defined names for variables, functions, and classes. E.g.,


student_name, total_marks. They must follow naming conventions (cannot begin
with a number or use special characters besides _).​

●​ Literals: Fixed values in a program, such as numbers, strings, and boolean values. E.g.,
234, 'Python', True.​

●​ Operators: Symbols used to perform operations. E.g., +, -, *, /, ==, and.


●​ Punctuators: Characters that organize code structure, such as (), [], {}, :, ,, ..​

3. Describe the Data Types in Python


Python provides various data types to store and manipulate different kinds of data:
Data Example Description Practical Use
Type

int a = 5 Integer values (whole Counting books, ages,


numbers, no decimals) IDs

float b = 5.2 Floating-point numbers Scientific calculations,


(with decimals) averages

str c = "Hello" Strings (sequence of Names, messages, text


characters in quotes) data

bool d = True Boolean (True or False) Condition checking,


logic switches

list `e = [1, 2, Ordered, Shopping cart, marks, IDs


mutable collection of items

tuple f = (1, 2, 3) Ordered, immutable Coordinates, fixed


collection of items configurations

dict g = {'a': 1} Unordered collection of Contact info, settings


key-value pairs

set h = {1, 2, 3} Unordered, unique Unique student IDs,


collection of elements tags

Conversion Examples:
●​ x = int('7') converts the string '7' to integer 7.
●​ y = float('2.5') converts the string '2.5' to float 2.5.
●​ z = str(10) converts the integer 10 into the string '10'.
4. Describe the Expressions in Python
An expression in Python is a combination of values, variables, operators, and function calls
which, when executed, is evaluated to a single value.
Types of Expressions:
●​ Constant Expressions: Only constants, e.g., 4 + 6
●​ Arithmetic Expressions: Combination of numeric values and arithmetic operators, e.g.,
a + b * c
●​ Relational Expressions: Compare values, resulting in True/False, e.g., a > b, b != c
●​ Logical Expressions: Combine or invert boolean expressions using and, or, not, e.g.,
a > b and b < c
●​ Combinational Expressions: Expressions that combine other types, e.g., a + (b >
c)
Example:
python
x = 18 + 2.3 # Arithmetic expression; result: 20.3 (float)
flag = (x > 10 and x < 30) # Logical expression; result: True

5. What are Arithmetic Expressions?


Definition:​
Arithmetic expressions in Python are expressions that perform basic mathematical calculations
using arithmetic operators. The primary operators are:
Operator Meaning Example Result

+ Addition 5+4 9

- Subtraction 9-3 6

* Multiplication 5*3 15

/ Division 10 / 2 5.0

// Floor Division 10 // 3 3

% Modulus 10 % 3 1

** Exponentiation 2 ** 3 8
Sample Code:
python
a = 5
b = 3
add = a + b # 8
sub = a - b # 2
mul = a * b # 15
div = a / b # 1.666...
mod = a % b # 2
exp = a ** b # 125

Extra Sample Exercise/Lab Questions (with Solutions)


1.​ Display the name of five students along with their marks.​

for i in range(5):
name = input("Enter student name: ")
marks = input("Enter marks: ")
print(name, "has marks", marks)

2.​ Calculate the area of a triangle (given base and height).​


base = float(input("Enter base: "))


height = float(input("Enter height: "))
area = 0.5 * base * height
print("Area of triangle:", area)

3.​ Calculate simple interest.​

P = float(input("Principal: "))
R = float(input("Rate: "))
T = float(input("Time (years): "))
SI = (P * R * T) / 100
print("Simple Interest:", SI)

4.​ Calculate area of a circle.​

radius = float(input("Enter radius: "))


area = 3.1416 * radius * radius
print("Area of Circle:", area)

You might also like