Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python q

The document provides an overview of Python programming, covering its dynamic nature, variables, data types, operators, and control statements. It details various data types including single and multi-value types, and explains how to use operators for arithmetic, logical, and relational operations. Additionally, it discusses control statements such as conditional and looping structures, along with built-in functions like print and input.

Uploaded by

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

Python q

The document provides an overview of Python programming, covering its dynamic nature, variables, data types, operators, and control statements. It details various data types including single and multi-value types, and explains how to use operators for arithmetic, logical, and relational operations. Additionally, it discusses control statements such as conditional and looping structures, along with built-in functions like print and input.

Uploaded by

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

Python

Python is a dynamic language because you don’t have to declare data type while
assigning a value.

Features of Python

Variables and Values

Variable: It is a name given to a value.

Value: These are the data stored inside the variable (placeholder).

a = 10
a = ’Hello’

Identifier and Keywords

Identifiers: These are some rules and regulations which are followed to name a variable.

Rule 1: It can be alphabet, alphanumeric but it should not start with numbers.

a = 10

a1 = 10

1a = 10

Rule 2: It should not be a special character except underscore.

@ = 10

# = 10

! = 10

_ = 10

Rule 3: You can’t leave space between variables.

ab = 10

a b = 10

Rule 4: It should not be a keyword.

Keywords

These are some predefined words having some specific tasks to do.

1. Keywords are immutable in nature.

Example: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

2. We have 35 keywords in which we have 3 special keywords: True, False and


None
3. Soft keywords: ‘_’, ‘case’, ‘match’, ‘type’

Feb 20, 2025


Data Types

Datatypes are used to specify the type of data stored inside a variable

We have two types of data types:

1. Single value data type: int, float, complex, bool


2. Multi value data type: string, list, tuple, set, dictionary

Single valued data type: These are the data which are stored individually inside a
variable in the form of integer, float, complex, Boolean.

Integer: The numbers which can be represented on a number line in the form of
negative, positive and zero.

Memory diagram for integers

Variable space Value Space

a 0x11

0x11 10

Feb 21, 2025

Float: Decimal values

Example: Temperature, Weight, Height

String: A string is a sequence of characters. Python treats anything inside quotes as a


string. This includes letters, numbers, and symbols.

P Y T H O N

0 1 2 3 4 5

Indexing: It’s a phenomenon of giving sub-address to a given address

We have two types of indexing:

1. Positive indexing: 0, 1, 2… infinity/n-1


2. Negative indexing: -1, -2…. -infinity

Slicing: It’s a phenomenon of extracting the sub data from a given data using indexing.
We have two types of slicing:

1. Individual Slicing
2. Group Slicing

Individual Slicing: It’s a phenomenon where we extract sub data individually.

Syntax: var[index_position]

a = ‘python’

a[2] = t

Group Slicing: It’s a phenomenon where we extract sub data in groups.

[start:stop:step]

Empty String: Single, double and triple quotes.

Note: String is immutable in nature.

Feb 24, 2025

List: It is a collection of homogenous, heterogeneous data stored in [].

Homogenous - same kind

Heterogenous - different kind

List is mutable in nature where we can add data, insert data or remove data from the
list.

1. append() – It is a function which is used to add data to the last of the collection.

syntax: var.append(value)

2. insert() – It is an inbuilt function which is used to add data as per user index
position.

syntax: var.insert( index position, value)

3. pop() – It is used to remove data


4. default value – []

Memory diagram for List


a = [10, ‘hello’, 3+5j, [1, 2, ‘hello’], ‘python’, [1, ‘star’]]

10 0x11 3+5j 0x22 0x33 0x44

Tuple: It is a collection of homogenous, heterogeneous data stored in ().

1. Immutable in nature where we can access the data but can’t modify it.
2. In python, tuple is the most secure data type which has security.
3. We use tuples for security purposes.

Feb 25, 2025

Set: Set is a unorganised type of data stored in {}

Var space Value space

a 0x11

0x11 ‘Hello’, ‘str’, 10, 5.3

1. Due to unorganised structure indexing is not possible


2. We use set for filtration - to avoid duplicate values

a={1,12,2,1,2,1,2,1,2,1,12} → {1, 2, 12}

3. Set is mutable in nature but accepts only immutable values.


4. add() - add value in a set.

Syntax: var.add()

5. remove() - remove value in a set.

Syntax: var.remove()

6. Default Value: set()

Dictionary: It is a data type where data is in the form of Keys & Values where keys are
immutable and values are mutable.

{K:V, K1:V1,....Kn:Vn}

Where, K = Key & V = Value

1. Dictionaries are mutable in nature.


2. Default value: {}
3. We have three inbuilt function in dictionary

var.keys()

var.values()

var.items()

Data Type Example Default Value


int x = int() 0
float x = float() 0.0
complex x = complex() 0j
bool x = bool() False
str x = str() "" (empty string)
list x = list() [] (empty list)
tuple x = tuple() () (empty tuple)
set x = set() set() (empty set)
dict x = dict() {} (empty dictionary)
bytes x = bytes() b'' (empty bytes)
bytearray x = bytearray() bytearray(b'') (empty bytearray)
NoneType x = None None

Operators: These are some symbols which have some specific meaning to work on
operands to do an operation effectively, efficiently or precisely.

In python, we have 7 types of operators:

1. Arithmetic Operators
2. Logical Operators
3. Relational Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators

Arithmetic Operators: These are all mathematical operators to do an operation.


Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2*3=6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16

Relational Operator: These are some comparison operators where you compare the
operands and get the output in the form of true or false.

Operato Meaning Example


r

== Is Equal To 3 == 5 gives us
False

!= Not Equal To 3 != 5 gives us


True

> Greater Than 3 > 5 gives us


False

< Less Than 3 < 5 gives us


True

>= Greater Than or 3 >= 5 give us


Equal To False
<= Less Than or 3 <= 5 gives us
Equal To True

Logical Operators: These are some comparison operators where we compare data
using gates.

(AND, OR, XOR, NOT)

Operato Exampl Meaning


r e

and (&) a and b Logical AND:


True only if both the operands are True

or (|) a or b Logical OR:


True if at least one of the operands is True

not (~) not a Logical NOT:


True if the operand is False and vice-versa.

xor (^) a xor b Logical XOR:


True if conditions are opposite, otherwise
False.

Feb 27, 2025

Bitwise Operator: This operator is used to compare the data using binary methods and
give you output in the form of numbers.

10 9 8 7 6 5 4 3 2 1 0

2 2 2 2 2 2 2 2 2 2 2

1024 512 256 128 64 32 16 8 4 2 1


Rules to solve bitwise:

1. Find the bin of both numbers.


2. Solve the bin with respective truth tables.
3. Put the power of 2 at one (1) place.
4. Sum it and calculate it.

Right Shift: Shift two places in the unit place to the right.

Left Shift: Shifts the bits of the number to the right and fills 0 on voids left.

Feb 28, 2025

Assignment Operator: These are the operators where we solve the operands by
having some operators, in the presence of equals to(=).

Operator Name Example

= Assignment Operator a=7

+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

*= Multiplication Assignment a *= 4 # a = a * 4

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10

Membership Operator: In this operator we check whether a sub-data belongs to data


or not, we use ‘in’ and ‘not in’ operator and get the output in the form of True/False.

Operato Meaning Example


r

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the 5 not in x


sequence
Identity Operator: In this operator we check the data belonging to each other with their
respective ‘ID’, we use ‘is’ and ‘not is’ operator and get the output in the form of
True/False.

Operato Meaning Example


r

is True if the operands are identical (refer to the x is True


same object)

is not True if the operands are not identical (do not x is not
refer to the same object) True

TypeCasting: It’s a phenomenon of converting one data type into another data type.

Syntax: var1=value

var1=data(var)

print(a)

Int Float Complex Bool String List Tuple Set Dict

Int ✓ ✓ ✓ ✓ ✘ ✘ ✘ ✘ ✘

Float ✓ ✓ ✓ ✓ ✘ ✘ ✘ ✘ ✘

Complex ✘ ✘ ✓ ✓ ✘ ✘ ✘ ✘ ✘

Bool ✓ ✓ ✓ ✓ ✘ ✘ ✘ ✘ ✘

String ✘ ✘ ✘ ✓ ✘ ✓ ✓ ✓ ✘

List ✘ ✘ ✘ ✓ ✘ ✓ ✓ ✓ ✘

Tuple ✘ ✘ ✘ ✓ ✘ ✓ ✓ ✓ ✘

Set ✘ ✘ ✘ ✓ ✘ ✓ ✓ ✓ ✘

Dict ✘ ✘ ✘ ✓ ✘ ✓ ✓ ✓ ✓
Mar 3, 2025

Print Function: Print is an inbuilt function which is used to get the input in the terminal
which is given by the user.

Input Function: Input is an inbuilt function which is used to take input or messages
from the user.

By default the nature of input is string.

Syntax: input(‘message’)

eval(): It is an inbuilt function which is used to evaluate or validate every data type with
respective symbols.

Mar 4, 2025

Control statement: It is a phenomenon where we control the operation by providing


some set of instructions to run the operation.

We have two types of control statement:

1. Conditional / Decisional
2. Looping

Conditional/Decisional: It’s a type of control statement where we provide some


condition for our situation to make an operation using if, else, elif, nestedif.

If: It is a condition where you deal with a true body statement or true condition for your
operation.

Syntax:

if condition:

TBS(True Body Statement)


isinstance(value, datatype)

Else: It is a conditional statement where you give a false statement for a true condition.

*In else we don’t mention conditions, we mention false statements.

If condition:

TBS(True Body Statement)

else:

FBS(False Body Statement)

Mar 5, 2025

elif: It is a conditional statement where we have ‘n’ number of true conditions for a
single operation.

Here, every true condition is interlinked to each other where if the first condition gets
true that will not go to the second condition.
We can use ‘n’ number of elif for a single operation where else is the optional.

Mar 6, 2025

Nested if: It is a type of conditional statement where we have a condition inside a


condition in which if the first condition is satisfied then only it will go for the second
condition.

In this condition, every if has an else part.

Looping: It is a control statement where we do the same set of instructions again and
again until and unless the condition becomes false.

We use looping to avoid the same set of instructions, to reduce the code size to
increase the efficiency.

We have two types of looping

1. While loop
2. For loop

While loop: It’s a looping statement where we have the same set of instructions again
and again until and unless conditions become false.

In the while loop we follow some loop:

1. To run a while loop we have to initialize the starting point.


2. Using while we give the stop point for the operation.
3. Write logic inside the body.
4. To run the loop we use updation in the form of increment, decrement.

Syntax:

Initialization (i)

While condition:

Logic

Updation(Inc/Dec)

Mar 11, 2025

Count: It is an inbuilt function which is used to calculate the substrings from the given
string
Syntax: var.count('substring')

Split: It is an inbuilt function which is used to convert a string into a list.

Syntax: car.split()

Mar 12, 2025

ASCII: American Standard Code for Information Interchange

These are some standards which are followed by the computers where we give a
number to a value which is accepted universally.

Chr: It is an inbuilt function which is used to get the character with respective ascii
number.

Syntax: chr(no.)

chr(65) -> ‘A’

Ord: We use order when we know the character but don’t know the number.

Syntax: ord(chr)

ord(‘a’) -> 97

chr(ord(‘a’)-32)-> A

Mar 24, 2025

Perfect number: It is a number which are sum of their factors except itself

Ex: 6

For Loop: Same set of instructions again and again until and unless the condition
becomes false. But it depends on the collection.

Syntax: for i in collection:

Collection: range(), str, list, tuple, set, dict

range(): It is a function where we set a limit as per lower, upper value.

Syntax: range (Start, End, Step)

In For Loop, we don’t have to initialize, updation to run the loop, it will automatically take
as per collection
In For Loop, whenever we’re dealing with indexing we use range function

Mar 28, 2025

While Loop For Loop

Infinite Loop Finite Loop

Starts with initialization and run up to Depends on collection


updation

Sufficient More Sufficient

We can’t solve set and dict due to Any collection because we take variable
initialization

Intermediate Termination Loop: These are the loop terminators where we cut the
running loop as per user request.

To cut the loop, we use keywords like break, continue, pass

Break: It is a keyword which is used to terminate the following loop at the given
condition or request.

Here, we exits the running loop using syntax: break

Apr 2, 2025

Functions: It is a block of code where we store a set of instructions as per our


requirement and they are callable when we call it.

Functions are used to reduce the code size by avoiding repetition codes where we
increase the efficiency, durability of the operation.

In python, we have two types of functions:

1. Inbuilt
2. User defined

Inbuilt Function: These are some predefined functions which have some specific task
to do. We don’t have to write code for it.

Unitary Function: These are some common inbuilt functions which are used for every
data type.
Example: print(), input(), eval(), id(), type(), bool()

Str: upper, lower, split(),

List: append(), input(), pop()

Tuple: index(), count()

Set: add(), remove()

Dict: .items, .values, .keys

User-Defined Function: These are functions which are created with the user
requirement.

To create a user defined function we have to use the ‘def’ keyword.

Def: It is a keyword which is used to create a user defined function.

Function Name: It is a name given to a function while creating a function.

Argument: These are some parameters passed while creating a function.

Return: It is a keyword which controls the flow of execution by assigning some values.

Calling Function: These are some functions which are created.

We have 4 types of user-defined functions:

1. Without Argument without return value


2. With Argument without return value
3. Without Argument with return value
4. With Argument with return value

A✗ R✗
A✓ R✗

A✗ R✓

A✓ R✓

Main Space Method Space

ex_upper() 0x11
0x11 Block of Code

Q1. Replace all the uppercase letters in a given string with a *

Q2. Write a function to extract all digits from given string

Q3. WAP to remove all uppercase letters from given string

Apr 7, 2025

JOIN Function: It is a function which is used to join the collection or a substring to the
collection to form a single string.

Syntax: ‘glue str’.join(var)

Without Argument with return value:

Syntax:

Def f_name():

Return v1, v2….

print(f_name())

Note:

1. In these types of functions we have to pass return while calling the function.
2. We use return in the operation to control the flow of execution of the function.

Apr 9, 2025

Anagram: These are the words whose length and alphabets are the same.
Ex: Silent = Listen

Apr 14, 2025

Recursion with Looping

Rules:

1. In this function we have to initialize all the variables in a single formal argument.
2. Create a termination code which is opposite to the looping condition using if and
store the output using return.
3. Write a logic as per requirement.
4. To update the loop or function we have to update in a single actual argument.

You might also like