0% found this document useful (0 votes)
2 views

Python

The document provides an overview of Python programming concepts, including operator precedence, statements, input/output operations, and various types of operators such as arithmetic, comparison, logical, and assignment operators. It also covers control statements like if-else and loops, detailing their syntax and providing examples for better understanding. Additionally, it explains string manipulation and how to use loops for various tasks, including counting, mathematical operations, and pattern printing.

Uploaded by

SHAHIDHA
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)
2 views

Python

The document provides an overview of Python programming concepts, including operator precedence, statements, input/output operations, and various types of operators such as arithmetic, comparison, logical, and assignment operators. It also covers control statements like if-else and loops, detailing their syntax and providing examples for better understanding. Additionally, it explains string manipulation and how to use loops for various tasks, including counting, mathematical operations, and pattern printing.

Uploaded by

SHAHIDHA
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/ 36

Precedence

This used an expression with more than one operator with different precedence to
determine which operation to perform 1st.

.p-parentheses
.E-Exponentiation
.M-multiplication
.D-Division
A-Addition
S-Substraction
Ex:

v=10+20*3

print(v)#1st calculate to multiple

USING AND & OR

name="joy"

age=23

if name=="joy" or name=="raghul" and age>=2:#1st is true so, we don't need evalute in second part

print("hello world")

else:

print("good bye!!")

another one ex:

print(100/10*10)#1st calculate division after multiple


3. STATEMENT
_____________________________________________________________________________________

A statement is an instruction that the Python interpreter can execute. It represents


a single action or a command in the program. Each line of code in Python typically
represents a statement.

 Comment Statement
 Declaration
 Assignment
 Input Statement
 Output Statement

Comment Statement
Human can understand python code not for complier and interpreter.

To add a multiline using # hash mark for each line

Ex:

Using string (triple quotes)

“”” Human can understand

python code not for

complier and interpreter.”””


Declaration
1.declaration refers to creating variables, functions, or classes

Variable Declaration: Assign a value to a variable.

Syntax:

x = 10

name = "Alice"

2.Function Declaration: Use def to define a function.

Syntax:

def function_name (parameters):#parametern like a,b

# Function bodys

return value

3.Class Declaration: Use class to define a class

Syntax:

class ClassName:

def __init__(self, parameters): # Constructor method (optional)

self.attribute = value

def method(self):

pass

4.Constant Declaration: Conventionally, use all uppercase letters for constants


PI = 3.14

ASSIGMENT STATEMET
An assignment statement in Python is used to assign a value to a
variable. It consists of a variable name on the left side of the = operator
and the value or expression on the right side. The value on the right is
evaluated and then stored in the variable on the left.
Systax:
variable_name = value
ex:
x = 10
name = "Alice"
pi = 3.14
*An assignment statement can also assign the result of an expression to a variable:

y = x + 5 # Assigns the result of x + 5 (which is 15) to y

INPUT STATEMENT
The input() function is used to read input from the user.

Syntax:

variable = input("Prompt message")

ex:

name = input("Enter your name: ")#optional

print("Hello, " + name)

OUTPUT STATEMENT
The print() function is used to display output.

Syntax:

Print( )

Ex:

Print(“hello world”)

Eval( )
The eval() function evaluates a given string as a Python expression and returns the
result.

Syntax:

eval(expression)

ex:

x=5

variable_name=eval(“x+5”)

print(variable_name)

Split( )
The split is used to split into list based on delimiter(string)

Syntax:

string.split(separator, maxsplit) #string and number

Ex:

text = "Hello World"

words = text.split() # Splits by spaces

print(words) # Output: ['Hello', 'World']


Parameter:

objects: Values to print (can be multiple).

sep=' ': Separator between values (default is a space).

end='\n': String to end the print with (default newline)

file=sys.stdout: Output stream (default is the console).

flush=False: Whether to flush the output buffer

immediately (default is False).

Ex:

print("Hello", "World", sep="-", end="!\n", flush=True)

op:

Hello-World!

Using Formatted string


Way to format strings in Python, the string with an f or F and place curly braces {} around the variables
or expressions want to include.
OPERATOR
. Arithmetic Operators
Used for mathematical calculations.
Operator Description Example

+ Addition a + b (5 + 3 = 8)
_ Subtraction a - b (5 - 3 = 2)
* Multiplication a * b (5 * 3 = 15)
/ Division a / b (5 / 3 = 1.67)
% Modulus (Remainder) a %b (5 % 3 = 2)
** Exponentiation a ** b (2 ** 3 = 8)
// Floor Division a // b (5 // 3 = 1)

Example:
a=5
b=3
print(a + b) # Output: 8
print(a - b) # Output: 2
print(a * b) # Output: 15
Comparison(relational)Operators
Used to compare values.

Operator Description Example

== Equal a == b

!= Not equal a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal a >= b


to

<= Less than or equal to a <= b

== Equal a == b

Example:
a=5
b=3
print(a == b) # Output: False
print(a > b) # Output: True
Logical Operators
Used to combine conditional statements.
Operato Description Example
r

and Returns True if both statements (a > 3 and b < 5)


are true
(True)
or Returns True if at least one (a > 3 or b > 5)

statement is true (True)


not Reverses the result not(a > 3) (False)

Example:

a=5
b=3
print(a > 3 and b < 5) # Output: True
print(a > 3 or b > 5) # Output: True
print(not (a > 3)) # Output: False
4. Assignment Operators
Used to assign values to variables.
Operator Example

= a=5 a=5

+= a += 3 a=a+3

-= a -= 3 a=a–3

*= a *= 3 a=a*3

/= a /= 3 a=a/3

%= a %= 3 a=a%3

//= a //= 3 a = a // 3

**= a **= 3 a = a ** 3

&= a &= 3 a=a&3

|= a |= 3 a=a|3

^= a ^= 3 a=a^3
>>= a >>= 3 a = a >> 3

<<= a <<= 3 a = a << 3

Example:
a=5
a += 3 # Equivalent to a = a + 3
print(a) # Output: 8
5. Bitwise Operators
Used for binary operations.
Operator name Description Example

& AND Sets each bit to 1 if both bits a&b


are 1

| OR Sets each bit to 1 if one of a|b


two bits is 1

^ xOR Sets each bit to 1 if one of a^b


two bits is 1

~ NOT Inverts all the bits ~a

<< Zero fill left shift Shift left bb pushing zeros in a << 2
from the right and let the
leftmost bits fall off

>> S Shift right bb pushing copies a >> 2


igned right shift of the leftmost bit in from the
left, and let the rightmost bits
fall off

Example:
a = 5 # 0101 in binarb
b = 3 # 0011 in binarb
print(a & b) # Output: 1 (0001 in binarb)
print(a | b) # Output: 7 (0111 in binarb)

6. Membership Operators
Used to check if a value exists in a sequence.

Operator Description Example

in Returns True if a a in b
sequence with the
specified value is
present in the object

not in Returns True if a a not in b


sequence with the
specified value is not
present in the object

Example:

text = "Hello World"


print("H" in text) # Output: True
print("a" not in text) # Output: True
7. Identity Operators
Used to compare memory locations of objects.
Operator Description Example

is Returns True if both a is b


variables are the same
object

is not Returns True if both a is not b


variables are not the
same object

Example:
a = [1, 2, 3]
b=a
c = [1, 2, 3]

print(a is b) # Output: True (same object)


print(a is c) # Output: False (different objects)
CONTROL STATEMENT
 If statement
 If-else statement
 Nested-if statement
 If elif else statement or labber if statement

If statement

If Statement: Executes a block of code if the


condition is True.
Syntax:

if condition:

# code to execute if condition is


Ex:

x=int(input("given a number"))

y= int(input("given another number"))

if(x>y):

print("x=",x,"is greater")

if(x<y):
print("y=",y,"is greater")

If else statement

The if-else statement evaluates a condition. If the condition is True, the


code will be evaluates. If it is False, the code block under else is
executed.
Syntax:

if condition:

# code to execute if condition is True

else:

# code to execute if condition is False

Ex:

num=int(input("enter the number:"))

if(num%2==0):

print(num,"is even")

else:

print(num,"is odd")
Nested If Statement
A nested if statement is an if statement inside
another if statement. It allows for multiple levels of
decision-making.
Syntax:

if condition1:
if condition2:
# code to execute if both condition1 is True
.
Ex:

a,b=10,20

if a!=b:

if a>b:

print("a is greater than b")

else:

print("a is greater than a")

else:

print("both a and b are equal")


If-Elif-Else Statement (or Ladder If
Statement)
The if-elif-else statement (often referred to as ladder if) checks multiple
conditions in sequence. It evaluates each condition in order until one is
True, and if none are True, the else block is executed.

Syntax:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
elif condition3:
# code to execute if condition3 is True
else:
# code to execute if none of the conditions are
EX: True

age = 20
if age < 18:
print("You are a minor.")
elif age == 18:
print("You are just an adult.")
elif age < 30:
print("You are a young adult.")
else:
print("You are an adult.")

________________________________________________________
_

Loops
To repeat a set of statements multiple times
continuously. There are three types:

 While loop
 For loop
 Nested loop
While loop
It’s is used to execute a block of statements
repeatedly until the given condition is satisfied.
When the condition is false .the loop is
terminated.
Syntax:

While expression:
Statement(s)

Ex:
Count=0

While(count<3):

Count=count+1

Print(“Joy”)

Op:

Joy

Joy

Joy
Basic Counting Examples
1.Count from 1 to 10
i=1
while i <= 10:
print(i)
i += 1
2.Count down from 10 to 1
i = 10
while i > 0:
print(i)
i -= 1
3.Print even numbers from 2 to 10

i=2
while i <= 10:
print(i)
i += 2
4.Print odd numbers from 1 to 9
i=1
while i < 10:
print(i)
i += 2
User Input-Based Loops
5.Take input until the user enters 'exit'
while True:
text = input("Enter something (type 'exit' to
stop): ")
if text.lower() == 'exit':
break
print("You entered:", text)
6.Guess the number game
secret = 7
guess = -1
while guess != secret:
guess = int(input("Guess a number (1-10): "))
print("You guessed it!")
Mathematical Loops
7.Sum of first 10 natural numbers
i=1
total = 0
while i <= 10:
total += i
i += 1
print("Sum:", total)
8.Factorial of a number (e.g., 5!)
n=5
fact = 1
i=1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)
9.Multiplication table of 5
num = 5
i=1
while i <= 10:
print(f"{num} x {i} = {num * i}")
i += 1
10. Fibonacci sequence (first 10 numbers)
a, b = 0, 1
count = 0
while count < 10:
print(a, end=" ")
a, b = b, a + b
count += 1
String Manipulation Loops
11. Reverse a string using while loop
s = "hello"
i = len(s) - 1
while i >= 0:
print(s[i], end="")
i -= 1
12. Count vowels in a string
text = "hello world"
vowels = "aeiou"
count = 0
i=0
while i < len(text):
if text[i] in vowels:
count += 1
i += 1
print("Vowel count:", count)
Logical Condition-Based Loops
13. Find the first multiple of 7 greater than
50
num = 51
while num % 7 != 0:
num += 1
print("First multiple of 7 after 50:", num)
14. Check if a number is prime
num = 29
i=2
is_prime = True
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
print("Prime" if is_prime else "Not Prime")
Control Flow in Loops
15. Skip printing number 5
i=1
while i <= 10:
if i == 5:
i += 1
continue
print(i)
i += 1
16. Stop at the first negative number in a list
numbers = [4, 7, 2, -1, 9]
i=0
while i < len(numbers):
if numbers[i] < 0:
break
print(numbers[i])
i += 1
Nested While Loops
17. Print a square pattern
i=0
while i < 5:
j=0
while j < 5:
print("*", end=" ")
j += 1
print()
i += 1
18. Print a right triangle pattern
i=1
while i <= 5:
j=1
while j <= i:
print("*", end=" ")
j += 1
print()
i += 1
Miscellaneous Examples
19. Simulate a countdown timer
import time
countdown = 5
while countdown > 0:
print(countdown)
time.sleep(1)
countdown -= 1
print("Time's up!")
20. Reverse a number
num = 1234
rev = 0
while num > 0:
rev = rev * 10 + num % 10
num //= 10
print("Reversed number:", rev)

FOR LOOP
1.Count from 1 to 10
for i in range(1, 11):
print(i)
1. Count down from 10 to 1
for i in range(10, 0, -1):
print(i)
2. Print even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
3. Print odd numbers from 1 to 9
for i in range(1, 10, 2):
print(i)
Looping Through Lists

5. Print each item in a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
6. Find the sum of a list of numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total)

Looping Through Strings

7. Print each character in a string


text = "hello"
for char in text:
print(char)
8. Count vowels in a string
text = "hello world"
vowels = "aeiou"
count = 0
for char in text:
if char in vowels:
count += 1
print("Vowel count:", count)
Mathematical Loops

9. Sum of first 10 natural numbers


total = sum(range(1, 11))
print("Sum:", total)
10. Factorial of a number (e.g., 5!)
fact = 1
for i in range(1, 6):
fact *= i
print("Factorial:", fact)
11. Multiplication table of 5
num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
12. Fibonacci sequence (first 10 numbers)
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b

Looping with Conditions

13. Check if a number is prime


num = 29
is_prime = True
for i in range(2, num // 2 + 1):
if num % i == 0:
is_prime = False
break
print("Prime" if is_prime else "Not Prime")
14. Find the first multiple of 7 greater than 50
for num in range(51, 100):
if num % 7 == 0:
print("First multiple of 7 after 50:", num)
break

Loop Control Statements

15. Skip printing number 5


for i in range(1, 11):
if i == 5:
continue
print(i)
16. Stop at the first negative number in a list
numbers = [4, 7, 2, -1, 9]
for num in numbers:
if num < 0:
break
print(num)
Nested Loops

17. Print a square pattern


for i in range(5):
for j in range(5):
print("*", end=" ")
print()
18. Print a right triangle pattern
for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print()

Miscellaneous Examples

19. Simulate a countdown timer


import time
for countdown in range(5, 0, -1):
print(countdown)
time.sleep(1)
print("Time's up!")
20. Reverse a number
num = 1234
rev = 0
for digit in str(num):
rev = int(digit) + rev * 10
print("Reversed number:", rev)
--------------------------------------------------------------------------

Function
Use def to define a function.

Syntax:

def function_name (parameters):#parametern like a,b

# Function bodys

return value

ex:
1. Basic Function
def greet():
print("Hello, Welcome to Python!")

greet()

2. Function with Parameters


def add(a, b):
return a + b

print(add(5, 3)) # Output: 8

3. Function with Default Parameters


def greet(name="Guest"):
return f"Hello, {name}!"

print(greet()) # Output: Hello, Guest!


print(greet("Alice")) # Output: Hello, Alice!
4. Function Returning Multiple Values
def operations(a, b):
return a + b, a - b, a * b, a / b

add, sub, mul, div = operations(10, 2)


print(add, sub, mul, div) # Output: 12, 8, 20, 5.0

5. Function with Variable Arguments (*args)


def sum_all(*numbers):
return sum(numbers)

print(sum_all(1, 2, 3, 4, 5)) # Output: 15

6. Function with Keyword Arguments (**kwargs)


def person_info(**details):
for key, value in details.items():
print(f"{key}: {value}")

person_info(name="John", age=30, city="New York")

7. Lambda (Anonymous) Function


square = lambda x: x * x
print(square(5)) # Output: 25

8. Function with a Loop


def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

print(factorial(5)) # Output: 120

9. Recursive Function
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120


10. Function with List Comprehension
def squares(n):
return [x**2 for x in range(1, n+1)]

print(squares(5)) # Output: [1, 4, 9, 16, 25]

11. Function with a Dictionary


def create_dict(keys, values):
return dict(zip(keys, values))

keys = ['name', 'age', 'city']


values = ['Alice', 25, 'New York']
print(create_dict(keys, values)) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

12. Function with Exception Handling


def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: Division by zero is not allowed"

print(divide(10, 2)) # Output: 5.0


print(divide(10, 0)) # Output: Error: Division by zero is not allowed

13. Function Using Map()


def double(x):
return x * 2

numbers = [1, 2, 3, 4]
result = list(map(double, numbers))
print(result) # Output: [2, 4, 6, 8]

14. Function Using Filter()


def is_even(n):
return n % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # Output: [2, 4, 6]
15. Function Using Reduce()
from functools import reduce

def multiply(x, y):


return x * y

numbers = [1, 2, 3, 4]
product = reduce(multiply, numbers)
print(product) # Output: 24

You might also like