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

python-basics

The document covers basic Python programming concepts including if loops, file handling, list and dictionary comprehensions, object-oriented programming (OOP) principles, and the use of yield and lambda functions. It provides code examples demonstrating age checks, grading systems, file writing, salary adjustments, and class inheritance. Additionally, it illustrates encapsulation and polymorphism through examples involving animals and bank accounts.

Uploaded by

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

python-basics

The document covers basic Python programming concepts including if loops, file handling, list and dictionary comprehensions, object-oriented programming (OOP) principles, and the use of yield and lambda functions. It provides code examples demonstrating age checks, grading systems, file writing, salary adjustments, and class inheritance. Additionally, it illustrates encapsulation and polymorphism through examples involving animals and bank accounts.

Uploaded by

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

python-basics

June 23, 2025

1 If Loop
[4]: age = input('Please enter the age:')
age = int(age)

if age >=18 :
print('The person is an adult.')
print('Inside the if loop')
else:
print('The person is not an adult.')
print('Inside the else loop')
print('End of the program')

Please enter the age: 21


The person is an adult.
Inside the if loop
End of the program

[6]: score = 80
if score < 50:
print("Grade: C")
elif (score >= 50) and (score <= 80) :
print("Grade: B")
elif (score >= 80 ) and (score <=100):
print("Grade: A")
else:
print("Grade: NA")

Grade: B

[11]: # nested if loop


# divisibility rule of 6 .

num = 15

if num > 0 :
print('A valid number is entered, Thank you !!')

1
if num % 2 == 0 :
print('The number is divisible by 2')
if num % 3 == 0 :
print('The number is divisible by 3')
print('Hence the number is divisible by 6')
else :
print('The number is not divisible by 3')
print('Hence, the number is not divisible by 6')
else :
print('The number is not divisible by 2')
print('Hence, the number is not divisible by 6')
else:
print('Please enter a valid number')

A valid number is entered, Thank you !!


The number is not divisible by 2
Hence, the number is not divisible by 6

2 Write data into a file


[12]: fileobject = open( 'D:/Dump/Demo.txt' ,'w')
fileobject.write('This is some text created to test the write functionality of␣
↪python.')

fileobject.close()

[13]: fileobject = open( 'D:/Dump/Demo.txt' ,'w')


fileobject.write(' Writing some more text to the file')
fileobject.close()

[14]: fileobject = open( 'D:/Dump/Demo.txt' ,'a')


fileobject.write(' \n This is the appended text.')
fileobject.close()

[16]: #### Assignment


## In the above code where we checked the divisibility of 6 , try to add␣
↪entries into logs where we have the print commands.

import datetime
user = input('Please enter the user : ')
num = input('Please enter the number : ')
num = int(num)
# user = 'saanvi'
# num = 100
fileobject = open('D:/Dump/log.txt','a')
fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '|' +␣
↪user + '|*************************************************\n')

2
fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '|' +␣
↪user + '|The program begins\n')

if num > 0 :

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +␣


↪'|' + user + '|A valid number '+ str(num) +' is entered, Thank you !!\n')
if num % 2 == 0 :

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")␣


↪+ '|' + user + '|The number is divisible by 2\n')
if num % 3 == 0 :

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:


↪%S") + '|' + user + '|The number is divisible by 3\n')

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:


↪%S") + '|' + user + '|Hence the number is divisible by 6\n')

else :

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:


↪%S") + '|' + user + '|The number is not divisible by 3\n')
fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:
↪%S") + '|' + user + '|Hence, the number is not divisible by 6\n')

else :

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")␣


↪+ '|' + user + '|The number is not divisible by 2\n')

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")␣


↪+ '|' + user + '|Hence, the number is not divisible by 6\n')

else:
#print('Please enter a valid number')
fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +␣
↪'|' + user + '|Invalid number '+ str(num) +' entered\n')

fileobject.write( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '|' +␣


↪user + '|The program ends\n')

fileobject.close()

Please enter the user : xyz


Please enter the number : 21

3
3 List comprehension
[19]: salary = [ 34000,48000,56789,98345,52891 ]
increased_salary = []
for sal in salary:
increased_salary.append( round(sal * 1.1,2))
print(salary)
print(increased_salary)

[34000, 48000, 56789, 98345, 52891]


[37400.0, 52800.0, 62467.9, 108179.5, 58180.1]

[21]: increased_salary_1 = [ round(sal * 1.1,2) for sal in salary ]


print(increased_salary_1)

[37400.0, 52800.0, 62467.9, 108179.5, 58180.1]

[22]: # increase the salary by 10% if the salary is less than 50k else increase it by␣
↪5%

increased_salary_2 = [ round(sal * 1.1,2) if sal < 50000 else round(sal * 1.


↪05,2) for sal in salary ]

print(increased_salary_2)

[37400.0, 52800.0, 59628.45, 103262.25, 55535.55]

4 Dictionary comprehension
[28]: sample_dict = { 'name' : 'Ashok' , 'age': 56 , 'Profession' : 'Teacher'}
print(sample_dict)
print(sample_dict.keys())
print(sample_dict.values())

{'name': 'Ashok', 'age': 56, 'Profession': 'Teacher'}


dict_keys(['name', 'age', 'Profession'])
dict_values(['Ashok', 56, 'Teacher'])

[29]: # Traditional approach


numbers = [1, 2, 3, 4]
squared_dict = {}
for num in numbers:
squared_dict[num] = num ** 2
print(squared_dict)

{1: 1, 2: 4, 3: 9, 4: 16}

[31]: squared_dict_1 = { num : num ** 2 for num in numbers }


print(squared_dict_1)

4
{1: 1, 2: 4, 3: 9, 4: 16}

[41]: squared_dict_2 = { num : num ** 2 if num % 2 == 0 else num for num in␣
↪numbers }
print(squared_dict_2)

{1: 1, 2: 4, 3: 3, 4: 16}

[43]: squared_even_dict_3 = {num: num ** 2 for num in [1,2,3,4,5,6,7,8,9] if num % 2␣


↪== 0}

print(squared_even_dict_3)

{2: 4, 4: 16, 6: 36, 8: 64}

5 Object Oriented Programming - OOP concept


[62]: class Dog:
no_ears = 2
no_legs = 4
no_tails = 1
can_fly = False
is_mammal = True
is_fast = None

def sound(self,sound_animal):
print('The sound of the animal is ',sound_animal)

[63]: dalmatian = Dog()


print(dalmatian.no_ears)
print(dalmatian.no_tails)
print(dalmatian.can_fly)
dalmatian.has_spots = True
print(dalmatian.has_spots)
print(dalmatian.sound('barking'))
print('***************************************')
pomerian = Dog()
print(pomerian.no_ears)
print(pomerian.no_tails)
print(pomerian.can_fly)
pomerian.hairy = True
print(pomerian.hairy)
print(pomerian.sound('woof woof'))

2
1
False
True

5
The sound of the animal is barking
None
***************************************
2
1
False
True
The sound of the animal is woof woof
None

[77]: class Dog:


no_ears = 2
no_legs = 4
no_tails = 1
can_fly = False
is_mammal = True
is_fast = None

def __init__(self,name,breed):
print('Inside the constructor')
self.dog_name = name
self.dog_breed = breed

def sound(self,sound_animal):
print('The sound of the animal is ',sound_animal)
print('The name of the dog is ',self.dog_name)

[78]: my_dog = Dog('Friend', 'Golden Retriever')


print(my_dog.dog_name)
print(my_dog.dog_breed)
my_dog.sound('growl')

Inside the constructor


Friend
Golden Retriever
The sound of the animal is growl
The name of the dog is Friend

5.0.1 Inheritence
[85]: class Animal :
def __init__(self,name):
self.animal_name = name
def speak(self):
print(f"{self.animal_name} makes some sound")

class Dog(Animal):
def speak(self):

6
print(f"{self.animal_name} makes woof woof sound")

class Cat(Animal):
def speak(self):
print(f"{self.animal_name} makes meow sound")

[86]: # Create objects


dog = Dog("Buddy")
cat = Cat("Whiskers")
generic_animal = Animal("Some Animal")

[89]: print(generic_animal.speak())
print(dog.speak())
print(cat.speak())

Some Animal makes some sound


None
Buddy makes woof woof sound
None
Whiskers makes meow sound
None

5.0.2 Polymorphism

[91]: class Dog:


def speak(self):
return 'Woof!'

class Cat:
def speak(self):
return 'Meow'

class Cow:
def speak(self):
return "Moo!"

[94]: dog = Dog()


cat = Cat()
cow = Cow()

print('Dog speaks', dog.speak())


print('Cat speaks', cat.speak())
print('Cow speaks', cow.speak())

Dog speaks Woof!


Cat speaks Meow
Cow speaks Moo!

7
5.0.3 Encapsulation

[100]: class BankAccount:


def __init__(self, balance,username):
self.__acc_balance = balance # Private attribute
self.user_name = username

def deposit(self, amount):


if amount > 0:
self.__acc_balance += amount
return self.__acc_balance

[102]: account = BankAccount(1000,'Satish')


print(account.deposit(500)) # Output: 1500

print(account.user_name)
#print(account.__acc_balance) # Error: AttributeError

1500
Satish

6 Yield
[110]: def countdown(n):
i = 1
while i <= n:
yield i
i += 1

[111]: for number in countdown(5):


print(number)

1
2
3
4
5

[ ]: ## lambda function

[115]: multiply = lambda x, y: x * y


print(multiply(5, 6))

30

[ ]:

You might also like