0% found this document useful (0 votes)
4 views29 pages

Programming Python

The document provides a comprehensive overview of Python programming, covering key concepts such as operators, control flow statements, and functions. It details various types of operators including arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators, along with examples. Additionally, it explains control flow statements like conditional statements and loops, and introduces functions with syntax and examples for practical applications.

Uploaded by

nandemail637
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)
4 views29 pages

Programming Python

The document provides a comprehensive overview of Python programming, covering key concepts such as operators, control flow statements, and functions. It details various types of operators including arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators, along with examples. Additionally, it explains control flow statements like conditional statements and loops, and introduces functions with syntax and examples for practical applications.

Uploaded by

nandemail637
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

PYTHON PROGRAMMING

Code: Do not be afraid to commit mistakes learn from it and try not to repeat.
Code Optimization: Reducing the number of lines of code without changing the actual meaning.
Basics
Operators
Operation: it is a task or action performed on value based on the operator used.
Operand: The values on which the operation is performed.
Operators: They are special symbols or keywords, that include pre-defined functionality based on which
the operation performed on operands
Ex: 4*13
Operation - Multiplication
Operand - 4,13
Operator - *
Expression: A statement that perform the operation.
There are totally 7 types of operation in python
1. Arithmetic operators
2. Comparison/Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Membership operators
7. Identity operators.
1. Arithmetic op: Used to perform mathematical operations
=> I/P: numbers (integers and decimal)
=> O/P: numbers (integers and decimal)
=> +, -, *, **[Exponentiation], //, /, %
==> + :
When used with a minimum of 2 operands performs addition.
When used with a single number represent +Ve number

1
Ex:

==> - :
When used with a minimum of 2 operands performs subtraction.
When used with a single number represent -Ve number.
Ex:

==> * :
When used compulsory minimum of 2 operands performs multiplication.
When used with a single operand it represents error.
Ex:

**[exponential];

Syn: base**power
2**3
# exponentiation
Print (3**2)
Print (5**2)

#floor division
Print (12//2) # it does not give a decimal number
Print (22//3) # it does not give a decimal number

2
#float division
Print (10/20)
Print (14/5)
#% modulus division
Print (12%5)
Print (17%8)
# Note print (999%1999)) answer will 999
# Because numerator is less than denominator
Print (999%1999)
It gives a reminder value

2. comparison operator:
- It helps to compare to given 2 val’s
- i/p: ele’s (constant, expression, Boolean values/condition
- o/p: Boolean value
- >, <, >=, <=, ==, !=
True, False, None:
- They are literals
- They are special type of keywords
Literals: means predefined numbers/values
- A. holds predefined value
True= 1
False=0
None=nothing

Examples:
print (2>5)
print ((2*4) <= (2**4))
print (True < (4*7))
print (True==2)
print ((10**0) <=1)
print ((33**True)>=(33**False))
print ((25>= (2**3)) < ((10+5) < (15+5)))

3
[Link] operators:
- I/p: Boolean condition
- o/p: Boolean value or anything that represent Boolean value
- it helps to combine and check multiple Boolean condition
- types: and, or, not

Boolean condition:
- Boolean value
- An expression that returns Boolean value or anything that represent Boolean value
- Constants
Note:
- Any number other than zero is considered as true

AND:
- C1 - C2 - O/P
- TRU - TRU - TRU
E E E
- T - F - F
- F - _ - F

- Print (2>0) and (True<5) and ((2*5) <= (2**4))

- print(10 and True and (10**0))

- print((2+5)and(5 and 10)and(1*(5-5)))

OR:
- C1 - C2 - O/P
- TRU - _ - TRUE
E
- T - F - T
- F - F - F

- print((10+20)or(88-88)or(36**1))

- print((5 and 0)or(3 and-1))

- print(0 and 1 or 5)

- print((5<=-10)or(5<=10))

4
NOT:
C1 C2
T F
F T

- print (not (True and 15))


- print (not ((13*5) or (16+5) and 0))
- print (not (False and True) and(5+3<=True))

4. BITWISE:
- A. &bitwise and
- B. | bitwise or
- C. ~  bitwise not / negation / complement
- D. ^ bitwise xor
- E. <<  bitwise left shift
- F. >> bitwise right shift

5. Assignment operations (=):


a. Storage/ initialization
b. Copying from an initialized vara

Syn1: Storage
Var_name = value
Num = 10
syn2: Copying
#initialized var
Var_name = initialized var_name

n1=100
n2 = n1
VARIABLES:
- it is a container
- it is a named memory location that holds single valued data.
Rules:
- It is compulsory to initialize a variable before utilization
- If the same val is stored into multiple different variables, then internally all the var’s will be
Ponting to same common memory
- When multiple var’s are pointing to the same memory, and out of those if any of one var is tried
to being re-initialized then a separate memory will be provided

5
- If multiple val’s are being stored one after the other into the same variable then it will point to the
latest updated val
- If multiple val’s are being stored together into the same variable then PVM will convert them into
a tuple
Id:
- It is a unique integer representation generated by the PVM during execution time based on the val
stored and memory assigned

Id ():
- It is a pre-defined function that returns the id of the specified argument

2 varieties of assignment operator:


a. Assignment +arithmetic
+=, -=, *=, //=, **=, /=, %=
b. Assignment +bitwise
&=, |=, ^=, <<=, >>=
Rules:
- It is compulsory to use initialized var’s if any
- The operand used on RHS for operation and LHS for updation should be same
- The same operand that is present on the RHS of the operation should be position on the LHS of
the expression
- Minimum of 2 operands is required for an expression to be converted into compound statement,
hence fourth ~= is not supported
Identity operation:
- It compares and checks the id’s of the given 2 operands
- o/p: Boolean value
NOTE:
- the object that can hold multiple individual elements into the same memory location
- ex: strings, list, set, tuple

Membership Operators (in, not in):


- It checks weather the specified elements are available within the group of elements
- It can only be used on iterable objects or group of elements

- s1="Apbal12"
- print("a" in s1)
- print("BAL"in s1)
- print("pba" in s1)
- print("Abl" in s1)
- x="100"
- print("1"in x)
- print("")

6
- print("00" in x)

Control Flow Statements:


- The lines of code that controls the execution flow in the given program
Types:
1. Conditional statement
a. Simple if
b. If else
c. Elif / else if ladder / if-else-if

2. Looping statement
A. For
i. For with range
a. increment
b. decrement
ii. for without range

B. While
i. Increment
ii. Decrement

3. Jumping statement
a. Break
b. Continue
c. Return
[Link] statement:
a. If:
Syntax: if Boolean_condition:
#logic
#return statement
Ex:
num=int(input("enter a number"))
if num %2==0:
print("even")
print(" natural number")

b. If-else:
Syntax: if Boolean_condition:
#logic
Else:
#alternate logic
#remaining statement

Ex:
num1=int(input("enter a num1\n"))
num2=int(input(" enter a num2\n"))
if num1>num2:

7
print(num1,"is greater")
else:
print(num2,"is greater")
print("it is natural number")

c. Elif:
Syntax: if boolean_condition:

If Boolean_condition:
#logic
Elif: condition:
#logic
Elif: condition:
#logic
Else:
# alternative logic
#remaining statement

Ex:
a=input("enter a day hobbie\n")
if (a=="college"):
print("ram is going to college")
elif(a=="sports"):
print("ram going to playing cricket")
elif(a=="agriculture"):
print("ram is doing some work in agriculture field")
else:
print("ram is sleeping")
print("program ended")
2. Looping statement:
 range ():
- It cannot return sequence of values by it’s self
- Hence to access these sequence of values one by one ”for” with range ()”

a. for with range ():


syntax: range (start, stop, step):
#logic

#remaing statement

ex:
range (1, 5, +1)

start:
- from where the sequence should begin
- default start0
stop:
- till where the sequence should get executed
- compulsory value
step:

8
- difference between current and future value
- default step+1
NOTE:
Start, stop/end, step integers

Note: Tracing: An analysing of code on how it works during execution time


a. Increment:
- for var_name in range (start, actual end, positive step):
#logic
#remaining statement

Rules:
- positive step
- start should be less than end
- actual end value should be plus one

b. Decrementing for loop:


- for var_name in range (start, actual end -1, negative step):
#logic
#remaining statement

9
- With a logic to print first ‘n’ natural no’s in decrement order
N=3
0/p=3,2,1
Start= 3(n)
End=1 (1-1)
Step= -1

Rules:
- Negative step
- Start should be greater than end
- Actual end -1, if end value also should be included
2. for without range ():
Syntax:
- For var_name in iterable _object/group of elements:
# logic
# remaining statements

10
Rules:

- The values passed need not be maintained in any order


- It moves only in forward direction
- Values of any datatypes can be passed provided, it must be an iterable object
- It even works on empty iterable object
- But cannot work on single valued data
- The looping variable directly stores the elements

for with range() for without range()

2. while loop:
Syntax:
#Initialize var
while bool_cond:
#logic

11
#updation of looping var increment/ decrement
Variables used in bool cond of while loop:
a. Looping variable
b. Conditional variable
Ex: write a logic to print natural numbers up to “n” (included):
i/p: n=5
expected o/p: 1 2 3 4 5
2345
345

I. Write a logic to print the natural numbers decrement order with a increment order
difference:

Examples of test cases:


Examples for loop:
1. for i in range (2**8,8):
print(i)
empty output

12
2. flag=false
while not flag:
print(“hello world”)
flag=flag+5
o/p hello world (bcoz initially while loop is true after updation while loop will be false)
II. write a logic to keep getting the integer i/p from the user until the user enters 0. Once 0 is
entered stop asking for the i/p and conclude the execution by printing a simple statement.
And if the user is entering an even num then do not display the entered num.

5 distinct diff between for and while loop with program example

Functions:
- it is a independent block of code that is include to perform a specific task
- it is included independent of any classes
- a function will be executed only when it is called
- a function is called by its name by providing the necessary i/p if any
syntax:
- def function_name(parameters):
#function definition or body of a function or scope of a function
#logic
return o/p value/values
#function call
Var_name=function_name(argument)
Execution flow of a function:
#called function
def addition (A,B):
sum=a+b
return sum
res = addition (10,5)
print(res*2)#30
print(res-3)#12

13
print(res**0)#1

Return:
- keyword
- last executable line of code within a function

Numerical programs:
1. even or odd:
------------

a. WAP to check whether the given number is even or odd.


b. WAP to check whether the given number is even or odd using customized function.

How to convert into a function?


1. Identify the major logic, copy it
2. Include a function declaration based on the task to be performed
3. Paste the logic within the scope of the function to execute
4. Design the o/p stmt i.e., return stmt
5. Call the function and store the o/p of the function if any.

14
Write a program to print all the even number present in a user define range

15
WAP to print 1st “n” even natural numbers.

Odd numbers

Write a program to check Whether the character is alphabet or not

WAP to print cube of the number only if it’s divisible by 9 and 6

16
WAP to check whether the given string is keyword or not

WAP to check whether the string is palindrome or not


S= keyword
Var [si, ei, up]
Var [ : : -1] # for reverse
Var [ : : 2] #for even alphabet
Var [1: :2] #for odd alphabets

WAP to check the character is special or not.

9a] WAP to check weather the year is leap year or not

17
Tracing:

9b] WAP to print the leap year and not leap year in the user defined range separately.

18
9c] WAP to print the leap year in the user defined range.

Tracing:

19
COUNT DIGITS:
Tracing:

Note:
-To remove a digit from RHS in a given number ==> “n //10”
-To carry forward the current cycle’s updated value to the next cycle for further operations, utilize
the same variable on RHS for operation and left for updation.

20
1] WAP to display the count of digits of a given number using customized function

Armstrong number:

If the user gives a negative number

21
Using function:

WAP to print ASN and non ASN values separately present in user defined range

22
WAP to print first “n” ASN’s.

WAP to print all the ASN of a user defined range

23
Reverse a number:
2857  7582
------------------------------
2857 7
285  (7*10) +5=75
28 (75*10) + 8= 758
2  (758*10) +2= 7582
- Until n>0:
i) Get the digit
ii) Align the digit in the o/p memory by making space
iii) Remove the digit

Using function:

24
Integer palindrome
If the reversal of a number same as the original number, then is said to be integer palindrome

WAP to reverse all the numbers present in a user defined range

25
WAP to print all the integer and non-integer palindromes present in user defined range separately

WAP to print first ‘n’ integer palindrome

WAP to print first ‘n’ non integer palindrome

26
WAP to return sum of all the digits in a given number.
N=142
o/p = 7(1+4+2)

WAP to return product of all the digits in a given number.


N = 42
o/p = 8(4*2)

Factor:
- The value is completely reducing a given number is zero
- The least factor of a number is 1
- The highest value of a number is it’s self
- All The factors of number can be listed from one to the number itself
- Ex:
N=41,2,3,4
i=1

27
n%i==0 n=4%1==0[t]
p(i)#1

n=4, i=2, 4%2==0[T]


print(i)#2

n=4, i=3, 4%3==0[F]

n=4, i =4, 4%4==0[T]


print(i)#4

WAP to count the number of cycles taken to get all the factors of a given number

All the factors of a given number can be listed from 1 to the direct square root of a number or
lower nearest square root of the number

Square roots:
1*1=1
2*2=4
3*3=9
4 * 4 = 16
5 * 5 =25
26  nearest square root 25 = 5
(hence all the factors of 26 can be listed from 1 to 5)
18  16  4(1 to 4)
111  100  10(1 to 10)
81  81  9(1 to 9)

28
2 * x = 22
X = 22 // 2 = 11 is also a factor
Here ‘2’ is a factor of 22

3 * y = 15
Y = 15 // 3 = 5 is also a factor
Here ‘3’ is a factor of 15

6 * z = 18
X = 18 // 6 = 3 is also a factor
Here ‘6’ is a factor of 6

i*x=n
here, only if n % i == 0[T]
p(i)
p(n // i)

A number is said to be prime if and only if the count of factor of a given number is exactly 2

29

You might also like