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

Programming using Python Notes

The document provides a comprehensive overview of programming in Python, covering variables, data types, operators, decision-making statements, loops, and functions. It includes practical examples for each topic, demonstrating how to use Python syntax effectively. The content is structured to guide beginners through the foundational concepts of Python programming.

Uploaded by

hasaanmansuri91
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 views29 pages

Programming using Python Notes

The document provides a comprehensive overview of programming in Python, covering variables, data types, operators, decision-making statements, loops, and functions. It includes practical examples for each topic, demonstrating how to use Python syntax effectively. The content is structured to guide beginners through the foundational concepts of Python programming.

Uploaded by

hasaanmansuri91
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

Programming using Python:

Variables in Python:

 Variable is like a container that stores data.

 In Python, you don’t need to declare its type


explicitly — it’s decided automatically when you
assign a value

Examples:

1.1 Assign and Print Variables

name = "Hasaan"
age = 21
weight = 82
print("My name is:",name)
My name is: Hasaan
print("My age is:",age)
My age is: 21
print("My weight is:",weight)
My weight is: 82

#1.2 Updating Variable Value


counter = 5
print("Initial Value:",counter)
Initial Value: 5
counter = counter + 5
print("Updated Value is:",counter)
Updated Value is: 10

#1.3 Multiple Variable Assigment

x , y , z = 5 , 10 , 15
print(x,y,z)
5 10 15

#1.4 Swapping Variables

a = 100
b = 200
a,b=b,a
print("The value of a after swapping is:",a)
The value of a after swapping is: 200
print("The value of b after swapping is:",b)
The value of b after swapping is: 100

#1.5 Using Variables in Calculations


lenght = 12
width = 8
area = lenght * width
print("The area of rectange is:",area)
The area of rectange is: 96

#1.6 String Concatenation

first_name = "Hasaan"
last_name = "Mansuri"
full_name = first_name + '' '' + last_name
full_name
'HasaanMansuri'

Data Types in Python:

 Data types in Python are a way to classify data


items.
 They represent the kind of value, which determines
what operations can be performed on that data.
 Since everything is an object in Python
programming, Python data types are classes and
variables are instances (objects) of these classes.
Practical:

#2.1 Numbers (int, float, complex)


name = "Hasaan"
print(type(name))
<class 'str'>
age = 21
print(type(age))
<class 'int'>
pi = 3.14
print(type(float))
<class 'type'>
z = 2 + 3j
print(type(z))
<class 'complex'>

#2.2 String

name = "Hasaan"
print([Link]())
HASAAN
print([Link]())
hasaan
print([Link]())
Hasaan
print([Link]("Hasaan","Nabil"))
Nabil
print([Link]())
['Hasaan']
word = ["python","is","fun"]
print(" ".join(word))
python is fun
print([Link]("Hasaan"))
0
print([Link]("Nabil"))
-1
print([Link]("l"))
0
print(len(name))
6
print("python".capitalize())
Python
#[Link]
#3.1 List Example

fruits = ["apple","banana","orange"]
fruits
['apple', 'banana', 'orange']
print(type(fruits))
<class 'list'>
[Link]("mango")
print(fruits[1])
banana

#[Link]

coordinates = (10,20)
coordinates
(10, 20)
print(type(coordinates))
<class 'tuple'>
print(coordinates[0])
10
print(coordinates[1])
20

#[Link]

unique_numbers = {1,2,3,4}
unique_numbers
{1, 2, 3, 4}
print(type(unique_numbers))
<class 'set'>
unique_numbers.add(5)
unique_numbers
{1, 2, 3, 4, 5}

#[Link]
student = {"name": "Hasaan" , "age": "21" , "marks":
"80" }
student
{'name': 'Hasaan', 'age': '21', 'marks': '80'}
print(type(student))
<class 'dict'>
print(student["name"])
Hasaan
student["marks"] = 90
student
{'name': 'Hasaan', 'age': '21', 'marks': 90}
#[Link]
is_active = True
print(type(is_active))
<class 'bool'>
print(5 > 3)
True

Operators in Python:

 Operators are used to perform operations on


variables and values.
 They are used to evaluate different types of
expressions and to manipulate the values of
operands or variables by performing different
operations on them.

Different Types of Operators:

(1) Arithmetic Operators


(2) Comparison Operators
(3) Assignment Operators
(4) Logical Operators
(5) Bitwise Operators

#Operators in Python
#[Link] Operator
a = 20
b = 10
print(a+b)
30
print(a-b)
10
print(a*b)
200
print(a//b)
2
print(a%b)
0
print(a**b)
10240000000000
#[Link] Operator
print(a==b)
False
print(a!=b)
True
print(a>b)
True
print(a<b)
False
print(a>=b)
True
print(a<=b)
False
#[Link] Operator
x=2
x
2
x += 1
x
3
x -= 1
x
2
#[Link] Operator
x=2
y=4
z=4
x is y
False
y is z
True
z is x
False
#[Link] Operator
a = 10
b=4
print("a & b =" , a&b)
a&b=0
>>> print("a | b =" , a | b )
a | b = 14
print("a | b =" , a | b )
a | b = 14
print("a ^ b =" , a ^ b)
a ^ b = 14
print("~a=",~a)
~a= -11

Decision Making Statements in Python:

 Decision making statements in Python primarily


use conditional statements to execute different
blocks of code based on whether a condition is true
or false.
 The main decision-making statements in Python
are if, if...else, if...elif...else, and
nested if statements.

Practical:

#[Link] statement
#Example 1: Check positive number
number = int(input("Enter number: "))
Enter number: 5
if number > 0:
print("Positive Number")

Positive Number
#Example 2: Eligiblity for voting
age = int(input("Enter age: "))
Enter age: 18
if age >= 18:
print("Eligible to vote")

Eligible to vote
#Example 3: Check if number is divisible by 5 or not
x = int(input("Enter value of x: "))
Enter value of x: 5
if x % 5 == 0:
print("Number is divisible by 5")
#[Link]-else statement
#Example 1: Check if number is odd or even
number = int(input("Enter number: "))
Enter number: 3
if number % 2 == 0:
print("Even Number")
else:
print("Odd Number")

Odd Number
#Example 2: Check if student is pass or fail
marks = int(input("Enter marks: "))
Enter marks: 78
if marks >= 35:
print("Pass")
else:
print("Fail")

Pass
#Example 3: Check login
username = input("Enter username: ")
Enter username: hasaan
password = input("Enter password: ")
Enter password: 123@itims
if username == "hasaan" and password ==
"123@itims":
print("Login Succeded")
else:
print("Login Failed")

Login Succeded
#Example 4: Tempreature Check
tempreature = int(input("Enter tempreature: "))
Enter tempreature: 35
if tempreature >= 30:
print("Hot Day")
else:
print("Cold Day")

Hot Day

#[Link]-elif-else statement
#Example 1: Check if number is positive , negative or
zero
number = int(input("Enter number: "))
Enter number: 4
if number > 0:
print("Positive Number")
elif number < 0:
print("Negative Number")
else:
print("Zero")

Positive Number
#Example 2: Grading System
marks = int(input("Enter marks: "))
Enter marks: 85
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 60:
print("Grade C")
elif marks >= 50:
print("Grade D")
else:
print("Fail")

Grade A

#Example 3: Check if the day is weekend or weekday


day = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
else:
print("Other day")

Wednesday

#[Link]-if else
#Example 1: Check age and gender
age = int(input("Enter age: "))
Enter age: 21
gender = input("Enter gender: ")
Enter gender: Male
if age >= 18:
if gender == "Male":
print("Adult Male")
else:
print("Adult Female")
else:
print("Minor")

Adult Male
#Example 2: Exam eligibility
attendance = int(input("Enter attendence: "))
Enter attendence: 75
marks = int(input("Enter marks: "))
Enter marks: 40
if attendance >= 75:
if marks >= 50:
print("Eligible for exam")
else:
print("Not enough marks")
else:
print("Attendance too low")

Not enough marks


Loops in Python:

 A sequence of statements are executed until some


condition for termination of the loop are satisfied is
called looping.
 Loop Statements allow us to execute single
statement or multiple statements and it’s is the
general form of looping in most programming
languages.
 Loops can execute a block of code number of times
until a certain condition is met. Their usage is fairly
common in programming.
 There are two types of loops in python: while loop
and for loop.

While Loop:

 While Loop is used to execute a block of


statements repeatedly until a given condition is
satisfied.
 When the condition becomes false, the line
immediately after the loop in the program is
executed.

Syntax:
while expression:
Statement(s)

For Loops:

The for loop in Python is used to iterate over a


sequence (list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.
Syntax:
for val in sequence:

Body of for

#Loops in Python
#While Loop
#Example 1: Print Numbers 1 to 10
number = int(input("Enter number: "))
Enter number: 1
while(number<=10):
print(number)
number = number + 1

1
2
3
4
5
6
7
8
9
10
#Example 2: To print python program 10 times
number = int(input("Enter number: "))
Enter number: 1
while(number<=10):
print("Python Program")
number = number + 1

Python Program
Python Program
Python Program
Python Program
Python Program
Python Program
Python Program
Python Program
Python Program
Python Program
#Example 3: Program to add natural numbers up to n.
n = int(input("Enter n: "))
Enter n: 5
sum = 0
i=1
while(i<=n):
sum = sum + i
i=i+1

print("The sum is:",sum)


The sum is: 15

#1.4 Multiplication table using while loop


num = int(input("Enter a number: "))
Enter a number: 3
sum = 0
i=1
while(i<=10):
print(f"{num} x {i} = {num * i}")
i=i+1

3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
#1.5 To reverse a number
'
num = 1234
rev = 0
while(num>0):
rev = rev * 10 + num % 10
num //= 10

print("The num is:",rev)


The num is: 4321

#[Link] loop
#Example 2.1
fruits = ["apple","banana","orange"]
for x in fruits:
print(x)

apple
banana
orange
#Example 2.2
for x in "orange":
print(x)

o
r
a
n
g
e
#Example 2.3
fruits = ["apple","orange","banana"]
for x in fruits:
print(x)
if x == "orange":
break

apple
orange

#Example 2.4
fruits = ["apple","orange","banana"]
for x in fruits:
print(x)
if x == "orange":
continue

apple
orange
banana
#Example 2.5
for x in range(6):
print(x)

0
1
2
3
4
5
#Example 2.6
for x in range(2,6):
print(x)

2
3
4
5

#Example 2.7
adj = ["red","orange","blue"]
... fruits = ["apple","orange","mango"]
... for x in adj:
... for y in fruits:
... print(x,y)

red apple
red orange
red mango
orange apple
orange orange
orange mango
blue apple
blue orange
blue mango

Functions in Python:

Functions in Python:
 A function is a block of code that performs a specific task.
 Functions help break our program into smaller and modular chunks.
 As our program grows larger and larger, functions make it more organized
and manageable.
 It avoids repetition and makes code reusable.

Defining a Function:

 We can define function using def keyword


 A function might take input in the form of
parameters.

Syntax to declare function is:

def fun():
print("Welcome to GFG")

Calling Functions:
Once we have defined a function, we can call it from
another function, program or even the Python prompt.
To call a function we simply type the function name
with appropriate parameters.

>>> greet(‘Raj’)
Hello, Raj. Good morning!

#Functions in Python
#Example 1: Simple Function
def greet(name):
print(f"Hello, {name}!")

greet("Hasaan")
Hello, Hasaan!
greet("Jethalal")
Hello, Jethalal!
#Example 2: Function with return value
def add(a,b):
return a+b

result = add(5,15)
print(result)
20
#Example 3: Default Parameters
def power(base,exponent=2):
return base ** exponent

print(power(5))
25
>>> print(power(5,3))
125
>>> #Example 4: Multiple Returns
>>> def divide(a, b):
... if b == 0:
... return "Error: Division by zero"
... return a / b
...
>>> print(divide(5,10))
0.5
>>> print(divide(10,0))
Error: Division by zero
>>> #Example 5: Lambda (Anonymous Function)
>>> square = lambda x: x * x
>>> print(square(6))
36

You might also like