0% found this document useful (0 votes)
3 views20 pages

Python - Copy

The document provides a comprehensive overview of Python programming concepts, including basic syntax, variables, data types, operators, comments, user input, and control structures. It covers advanced topics such as lists, tuples, dictionaries, and sets, along with practical exercises for each section. Additionally, it emphasizes the importance of identifiers, type conversion, and string manipulation in Python.

Uploaded by

KRISHNA GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Python - Copy

The document provides a comprehensive overview of Python programming concepts, including basic syntax, variables, data types, operators, comments, user input, and control structures. It covers advanced topics such as lists, tuples, dictionaries, and sets, along with practical exercises for each section. Additionally, it emphasizes the importance of identifiers, type conversion, and string manipulation in Python.

Uploaded by

KRISHNA GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 20

1.

First Program:

print("hello world")

2.Variables:

variable = value
print(variable)

Ex:
name = Kuro
print(name)

## A variable can be used as a value in another variable


>>Rules for Identifiers:
1. Identifiers can be combination of uppercase and lowercase letters,digits or an
underscore (_) So myVariable, Variable1, variable_for_ print are all valid python
identifiers
2. An Identifier can not start with digit. So while variable1 is valid, 1variable
is not.
3.We can't use special symbols like !,@,#,$etc.. in our identifier
4.Identifier can be of any length.

3.Data Types:

1.String = Any sentence or a word or even a letter written in English. These are
always written in ("_")or('_')
ex = "Krishna" or 'Hello world'
2.Integer = Any integer whether it is -ve or +ve
ex = 25,-25,0
3.Float = Used to represent decimal data
ex = 2.33, 4.89
4.Boolean = It only has two value either True or False
5.None = It represents one value which itself has no value called None
##Keywords = These are reserved words used in python like capital T true or
capital F false or lambda
##Python is case-sensitive language which means Uppercase words act as different
syntax than lowercase even if the words are same.
##Float is superior than int as it carries more value than int

Exercise:
Print Sum:

a = 2
b = 3
sum = a + b
print(sum)

4. Comments:

Comments are sentences which are not supposed to be a part of the final code these
are written to classify or to have a organised or clean code.
These are used with placing a # in ahead of sentence.

5.Types of Operators:
An Operator is a symbol that performs a certain operation between operands.
i) Arithmetic Operators = +, -, *, /, %, **
ii) Relational / Comparision Operators = ==, !=, >, <, >=, <=
iii) Assignment Operators = =, +=, -=, *=, /=, %=, **=
iv) Logical Operators = not, and, or

Ex:
Assignment Operators:
a = 30
b = 40
c = 2
d = 5
e = 10
f = 3

a += 10
b -= 10
c *= 10
d /= 10
e %= 10
f **= 10
print(a, b, c, d, e, f)

Logical Operators (works on the same concept of logic gates):


val1 = True
val2 = False
print(val1 and val2)
print(val1 or val2)
print(not val1)

6. Type Conversion:
It refers to change in a specific type of variable into another type of variable.
Like if we add a integer value in a variable in the the form of a string and do an
arithmatic operation on it, it will show a runtime error.
to fix these we can refer to this example:

Code:
a = "2"
b = 3
sum = a + b
print(sum)

Run:
error

Code:
a = int("2")
b = 3
sum = a + b
print(sum)

Run:
5

Use of type casting:


adding a variable1(variable2)
7.User Input:
This statement helps the code to ask for input from the user
input() statement is used to accept values (using keyboard) from user
input() #result for input() is always a str
int ( input() ) #int
float (input() ) #float

##using only input for a variable the type of data will be of string class to get
rid of this and let's say we want int class we can write:
val = int(input("enter value"))
print(val)

Now this will be of int class.

Practise Question:
Write a program to input 2 numbers and print their sum.

a = int(input("Enter Your First Number "))


b = int(input("Enter Your Second Number "))
sum = a + b
print(sum)

Write a program to input side of a square and print it's area.

side = int(input("Enter your side "))


area = side * side
print(area)

Write a program to input 2 floating point numbers and print their average.

a = float(input("Enter your first number "))


b = float(input("Enter your second number "))
average = (a + b)/2
print(average)

Write a program to input 2 int numbers, a and b.


Print True if a is greater than or equal to b. If not print False.

a = int(input("Enter your first number "))


b = int(input("Enter your second number "))
print(a >= b)

8. Strings:

String is data type that stores a sequence of characters.


##Escape Sequence Characters:
These are used to format the code which the system doesn't directly understand
ex:
If we want print("hello world . This is a string")
but we also want that ("hello world") and ("This is a string") two be written two
seperate linesthen what we do is
we will write :
print("hello world . \n This is a string ") \n represents next line

Basic Operations:
i) concatenation:
"hello" + "world" ---> "helloworld"
ii) length of str:
len(str)
##length counts not only characters but also spaces

A.) Indexing:
Index here refers to the position of a character int the total outcome starting
from 0

ex:
A P N A _ H O S T E L ----> String
0 1 2 3 4 5 6 7 8 9 10 11 ---> Indexing

str = "APNA HOSTEL"


print(str[0])

Run:
A

B.) Slicing:
Accessing parts of a string

str[starting_idx : ending_idx]

str = "APNA HOSTEL"


str[1 : 4] is "pna"

##Negative Index:
A P P L E ---> String
-5 -4 -3 -2 -1 ---> Negative Indexing

str = "APPLE"
print(str[-3 : -1])

Run:
PL

C.) String Functions:

str = "I am a coder."


str.endswith("er.") #returns true if string ends with substr
str.capitalize() #capitalizes 1st char
str.replace(old, new) #replaces all occurances of old with new
str.find(word) #returns 1st index of 1st occurrence
str.count("am") #counts the occurrence of substr in string

Ex:
str = "i am studying python from Apna College"
str =str.capitalize()
print(str)
print(str)
print(str.count("o"))
print(str.find("o"))
print(str.replace("python" , "javascript"))

Practise Questions:
Write a program to input user's first name & print its length.

name = input("Enter your name: ")


print(len(name))
Write a program to find the occurance of '$' in a String.

Class = "Niggesh Nangey does not have any $ "


print(Class.count("$"))

9.) Conditional Statements:


(SYNTAX) = if-elif-else

if(condition) :
Statement1
elif(condition) :
Statement2
else(condition) :
StatementN

Ex:

age = int(input("Enter your age: "))


if(age >= 18) :
print("Eligible to vote")
elif(age <= 18) :
print("Not Eligible")

##If I want that if and any specific elif statement to be always true I will just
write True in the condition statement
##You can write if or elif statement any number of times you want but you can only
write else once
##Nesting is possible in if and else statements in python

Ex:

marks = int(input("Enter your marks: "))


if(marks >= 90) :
print("Grade = A")
elif(marks >= 80) :
print("Grade = B")
elif(marks >= 70) :
print("Grade = C")
else :
print("Grade = D")

Practise Questions:
Write a program to check if a number entered by the user is odd or even.

number = int(input("Enter your number: "))


if(number % 2 == 0) :
print("Even")
elif(-2 < number < 2) :
print("Invalid")
else :
print("Odd")

Write a program to find the greatest of 3 numbers entered by the user.

num1 = (input("Enter your first number: "))


num2 = (input("Enter your second number: "))
num3 = (input("Enter your third number: "))
if(num1 > num2 and num1 > num3) :
print("The greatest of them all is:" , num1)
elif(num2 > num3) :
print("The greatest of them all is:" , num2)
else :
print("The greatest of them all is:" , num3)

Write a program to check if a number is a multiple of 7 or not.

number = int(input("Enter your number: "))


if(number % 7 == 0) :
print("True")
else :
print("False")

10.) Lists:
A built-in data types that stores set of values
It can store elements of different types (integer, float, string, etc..)

Ex:

marks = [94.4, 95.3, 87.6]


print(marks)

Run:
[94.4, 95.3, 87.6]

##Difference of lists and strings is that strings are immutable while list are
mutable which means item assignment is possible in list while it isn't possible in
string.
Ex:

marks = [Karan, 85, True]


print(marks[2])
marks[2] = "Lucky"
print(marks)

A.) List Slicing:


Similar to String Slicing

list_name[starting_idx : ending_idx]

Ex:

marks = [85, 78, 63]


print(marks[1 : 2])

Run:
[78, 63]

B.) List Methods:

list = [1, 2, 3]
list.append(4) #adds one element at the end
list.sort() #sorts in ascending order
list.sort(reverse = True) #sorts in descending order
list.reverse() #reverses list
list.insert(idx, el) #insert element at index
list.remove(1) #removes first occurance of element
list.pop( idx ) #removes element at idx

Ex:

list = [1, 2, 3]
# print(list.append(5))
# print(list)
# print(list.sort())
# print(list)
# print(list.sort( reverse = True))
# print(list)
# list.reverse()
# print(list)
# list.insert(1, 5)
# print(list)
# list.remove(1)
# print(list)
# list.pop(1)
# print(list)

11.) Tuples:
A built-in data type that lets us create immutable sequences of values.
##Difference between list and tuple is that lists are mutable while as tuples are
not.

SYNTAX:
tup = (2, 1, 3, 4)
print(tup[3])

Run:
4

#Empty Tuple:
tup = ()
print(tup)

A.) Tuple Slicing:


Same as String and list Slicing

B.) Tuple Methods:


tup = (2, 1, 3, 4)
tup.index(el) #returns index of first occurrence
tup.count(el) #counts total occurences

Practise Questions:

Write a program to ask user to enter names of their 3 favorite movies & store them
in a list.

name1 = input("Enter the name of the 1st movie: ")


name2 = input("Enter the name of the 2nd movie: ")
name3 = input("Enter the name of the 3rd movie: ")
list = [name1, name2, name3]
print(list)

Write a program to check if a list contains a palindrome of elements.

list = [1, 2, 3, 2, 1]
copy_list = list.copy()
if(copy_list == list) :
print(True)
else :
print(False)

Write a program the number of students with the "A" grade in the following tuple.

("C", "D", "A", "A", "B", "B", "A")

tup = ("C", "D", "A", "A", "B", "B", "A")


print(tup.count("A"))

Write a program to Store the values in a list & sort them from "A" to "D".

list = ["C", "D", "A", "A", "B", "B", "A"]


list.sort()
print(list)

12.)Dictionaries:
Dictionaries are used to store data values in key:value pairs
They are unordered, mutable(changeable) & don't allow duplicate keys.

SYNTAX:
dict = {
"name" : "krishna",
"cgpa" : 9.6,
"marks" : [98, 97, 95],
}

"key" : value
dict["name"], dict["cgpa"], dict["marks"]
dict["key"] = "value" #to assign or add new

Ex:
info = {
"key" : "value",
"name" : "krishna",
"age" : 98,
"marks" : 94.4,
"subjects" : ["maths", "science"],
}
print(info)
print(info["subjects"])

A.) Nested Dictionaries:

SYNTAX Example:
student = {
"name" : "krishna",
"score" : {
"chem" : 98,
"phy" : 97,
"math" : 95
}
}
print(student["score"]["chem"])

Run:
98

B.) Dictionary Methods:

my.Dict.keys() #returns all keys


my.Dict.values() #returns all values
my.Dict.items() #returns all (key, val) pairs as tuples
my.Dict.get("key"" ) #returns the key according to value
my.Dict.update(newDict ) #inserts the specified items to the dictionaries

Ex:

student = {
"name" : "Krishna",
"score" : {
"chem" : 98,
"phy" : 95,
"math" : 90,
}
}
# print(student["score"]["chem"])
# print(student.keys())
# print(student.values())
# print(student.items())
# print(student.get("name"))

# student.update({"city": "Vadodara"}) <-----This can be written in two forms


# print(student)

# new_Dict = {"city" : "Vadodara"} <-----This is the other way


# student.update(new_Dict)
# print(student)

13.) Sets:
Set is the collection of the unordered items.
Each elements in the set must be unique & immutable.
Sets itself are mutable but it's elements are immutable
Only immutable objects can be added to the set as it has a hashable value and hence
mutable object can be registered

nums = {1, 2, 3, 4 }
set2 = {1, 2, 2, 2, }
#repeated elements stored only once, so it resolved to {1, 2 }
null_set = set() #empty set syntax
#since it is immutable it cannot store lists or dictionaries in it.
#difference btw an empty set or empty dictionary is it's syntax:
Empty Set:
collection = set()
Empty Dictionary:
collection = {}

Ex:
collection = {1, 2, "Hello", 3, 4 }
print(collection)

A.) Set Methods:


set.add(el) #adds an element
set.remove(el) #removes the element
set.clear() #empties the set
set.pop() #removes a random value

Ex:
collection = {1, 2, "Hello", 3, 4 }
# collection.add(7)
# collection.add("world")
# collection.add(8)
# collection.remove(1)
# print(collection)
# collection.clear()
# print(collection)
# collection.pop()
# print(collection)

set.union(set2) #combines both set values & returns new


set.intersection(set2) #combines common values & returns new

Ex:
set1 = {1, 2, 3 }
set2 = {2, 3, 4 }
print(set1.union(set2))
print(set1.intersection(set2))

Practise Questions:

Store following word meanings in a python dictionary :


table : "a piece of furniture", "list of facts & figures"
cat : "a small animal"

words = {
"table" : ["a piece of furniture" , "list of facts and figures"],
"cat" : "a small animal"
}
print(words)

You are given a list of subjects for students. Assume one classroom is required for
1 subject. How many classrooms are needed by all students. List:
"python","java","C+
+","python","javascript","java","python","java","C++","C"

set = { "python" , "java" , "C++" , "python" , "javascript" , "java" , "python" ,


"java" , "C++" , "C" }
total_classrooms = len(set)
print(total_classrooms)

Write a program to enter marks of 3 subjects from the user and store them in a
dictionary. Start with an empty dictionary & add one by one. Use subject name as
key & marks as value.

math = int(input("Enter your maths marks: "))


physics = int(input("Enter your physics marks: "))
chemistry = int(input("Enter your chemistry marks: "))
dict = {}
dict.update({"math" : math})
dict.update({"physics" : physics})
dict.update({"chemistry" : chemistry})
print(dict)
Figure out a way to store 9 & 9.0 as separate values in the set.

set = float({9, 9.0})


print(set)

2nd Way:

set = {
("float" : 9.0),
("int" : 9)
}
print(set)

14.) Loops:
Loops are used to repeat instructions.

i.) while Loops:


SYNTAX:
while condition :
#some work

Ex:
We want to print hello 5 times:

count = 1
while count <= 5 :
print("Hello")
count += 1

Practise Condition:

Print numbers 1 to 100.

i = 1
while i<=100 :
print(i)
i+=1

Print numbers from 100 to 1.

i = 100
while i>=1 :
print(i)
i-=1

Print the multiplication table of a number n.

n = int(input("Enter your number: "))


i = 1
while i <= 10 :
print(i * n)
i+=1

Print the elements of the following list using a loop.


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

num = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


idx = 0
while idx < len(num) :
print(num[idx])
idx+=1

Search for a number x in this tuple using loop.{x = 36}


(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)

num = (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)


x = 36
i = 0
while i < len(num) :
if(num[i] == x) :
print(i)
i+=1

A.) Break & Continue:


Break: used to terminate the loop when encountered.
Continue: terminates execution in the current iteration & continues execution of
the loop with the next iteration.
##Continue acts as skip

Ex:
i = 1
while i <= 5 :
print(i)
if(i == 3) :
break
i += 1

Ex:
i = 0
while i <= 5 :
if(i == 3) :
i += 1
continue
print(i)
i += 1

ii.) For Loop:


These loops are used for sequential traversal. For traversing list, string, tuples
etc..
for loops(SYNTAX):

for el in list:
#some work

Ex:
list = [1, 2, 3]

for el in list:
print(el)

Practise Questions:

Print the elements of the following list using a loop:


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
list = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

for val in list :


print(val)

Search for a number x in this tuple using a loop:{x = 49}


(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)

tup = (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)


x = 49
idx = 0
for val in tup :
if(val == x) :
print("Found at idx: ", idx)
break
idx += 1

A.) Range():
Range functions returns a sequence of numbers, starting from 0 by default, and
increments by 1(by default), and stops before a specified number.

SYNTAX:
range(start?, stop, step?)

Ex:
for el in range(5) :
print(el)
for el in range(1, 5) :
print(el)
for el in range(1, 5, 2) :
print(el)

Practise Questions:

Print numbers from 1 to 100:

for el in range(101) :
print(el)

Print numbers from 100 to 1.

for el in range(100, 0, -1) :


print(el)

Print the multiplication table of a number n.

num = int(input("Enter your number: "))


table = num * 10

for el in range(num, table, num) :


print(el)

B.) Pass Statement:


pass is a null statement thet does nothing . It is used as a placeholder for
future code.

SYNTAX:
for el in range(10) :
pass

Ex:

for el in range(10):
pass

print("hello")

Run:
hello

Practise Questions:

Write a program to find the sum of first n numbers. (using while)

num = int(input("Enter your number: "))


sum = 0
i = 1
while i <= num:
sum = sum + i
i += 1
print("Sum of first", num, "numbers is:", sum)
## If you want to print only the final sum then make sure the print statement is
not indented in the while condition.

Write a program to find the factorial of the first n numbers. (using for)

num = int(input("Enter your number: "))


mul = 1
i = 1
for el in range(num) :
mul = mul * i
i+=1

print(mul)

15.) Functions and Recursion:


Functions:
Block of statements that perform a specefic task.

Syntax:

def_func_name(param1, param2, param3 ......) :


#some work
return val

func_name(arg1, arg2, arg3...) #function call

Ex:

def sum(a, b) :
s = a + b
return s

print(sum(2, 3))
A.) Types of Functions:
i) Built-in Functions:
a) print()
b) len()
c) type()
d) range()

ii) User defined Functions


#Default Parameters : Assigning a default value to parameter, which is used when no
argument is passed.

Let's Practise :

Write a function to print the length of a list. (list is the parameter).

list_a = [1, 2, 3, 4, 5]

def print_li(list) :
print(len(list))

print_li(list_a)

Write a function to print the elements of a list in a single line. (list is the
parameter).

list_a = [1, 2, 3, 4, 5]

def print_el(list) :
for val in list :
print(val , end=" ")

print_el(list_a)

Write a function to find the factorial of n.

n = int(input("Enter your number: "))

def factorial(num) :
mul = 1
i = 1
for el in range(num):
mul = mul * i
i+=1
print(mul)

factorial(n)

Write a function to convert USD into INR:

num = int(input("Enter your Number: "))

def convert(number) :
con = number * 85
print(con)

convert(num)

Recursion:
When a function calls itself repeatedly :

Syntax & Example :


#prints n to 1 backwards

def show(n) :
if(n == 0) :
return
print(n)
show(n-1)

#returns n!

def show(n) :
if(n == 0 or n ==1) :
return 1
else :
return n * show(n - 1)

Write a recursive function to calculate the sum of first n natural numbers.

num = int(input("Enter your Number: "))

def show(n):
if n == 0:
return 0
else:
return n + show(n - 1)

print(show(num))

Write a recursive function to print all elements in a list.

list_a = [1, 2, 3, 4, 5, 6]

def print_el(list, idx) :


if(idx == len(list)) :
return
print(list[idx])
print_el(list, idx + 1)

print_el(list_a, 6)

Exercises:
A) Questions on Conditionals:
1) Classify a person's age group : Child(<13), Teenager(13-19), Adult(20-59),
Senior(60+).

age = int(input("Enter your age: "))

if(age < 13) :


print("Child")
elif(age < 20) :
print("Teenager")
elif(age < 60) :
print("Adult")
else :
print("Senior")
2) Movie tickets are priced based on age: $12 for adults(18 and above), $8 for
children. Everyone gets a $2 discount on
Wednesday.

age = int(input("Enter your age: "))


day = input("Enter the day: ")

if(age < 18) :


if(day == "Wednesday") :
print("Ticket fee : $6")
else :
print("Ticket Fee : $8")
else :
if(day == "Wednesday") :
print("Ticket fee : $10")
else :
print("Ticket Fee : $12")

3) Assign a letter grade based on a student's score: A(90-100), B(80-89), C(70-


79), D(60-69), F(below 60).

marks = int(input("Enter your marks: "))

if(marks >= 90):


print("Grade : A")
elif(marks >= 80):
print("Grade : B")
elif(marks >= 70):
print("Grade : C")
elif(marks >= 60):
print("Grade : D")
else :
print("Grade : F")

B) Questions on Loops:
1) Given a list of numbers, count how many are positive.
numbers = [1, -2, 3, -4, 5, 6, -7, -8, 9, 10]

numbers = [1, -2, 3, -4, 5, 6, -7, -8, 9, 10]


i = 0
for el in numbers :
if(el > 0) :
i+=1
print(i)

2) Calculate the sum of even numbers up to a given number n.

n = int(input("Enter your number: "))


i = 1
sum = 0
for i in range(n+1) :
if i % 2 == 0 :
sum = sum + i
i+=1
print(sum)

3) Print a multiplication table for a given number up to 10. but skip the fifth
iteration.
num = int(input("Enter your number: "))
i = 0
for i in range(10):
if i == 4 :
continue
i+=1
print(num * i)

4) Reverse a String using a loop:

input_str = "Python"
reversed_str = ""

for char in input_str :


reversed_str = char + reversed_str

print(reversed_str)

5) Given a string, find the first non-repeated character.

input_str = "tweeter"

for char in input_str :


if input_str.count(char) == 1:
print("Char is : ", char)
break

6) Compute the factorial of a number using a while loop.

num = int(input("Enter your number: "))


i = 1
mul = 1
while i <= num :
mul = mul * i
i+=1
print(mul)

7) Keep asking the user for input until they enter a number between 1 and 10.

while True :
input_num = int(input("Enter your number: "))
if 1 <= input_num <= 10 :
print(input_num)
break
else :
print("Invalid")

16) File I/O :


Python can be used to perform operations on a file. (read & write data)

Types of all files:


i) Text files : .txt, .docx, .log, etc..
ii) Binary files : .mp4, mp3, .mov, .png, .jpeg, etc...

A) Open, read & close File:


We have to open a file before reading or writing.
SYNTAX:
f = open("file_name", "mode")

## file_name = sample.txt , demo.docx


## mode = r : read mode, w : write mode

data = f.read()
f.close()

Example :

f = open("demo.txt" , "r")
data = f.read()
print(data)
f.close()

You might also like