Basic Python
Basic Python
Basic Python
Preface
Basics of Python
1
SR. PAGE
No:
INDEX OF CONTENT
NO:-
1 What is Python?
15
3 Why Python. 16
6 What is a Variable? 18
2
9 Sequence Data Type:- Strings 19-22
,Slicing, Modifying Strings, String
Concatenation.
10 Python Operators:- 22
· Arithmetic operators
23
· Assignment operators
· Comparison operators
24
· Logical operators
· Identity operators
· Membership operators
· Bitwise operators
14
Python Functions: Arguments, 26
3
15 Python Lambda.
27
17 Module. 27
18 Math Functions.
27
4
PYTHON REAL LIFE
PROBLEMS SOLVING:
SR. PAGE
INDEX OF PYTHON REAL LIFE NO:
NO:
PROGRAMS
1 Write a program for Add Two Numbers In 28
Python Using Sum.
5
7 Convert Kilometers to Miles using the formula 35
of miles.
6
17 Write a program to Remove the last item in the 44
set by using pop () method
7
27 Write a program to print the user input number 52
of a fibonacci sequence using a for loop.
8
36 Write a program making a dictionary from two 59
lists by using the zip function.
9
46 Write a program to check whether a number is 69
in a given range.
10
56 Write a python program to find all duck 77
numbers within a range
11
66 Write a program for Diamond pattern by using 87
Nested for loop.
12
75 Write a program to calculate the cosine 96
similarity of 2 vectors (as numpy arrays).
13
84 Write a python program to access the index of a 105
list using a for loop in python.
14
What is Python?
“Python is a popular programming
language. It was created by Guido van
Rossum, and released in 1991.”
It is used for:
15
● Python can be used for rapid
prototyping,or for production-ready
software development.
Why Python?
● Python works on different platforms
(Windows, Mac, Linux, Raspberry Pi,
etc).
● Python has a simple syntax similar
to the English language.
● Python has syntax that allows
developers to write programs with
fewer lines than some other
programming languages.
● Python runs on an interpreter
system, meaning that code can be
executed as soon as it is written.
This means that prototyping can be
very quick.
● Python can be treated in a
procedural way, an object-oriented
way or a functional way.
Input:
16
Allows you to ask a user to type some
sort of information into the program and
to save that information into a variable
that the program can process.
Type:
Id:
17
Creating a Comment:(used in every
programs)
Python Numbers:
There are three numeric types
in Python.
● int
18
● Float
● complex
Strings:
Slicing:
Modify Strings:
Python has a set of built-in methods that
you can use on strings.
19
● Upper Case
● Lower Case
● Remove Whitespace
● Replace String
● Split String
String Concatenation:
String Format:
As we learned in the Python Variables
chapter, we cannot combine strings and
numbers like this.
20
them in the string where the
placeholders {} are.
List:
Lists are used to store multiple items in a
single variable.
Tuple:
Set:
21
Set is one of 4 built-in data types in
Python used to store collections of data,
the other 3 are list,tuple and Dictionary
all with different qualities and usage.
Dictionary:
Modify Strings:
Python has a set of built-in methods that
you can use on strings.
● Upper Case
● Lower Case
● Remove Whitespace
● Replace String
● Split String
Python Operators:
22
In the example below, we use the +
operator to add together two values:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
23
Python Logical Operators:
● Equals: a == b
24
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
Nested If:
You can have if statements inside if
statements, this is called nested if
statements.
25
other object-oriented programming
languages.
Python Functions:
Arguments:
26
You can add as many arguments as you
want, just separate them with a comma.
Python Lambda:
Python Classes/Objects:
Module:
27
A file containing a set of functions you
want to include in your application.
Math Functions:
The min() and max() functions can be
used to find the lowest or highest value
in an iterable.
Coding part:-
#User can create two variable num1 and
#num2
num1=10
num2=20
sum=num1+num2
28
print(“the sum of two number is:”,sum)
29
3. Write a program for Hello world
print by using print function
#User can directly use print function
#use single quotes or double quotes in print
function
print("Hello world!")
30
#The square root of a given number using sqr
#root variable values
print("the square root of given number is
",Sqr_root)
31
6. Write a program for Simple
Calculator Using function
32
#define square function and using print
#statement
def sqr(num1,num2):
print(f'{num1}**2={num1**2}')
print(f'{num2}**2={num2**2}')
#using while loop for continue
while(True):
#taking input from users for num1 variable
num1=int(input("enter any number:"))
#taking input from users for num2 variable
num2=int(input("enter another number:"))
#using print statement to show task
print("""this is your taks
1.add
2.sub
3.mul
4.div
5.mod
6.flo
7.sqr """)
print(f'{num1}+{num2}=={add(num1,num2)}')
elif(ip==2):
33
print(f'{num1}-{num2}=={sub(num1,num2)}')
elif(ip==3):
print(f'{num1}*{num2}=={mul(num1,num2)}')
elif(ip==4):
print(f'{num1}/{num2}=={div(num1,num2)}')
elif(ip==5):
print(f'{num1}%{num2}=={mod(num1,num2)}')
elif(ip==6):
print(f'{num1}//{num2}=={flo(num1,num2)}')
elif(ip==7):
sqr(num1,num2)
else:
break #for quite
34
7.Convert Kilometers to Miles using
formula of miles.
35
print(km,"kms in miles will be",mile,"miles")
36
#using print statements for print value of y
print("the value of y is",y)
37
elif a==0:
print("number is zero ")
#statement for elif block execution
38
11. Write a program to check if a
given year is a leap year or not.
#using else
else:
print(year,"is not leap year")
39
12. Write a program to check given
number is prime or not
#creating num variable for taking input from
#user
num=int(input("enter any number:"))
40
13.Write a program to GENERATE A
RANDOM NUMBER
41
print("a and b are equal")
#is above both conditions is false then else
#block will execute
else: #no need condition
print("a is greater than b")
#User can create two variable a and b to
#compare it self by values
a = 200
b = 33
# user can use if condition
if b > a: # b is greater than a
print("b is greater than a")
#user can use elif if conditions is more
elif a == b: # a and b is equal
print("a and b are equal")
#is above both conditions is false then else
#block will execute
else: #no need condition
print("a is greater than b")
42
#user can make list
my = ["a", "b", "a", "c", "c"]
#use fromkeys method for remove
#duplicates
my = list(dict.fromkeys(my))
print(my) #print my list
43
17. Write a program to Remove the
last item in set by using pop() method
44
"year": 1964
}
#Using the pop() method for removing last
#element
dict.pop("model")
print(dict) #the dictionary after removal
45
20.Write a program by marks we can
find grade using if… elif… else.
else:
print("you have failed in examination with F
grade ") #print for else statement
46
21. Write a Program for choosing any
language.
#user can create any variable and take input
#from user by using input function
choice=int(input("""please select your favorite
language
1.python language
2.java language
3.R language
4.Rust language
please select :"""))
if(choice==1): # if for python language
print("your selected language is: python
language ")
elif(choice==2): #elif for java language
print("your selected language is:java
language ")
elif(choice==3): #elif for R language
print("your selected language is:R language
")
elif(choice==4): #elif for Rust language
print("your selected language is:Rust
language ")
else: #else if above condition is not met
print ("you are not from this world! ")
47
22.Write a program for checking
eligibility of voting.
48
23. Write a program to Find vowels
from any string and count by using
for loop
for i in s:
if(i in vowel):
count +=1 #indexing increment
print(count) #print the count values
49
#this is the formula
fahrenheit=(celsius*(9/5))+32
#Users can use(1.8) instead of (9/5)
#print statement using display the
#converted value.
print("the converted value
is",fahrenheit,"fahrenheit")
50
26.Write a program for user input
name,age and marks.Using
formatting of string and string
interpolation(f.string)
#string formatting
#user can use input function for taking input
#name
name=input("enter your name:")
#user can use input function for taking input
#age
age=input("enter your age:")
#user can use input function for taking input
#marks
marks=input("enter your marks:")
#just for shows user input values
print(name,age,marks )
#string formatting
print("my name is " +name+ "my age is
"+age+" my marks is"+marks)
#string interpolation (f.string )
print(f"my name is {name},my age is {age},my
marks is {marks}")
51
27.Write a program to print the user
input number of a fibonacci
sequence using a for loop.
#using variable a and b and assigning values
a=0
b=1
#taking input from user any number
num=int(input("enter any number to obtain
fibonacci sequence:"))
#if condition
if num==1:
print(a) #print a values
else: #else
print(a) #print a values
print(b) #print b values
#using for loop and range
for i in range(1,num+1):
c=a+b #creating variable c and assigning
#value a+b
a=b #assign
b=c #assign
print(c) #print c values
52
28.Write a program to print all prime
numbers in intervals by using a for
loop.
53
29.Write a program to print the even
numbers from a given list by using a
function.
#python program to print the even numbers
#from a given list using a function.
#using function
def is_even_number(num):
enum=[] #creating object for empty list
for n in num: #using for loop
if n %2==0: #using if for conditions for
#even number
enum.append(n) #using append
#method
return enum #using return
#using print statement
print(is_even_number([11,12,13,14,15,16,17,1
8,19]))
54
return 1 #returning 1
else: #using else
#returning the values multiply by factorial of
#value-1
return n * factorial (n-1)
#users can create variable and take input from
#user
n=int(input("enter any number to compute the
factorial:"))
print(factorial(n)) #print the factorial value
55
index = index -1 #assigning the index
#value for reverse
return rs #return the rs
print(string_reverse("sarjilsatware")) #print the
#string_reverse
56
33.Write a program to compute
maximum elements from a list by
using lambda function with reduce
function.
#python program using a lambda function with
#reduce function
#to compute maximum element from list
import functools #importing functools
#creating list
A=[11,34,54,65,90,23]
#using print statement
print("the maximum element of the list
is:",end="")
#using lambda and reduce function
print(functools.reduce(lambda a,b:a if a>b else
b,A))
57
#call lambda function
#create variable and take input from user
num=int(input("enter the number\n"))
#create variable for square
result= square(num) #print statement
print("square of number is:",result)
58
36.Write a program making a
dictionary from two lists by using the
zip function.
#create two list
l1=[1,2,3,4,5]
l2=["sarjil","sufiyan","uvais","madiha","umar"]
#create variable and apply zip function
zip_obj=zip(l1,l2)
print(zip_obj) #print created variable zip_obj
l1=list(zip_obj) #convert into list
d1=dict(l1) #convert into dictionary
print(d1) #print dictionary
59
37.Write a program function that
accepts a string and calculates the
number of uppercase letters and
lowercase letters.
#using function
def string_test(s):
d={"upper_case":0,"lower_case":0}
#creating a dictionary and assigning the value
#lowercase and uppercase 0.
for c in s: #using for loop
if c.isupper(): #using if condition for
#upper case
d["upper_case"]+=1
elif c.islower(): #using elif condition for
#lower case
d["lower_case"]+=1
else: #using else for pass
pass
print("original string:",s) #print for original
#string
#using print function for uppercase
print("no. of uppercase
characters:",d["upper_case"])
#using print function for lowercase
print("no.of lower case
characters:",d["lower_case"])
#calling for function
string_test("I Love My India")
60
38.Write a program to find the most
repeated number from a list.
#find the most repeated number from list
max_count = 0
numbers=[1,2,3,3,3,4,5,6,73]
# Iterate through the list
for num in numbers:
# Count occurrences of the current number in
#the list
current_count = numbers.count(num)
61
39.Write a program to find the most
repeated number from a user
inputted numbers by using functions
and modules.
def main():
# Input: List of numbers
numbers = [int(x) for x in input("Enter
numbers separated by space: ").split()]
62
# Output the result
print(f"The most repeated number is
{most_repeated_number} with a count of
{count}.")
if __name__ == "__main__":
main()
63
for i in range(num_terms):
print(fibonacci(i), end=" ") #print
#statement
64
month = int(input("Enter month: "))
#using print statements for calendar.month
print(calendar.method with user inputted year
and month month(year, month))
65
print("Please enter a positive integer.")
else: #using else statement
print("Fibonacci sequence:")
#using for loop with range
for i in range(num_terms):
print(fibonacci(i), end=" ") #print
#statement
66
#user can create variable B and assign
#matrices
B= [[4,5,6],
[8,9,1],
[3,5,6]]
result[i][j]=A[i][j]+B[i][j]
print(result) #print statement for print result
67
#user can create T variable and apply empty
#matrix
T= [[0,0],
[0,0],
[0,0]]
#using for loop for row with range
for i in range(len(A)):
#using for loop for column with range
for j in range(len(A[0])):
T[j][i]=A[i][j] #assigning the transpose
#using print statement for T matrix
print(T)
68
46.Write a program to check whether
a number is in a given range.
#using function
def test_range():
#taking input from user in variable of n
n=int(input("enter any number"))
#using if condition with range
if n in range(3,10):
#using print statement(if Block )
print(" %s is in the range"%str(n))
else: #using else
#using print statement (else block )
print("the number is outside the given
range.")
test_range() #testing the range
69
max_count = 0
numbers=[1,2,3,3,3,4,5,6,73]
# Iterate through the list
for num in numbers:
# Count occurrences of the current number in
#the list
current_count = numbers.count(num)
70
if i in dict: #using conditional statement
dict[i] += 1 #assigning the value
else: #using else statements
dict[i] = 1 #assigning the value
71
50.Write a python program to catch
multiple handling in python.
#User can create string variable and take input
from user
string = input("Enter something here: ")
#using try function
try:
#User can create num variable and take
input from user
num = int(input("Enter a number here: "))
print(string + str(num)) # Convert num to
string before #concatenation
#using exception method and allies a
except(ValueError, TypeError) as a:
#using print statement
print(a)
72
51.Write a python program How to
print out without a newline.
73
return sum(1 for char in s if char in vowels)
#the user can create a variable string and take
input from the user.
string = input("Enter a string: ")
#using print statements
print("Number of vowels:",
count_vowels(string))
74
#using the return function for less number of
#n.
return fib_series[:n]
#user can create n variable and take user input
from user
n = int(input("Enter the number of terms:"))
#using print statement
print("Fibonacci series:", fibonacci(n))
75
#using return
return True
#user can create num variable and take input
#from user
num = int(input("Enter a number: "))
#using if statements
if is_prime(num):
#using print statement
print(num, "is prime")
else: #using else
print(num, "is not prime")
#using a print statement.
76
#using print statements for reversed_string
#variables.
print("Reversed String:", reversed_string)
77
#user can create variable #duck_numbers
#and assign empty list
duck_numbers = []
#using for loop with range
for num in range(start, end + 1):
#using if condition
if is_duck_number(num):
#using append method
duck_numbers.append(num)
#using the return function.
return duck_numbers
# Test the function
#user can create an variable start_range and
#take input from user
start_range = int(input("Enter the start of the
range: "))
#user can create an variable end_range and
#take input from the user.
end_range = int(input("Enter the end of the
range: "))
#using a print statement.
print("Duck numbers within the range",
start_range, "to", end_range, "are:")
#using print statements.
print(find_duck_numbers(start_range,
end_range))
78
57.Write a python program to Calculate
the power of a number.
79
print(f"{base} raised to the power of {exponent}
is {result}")
80
print("Square root of", num, "is", square_root)
81
60.Write a python program to Check if a
string is a valid email address.
#import re module
import re
#the user can create a function is_valid_email
with parameter email.
def is_valid_email(email):
#the user can create a variable pattern and
assign the value below.
pattern =
r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
$'
# using return with regular expressions.
return re.match(pattern, email) is not None
82
else: #using else with a print statement.
print(email, "is not a valid email address")
83
62. Write a program for inverted full
pyramid pattern by using Nested for
loop
#User can create a variable and take input
#from user for rows using input function
for i in range(0,n):
#for loop for spaces
for j in range(0,i):
print(" ",end="") # print for spaces
84
63. Write a program for Right half
pyramid pattern by using Nested for
loop
#User can create a variable and take input
#from user for rows using input function
n=int(input("enter any number for:"))
#using for loop with range of 0 and input
#number
for i in range(0,n):
for j in range(0,i+1):
print("*",end=" ") #print for stars
print() #empty print for new line
85
n=int(input("enter any number for:"))
#using for loop with range of 0 and input
#number
for i in range(0,n):
# this loop for spaces decrease
for j in range(0,n-(i+1)):
print(" ",end=" ") #print for spaces
for i in range(0,n):
86
# this loop for spaces decrease
for j in range(0,n-(i+1)):
for j1 in range(0,i+1):
print("*",end=" ") #print for stars
print() #empty print for new line
87
for j in range(1,row-i+1): #for spaces
print(" ", end="")
for j in range(1, 2*i): # for stars
print("*", end="")
print()
# Lower part of diamond
for i in range(row-1,0, -1):
for j in range(1,row-i+1): #for spaces
print(" ", end="")
88
def cube(num):
return num**3 #return for cube
89
#python program using a lambda function with
#reduce function
import functools
#importing functools
#creating list
A=[11,34,54,65,90,23]
#using print statement
90
if n==1: #using if statement
return n #return the vales
else: #using else
return n*recur_factorial(n-1) #return the
#value of multiply by recur_function n-1
#create variable and take input from user
num=int(input("enter any number:"))
#check if the number is negative
if num<0: #using if num is less than 0
print("sorry,factorial is does not exist for
negative numbers")
elif num==0: #Using elif num==0
print("the factorial of 0 is 1") #Print
#statement
else: #Using else
#print statement for factorial
print("the factorial
of",num,"is",recur_factorial(num)
91
a=arange(20,26) #creating variables and
#assigning range values
print(a) #print a
b=a[1:6:1] #slicing,initially:ending:step 1
print(b) #print b
b=a[1:6:2] #slicing,initially:ending:step 2
print(b) #print b
92
print(a) #print a
b=a[1:6:1] #slicing,initially:ending:step 1
print(b) #print b
93
import numpy as np
#creating array
x=np.array([[1,2,3],
[4,5,6],
[7,8,9]])
#transpose
#print the X_transpose variable
print("transpose array:\n",x_transpose)
94
x=np.array([[1,2,3],[4,5,6],[7,8,9]])
print("array is:\n",x) #print array
print(" ") #for spacing
95
#creating array
angles=np.array([3.14,3.14/2,6.28])
print("array is:\n",angles) #print original array
sine_of_angles=np.sin(angles) #creating
#variable and assign the sin(angles)
#print statements
print("sine of the given array of
angles=",sine_of_angles)
angles=np.array([3.14,3.14/2,6.28])
print("array is:\n",angles) #print original array
96
cosine_of_angles=np.cos(angles) #creating
#variable and assign the scos(angles)
#print statements
97
#checking order of i
98
77.Write a program for counting the
substring from string,using a for
loop.
#user can create any string like this
str="helloooooo"
#user can create substring
sub_str="ooo"
#create count variable for counting
count=0
#using for loop
for i in range(0,len(str)-2):
#using if for condition
if(str[i]=="o" and str[i:i+3]==sub_str):
count +=1 #assigning the count value
#with 1
#print the count values
print(count)
99
#user can create any variable and take input
100
temp=f_term+s_term #assigning value for
temp
f_term=s_term #assigning value for
f_term
s_term=temp #assigning value for
s_term
print(s_term) #print s_term
result=list(map(lambda x:2**x,range(terms+1)))
#using print statement for print the result
print(result)
101
#using for loop for iterating values
for i in range(terms+1):
#using print statement
print("the value of 2 raised to the
power",i,"is",result[i])
102
print(oct(decimal),"in octal ")
103
82.Write a python program to convert
Decimal to Binary using Recursion.
104
83.write a python program, How to
merge two dictionaries.
# User can create variable dict1 and make
dictionary 1
dict1 = {"abbas": 45, "rukhsar": 34, "hasan": 10}
# User can create another variable dict2 and
make dictionary 2
dict2 = {"sarjil": 22, "sufiyan": 25, "uvais": 20}
# Merge dictionaries using update() method
dict1.update(dict2)
# Print the merged dictionary
print(dict1)
105
85.Write a python program how to
slice a list in python.
#user can create variable a and apply list with
some name
a=["sarjil","sufiyan","asad","khalid","uvais","sal
man"]
106
86.Write a program to iterate over
Dictionaries using a for loop.
107
#using if condition and checklist
if not my_list:
#using print statement
print("the list is empty")
108
#using print statement
print("After removing 3:", my_list)
109
#using a print statement.
print("Simple interest:", simple_interest)
110
#the user can create an variable average and
#assign the function.
average = calculate_average(numbers)
#using print statement for average
print("Average:", average)
111