Python
Python
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
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!!")
Comment Statement
Declaration
Assignment
Input Statement
Output Statement
Comment Statement
Human can understand python code not for complier and interpreter.
Ex:
Syntax:
x = 10
name = "Alice"
Syntax:
# Function bodys
return value
Syntax:
class ClassName:
self.attribute = value
def method(self):
pass
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:
INPUT STATEMENT
The input() function is used to read input from the user.
Syntax:
ex:
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:
Ex:
Ex:
op:
Hello-World!
+ 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.
== Equal a == b
!= Not equal 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
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
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
<< Zero fill left shift Shift left bb pushing zeros in a << 2
from the right and let the
leftmost 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.
in Returns True if a a in b
sequence with the
specified value is
present in the object
Example:
Example:
a = [1, 2, 3]
b=a
c = [1, 2, 3]
If statement
if condition:
x=int(input("given a number"))
if(x>y):
print("x=",x,"is greater")
if(x<y):
print("y=",y,"is greater")
If else statement
if condition:
else:
Ex:
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:
else:
else:
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
Miscellaneous Examples
Function
Use def to define a function.
Syntax:
# Function bodys
return value
ex:
1. Basic Function
def greet():
print("Hello, Welcome to Python!")
greet()
9. Recursive Function
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
numbers = [1, 2, 3, 4]
result = list(map(double, numbers))
print(result) # Output: [2, 4, 6, 8]
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
numbers = [1, 2, 3, 4]
product = reduce(multiply, numbers)
print(product) # Output: 24