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

Ch3 - Python Notes

This document provides a comprehensive overview of Python, including its history, features, advantages, limitations, and applications. It covers essential concepts such as data types, operators, functions, conditional statements, and loops, along with examples for clarity. The document serves as a foundational guide for beginners to understand and work with Python programming.

Uploaded by

dharshanr2023
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 views17 pages

Ch3 - Python Notes

This document provides a comprehensive overview of Python, including its history, features, advantages, limitations, and applications. It covers essential concepts such as data types, operators, functions, conditional statements, and loops, along with examples for clarity. The document serves as a foundational guide for beginners to understand and work with Python programming.

Uploaded by

dharshanr2023
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

Tab 1

Chapter 3: Brief Overview of Python 13/05/25

1. Introduction to Python

●​ Creator: Guido Van Rossum


●​ Year of Release: 1991
●​ Developed at: CWI (Centrum Wiskunde & Informatica), Netherlands
●​ Name Origin: From BBC comedy series "Monty Python's Flying Circus"

Parent Languages:

●​ ABC
●​ Modula-3

Applications of Python:

●​ Software Development
●​ Web Development
●​ Scientific Computing
●​ Big Data
●​ Artificial Intelligence (AI)

2. Features of Python

1.​ General-purpose: Used for both scientific and non-scientific applications.​

2.​ Platform Independent: Runs on Windows, Linux, Mac, etc.​

3.​ Simple & High-level: Easy to read and understand.​

4.​ Interpreted Language: Executes line-by-line, helpful for beginners.​

5.​ Readable Code: Uses English-like syntax.​

6.​ Extensible: Can be used to enhance other applications.​

7.​ Easy to Learn: Beginner-friendly.​

8.​ Case Sensitive: Python, PYTHON, and python are treated as different.

3. Advantages of Python
Advantage Explanation
Easy to Use Simple syntax, object-oriented and compact

Expressive Language Short code with high readability

Interpreted Language Code runs line-by-line; easy to debug

Rich Library Support Built-in modules for web, email, GUI, etc.

Cross-Platform Works on multiple OS platforms

Free and Open Source Available at no cost; source code modifiable

Versatile Usage Useful in scripting, games, system admin,


etc.

4. Limitations of Python

1.​ Slower Execution: Interpreted, not fully compiled.​

2.​ Fewer Libraries: Compared to C, Java, etc.​

3.​ Weak in Type Binding: Less strict with data types.​

4.​ Not Easily Convertible: Syntax differs from other languages.​

5. Working in Python

To run Python, install the Python interpreter and use IDLE (Integrated Development and
Learning Environment).

Two Modes to Work in Python:

A. Interactive Mode
●​ Directly type and run commands.

●​ Prompt: >>> (ready for input), ... (waiting for continuation)​

●​ Best for small programs or testing.​

●​ Use # for comments.​

●​ Useful Commands:​

○​ help() – Opens help​


○​ help(print) – Help for specific function​

○​ credits, license(), copyright​

○​ quit() or Ctrl+D – Exit​

○​ Ctrl+F6 – Restart shell​

B. Script Mode

●​ For writing and saving longer programs.​

●​ Steps in IDLE:​

1.​ File → New Window​

2.​ Type code​

3.​ Save file (Ctrl+S)​

4.​ Run code (F5 or Run → Run Module)​

6. print() Function

●​ Used to display output​

●​ Syntax: print(<object(s)>)​

Examples:​
print("Hello World")
print('Python is Fun')

7. Python Character Set

Python uses a set of characters including:

●​ Letters: A–Z, a–z​

●​ Digits: 0–9​

●​ Special Symbols: +, -, *, /, @, etc.​

●​ Whitespace: space, tab, newline​


●​ Other Characters: Used in strings, identifiers, etc.​

8. Python Tokens

A Token is the smallest unit in a program (also called a lexical unit).

Types of Tokens:

1.​ Keywords​

○​ Predefined words with special meaning.​

○​ Cannot be used as variable names.​

○​ Examples:​
if, else, while, for, True, False, def, return, import, in, etc.​

2.​ Identifiers​

○​ Names used for variables, functions, classes, etc.​

○​ Rules:​

■​ Must start with a letter (A-Z/a-z) or underscore _​

■​ Can contain letters, digits, and underscore​

■​ Cannot begin with a digit​

■​ Keywords cannot be used​

■​ Case sensitive (total, Total, TOTAL are different)​

■​ Should be meaningful and short​

3.​ Literals​

○​ Constant values are assigned to variables.​

○​ Types:​

■​ String literals ("hello", 'world')​

■​ Numeric literals (10, 3.14)​


■​ Boolean literals (True, False)​

■​ None literal (None)​

4.​ Operators​

○​ Symbols used for calculations or comparisons.​

○​ Examples:​

■​ Arithmetic: +, -, *, /​

■​ Comparison: ==, !=, <, >​

■​ Logical: and, or, not​

5.​ Punctuators (Delimiters)​

○​ Symbols that organize code.​

○​ Examples:​
(), {}, [], :, ,, ;, @, =, ->

6. Variable

●​ A variable is a name that refers to a value.​

●​ It stores data that can change during the execution of a program.​

●​ A variable is also called an identifier.​

●​ It must follow identifier naming rules (no spaces, must start with a letter or underscore,
etc.).​

🔹 Creating Variables
Variables are created by assigning a value to a name.

age = 20 # Integer variable

average = 95.6 # Float variable

name = "CBSE" # String variable

Note: A variable is created only when a value is assigned


🔹 Multiple Assignments
1.​ Same value to multiple variables:​

a = b = c = 18

2.​ Different values to different variables:​

x, y, z = 10, 20, 30 # x=10, y=20, z=30

Data Types:

a.​ Number:
int:
Ex: age = 10
float:
Ex: per = 95.8
complex:
Ex: a = 3 + 4i

b.​ Sequence:
String:
Ex: str1 = “Hello”
str2 = “37”
str3 = ‘Python’
List: Uses square brackets. It is mutable (can change items)
Ex: #To create a list
list1 = [1, “Amal”, “M”, “11B”,“Fujairah”]
Tuple: Uses Parenthesis. It is immutable (cannot change items)
Ex: #To create a tuple
tuple1 = (1, “Amal”, “M”, “11B”,“Fujairah”)
a.​ Mapping:
Dictionary: key-value pairs separated by commas and enclosed in curly brackets { }
Ex:
dict1 = {“Alice”: 20, “Bob” : 23, “Christy” : 25}

Operators:

1.​ Arithmetic operators:

Operator Meaning Example Result

+ Addition 5 + 3 8

- Subtraction 5 - 2 3

* Multiplication 4 * 2 8

/ Division 10 / 2 5.0

// Floor Division 10 // 3 3

% Modulus 10 % 3 1

** Exponentiation 2 ** 3 8

PT1 topic ends.


2.​ Relational/Comparison Operators
Relational operators compare the values of the operands on either side and determine their
relationship. Here are examples using the variables `num1 = 10`, `num2 = 0`, `num3 = 10`, `str1
= "Good"`, and `str2 = "Afternoon"`:

Operator Meaning Example

== Equal to 5 == 5 → True

!= Not equal to 4 != 5 → True

> Greater than 6 > 3 → True

< Less than 2 < 5 → True

>= Greater or equal 5 >= 5 → True

<= Less or equal 4 <= 6 → True

3.​ Logical Operators


Python supports three logical operators: `and`, `or`, and `not`, which must be written in
lowercase. Based on the logical operands on either side, these operators evaluate to `True` or
`False`.

Operator Meaning Example

and Both True 5 > 2 and 4 < 6 → True

or At least one True 5 > 2 or 4 > 6 → True

not Reverse value not(5 > 2) → False

4.​ Assignment Operators


Assignment operators are used to assign or change the value of a variable.

Operator Meaning Example

= Assign x = 5

+= Add and assign x += 3 → x = x + 3

-= Subtract and assign x -= 2

*= Multiply and assign x *= 4

5.​ Membership Operators

Used to check if a value exists in a sequence (like a list, string, etc.).

in – Returns True if the value is found.​



numSeq = [1, 2, 3]
2 in numSeq # True
'1' in numSeq # False (string vs number)

not in – Returns True if the value is not found.​




10 not in numSeq # True
1 not in numSeq # False

Expressions

An expression combines values, variables, and operators to produce a result.

Examples:
num - 20.4
23 / 3 - 5 * (14 - 2)
"Global" + "Citizen"

Operator Precedence

Precedence decides which operator runs first in a complex expression.

Important Rules:

●​ Parentheses () run first.​

●​ Then follow operator rules (e.g., * before +).​

●​ Left to right for same-level operators.​

Examples:

1.​ 20 + 30 * 40​
→ 30 * 40 = 1200, then 20 + 1200 = 1220​

2.​ (20 + 30) * 40​


→ 50 * 40 = 2000​

3.​ 15.0 / 4.0 + (8 + 3.0)​


→ 3.75 + 11.0 = 14.75​

input() in Python

The input() function takes user input from the keyboard. All input is treated as a string, even
if the user types a number.

How it works:

●​ It shows a message (optional) and waits for the user to type something.​

●​ It always returns the input as a string.​

Example 1:

name = input("Enter your name: ")


print("Hello", name)
Example 2 (convert input to number):
age = int(input("Enter your age: "))
print(age + 5)

Use int() for integers and float() for decimals.

Debugging in Python
Debugging is finding and fixing errors in a program to ensure it runs correctly and gives the right
output.

Errors in a program can:

●​ Stop it from running​

●​ Or make it produce the wrong result​

Types of Errors

Python programs may contain the following three types of errors:

1. Syntax Errors

●​ Happens when the code breaks Python’s grammar rules.​

●​ The program will not run until the error is fixed.​

●​ Example: Missing a parenthesis​

print("Hello" # ❌ Syntax Error

2. Logical Errors (Semantic Errors)


●​ The program runs without crashing, but gives the wrong output.​

●​ These errors are hard to detect because the program seems fine.​

●​ Example: Wrong formula for average​

average = 10 + 12 / 2 # ❌ Wrong logic


# Correct: (10 + 12) / 2

3. Runtime Errors

●​ Happens while the program is running.​

●​ The syntax is correct, but the program crashes due to an invalid operation.​

●​ Example: Dividing by zero​

x = 5 / 0 # ❌ Runtime Error: Division by zero

Function
A function is a block of code that performs a specific task.​
It helps in code reusability and modular programming.

Types of Functions

1.​ Built-in Functions – Already available in Python (e.g., print(), len(), sum())​

2.​ User-defined Functions – Created by the programmer using def

Syntax of a Function

def function_name(parameters):
# code block
return value #The return keyword returns the result from
the function.
Conditional Statements
Conditional statements help us make decisions in a program based on certain conditions.

1. if Statement

The if statement checks a condition. If the condition is True, it runs the code inside it.

🔸 Syntax:
if condition:
# code block

🔸 Example:
age = 18
if age >= 18:
print("You can vote.")

2. if-else Statement

If the condition is True, it runs the if block.​


If the condition is False, it runs the else block.

🔸 Syntax:
if condition:
# code if true
else:
# code if false

🔸 Example:
marks = 40
if marks >= 50:
print("Pass")
else:
print("Fail")

3. if-elif-else Statement

Used when you have multiple conditions to check.

🔸 Syntax:
if condition1:
# block 1
elif condition2:
# block 2
else:
# default block

🔸 Example:
grade = 85
if grade >= 90:
print("A Grade")
elif grade >= 75:
print("B Grade")
elif grade >= 60:
print("C Grade")
else:
print("Fail")

Loops in Python
1. For Loops

●​ Used for iterating over a sequence.​


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry

2. While Loops

●​ Repeats as long as the condition is true.

i = 1
while i <= 5:
print(i)
i += 1
# Output:
# 1
# 2
# 3
# 4
# 5

3. Range Function

●​ Generates a sequence of numbers.​

for i in range(1, 10, 2):


print(i)
# Output:
# 1
# 3
# 5
# 7
# 9

Explanation of range(start, stop, step):

●​ start: where to begin (default 0)​

●​ stop: where to stop (not included)​

●​ Step: How much to increment

***************************************************************************

You might also like