a = input("Enter you name:")
print("Hello",a)
a = input("Enter a number.")
print(a, type(a))
a = int(input("Enter a number"))
b = int(input("Enter another number"))
print("Sum of both the numbers is: ", a+b)
#keyword argument
def func(n, m):
print("n = " + str(n))
print("m = " + str(m))
func(5, 10)
print('\n')
# We can mess with the default order of arguments while calling the funciton if we use keyword arguments
func(m=5, n=10)
n = 5
m = 10
n = 10
m = 5
def factorial(num):
if num == 1: #base case
return 1
return num * factorial(num - 1)
print(factorial(5))
120
# variable no. of arguments (*args)
def func(*args):
# args is tuple with the argument
for i in args:
print(i)
func('hello', 'to', 'python', 'class', 'for', 'first', 'years')
print()
def my_print(*not_necessarily_args):
for i in not_necessarily_args:
print(i)
my_print('hello', 'my', 'name', 'is', 'bin'+'bash')
hello
to
python
class
for
first
years
hello
my
name
is
binbash
# variable no. of keyword arguments (**kwargs)
def func(**kwargs):
for key, values in kwargs.items():
print(key, values)
func(hello='to', python='class', year='first')
print("-"*40)
def kw_args_func(**not_necessarily_kwargs):
for key, value in not_necessarily_kwargs.items():
print('key:', key, ' ', 'value:', value)
kw_args_func(sep='/', end='*', name='bin')
hello to
python class
year first
----------------------------------------
key: sep value: /
key: end value: *
key: name value: bin
# This will give a error
def ff(*args, **kwargs, name):
for arg in args:
print(args)
for key,value in kwargs.items():
print(key, ": ", value)
print("Name: ", name)
ff(10, "Hello", ran=20, "Foo Bar")
File "<ipython-input-39-938320840b18>", line 2
def ff(*args, **kwargs, name):
^
SyntaxError: invalid syntax
lambda arguments: expression
# Program to show the use of lambda functions
double = lambda x: x * 2
# Output: 10
print(double(5))
10
# Program to filter out only the even items from a list using filter()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
# Output: [4, 6, 8, 12]
print(new_list)
[4, 6, 8, 12]
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)
[2, 10, 8, 12, 16, 22, 6, 24]
from Game.Sound.load import volume_up
.# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(0,9))
### Minimal Example Class
class Car:
pass
c1 = Car()
c1.name = "Model 3"
c1.company = "Tesla"
print(c1)
print(c1.name)
print(c1.company)
class Car:
def __init__(self, car_model, car_company, car_color):
# Initialising Propertis Specific to the object.
self.model = car_model
self.company = car_company
self.color = car_color
def get_color(self):
# Instance Method
return self.color
def set_color(self, new_color):
# Instance Method
self.color = new_color
# Instantiating an Object or Creating an Object
my_car = Car("Model S", "Tesla", "Maroon") # my_car is an instance/object of Car Class.
__fun__()
: “dunder” syntax in python means some special variable/method in python. Example - __init__()
, __str__()
method, __file__
, __dict__
property etc.__init__()
: constructor method of a class. A method to specify properties/attributes of an object along with declarationn of the object. In other words __init__()
method sets the initial state of the object by assigning the values of the object’s properties.class Car:
wheels = 4 # Class Variable/attribute
def _init_(self, company): # Constructor method
self.company = company
def get_company(self): # Instance Method
return self.company
def get_wheels(self): # Instance methods
return Car.wheels
my_car = Car("Tesla")
my_car = Car("Tesla")
print(my_car._dict_) # Print the Properties associated with an object as a dictionary
print(my_car.get_company()) # Actually Treated as:- print(Car.get_company(my_car))
print(my_car.get_wheels())
instance
reference as their first positional argument. Which is automatically passed when we call an instance method. Example - obj_name.instance_method()
is treated as ClassName.instance_method(obj_name)
.self
argument. So, we can access the instance variable using self.var_name
inside a method.@classmethod
decorator over a function definition is used to define a class method.class
as their first positional argument. Which is automatically passed when we call a class-method. e.g. ClassName.class_method_name()cls
argument. So, we can access the Class variable using cls.var_name inside a method.### Car Class Example
class Car:
wheels = 4 # Class Variable/attribute
def _init_(self, company): # Constructor method
self.company = company
def get_company(self): # Instance Method
return self.company
def get_wheels(self): # Instance methods
return Car.wheels
@classmethod
def about(cls): # Class Method
return "This is the Blue-Print of a Car having " + str(cls.wheels) + " wheels."
print(Car.about())
# You can call a class-method using an instance but as an instance never stores a classmethod. So, Car.about() is called.
print(my_car.about())
ClassName.static_method_fun()
, InstanceName.static_method_fun()
.# Static Methods
class Car:
wheels = 4 # Class Variable/attribute
def _init_(self, company):
print(self)
self.company = company
def get_company(self): # Instance Method
return self.company
def get_wheels(self): # Instance methods
return Car.wheels
@classmethod
def about(cls):
return "This is the Blue-Print of a Car having " + str(cls.wheels) + " wheels."
@staticmethod
def calculate_fuel_amount(cost_per_litre, amount_paid):
# A uitility Function.
return amount_paid/cost_per_litre
my_car = Car("Tesla")
fuel_amount = Car.calculate_fuel_amount(90, 900)
# fuel_amount = my_car.calculate_fuel_amount(90, 900)
print(fuel_amount, "Litres")
In this, we will talk about files that store data.
There are two types of data files:
Attribute | Description |
---|---|
file.closed | Returns true if file is closed, false otherwise. |
file.mode | Returns access mode with which file was opened. |
file.name | Returns name of the file. |
To open a file in our program we have a function named open().
<file_objectname> = open(<filename>)
<file_objectname> = open(<filename>, <mode>)
a = open("myFile.txt", "r") # File Opened in read mode
b = open("list.txt", "w") # File opened in the write mode
Text Files | Binary Files | Function | Description |
---|---|---|---|
‘r’ | ‘rb’ | read | File must exist, else error |
‘w’ | ‘wb’ | write | If file exist overwrite, else create new file |
‘r+’ | ‘r+b’ or ‘rb+’ | read and write | File must exist, else error. Both read and write works |
‘w+’ | ‘w+b’ or ‘wb+’ | write and read | If file exist overwrite, else not create new file. Both read and write works |
‘a’ | ‘ab’ | append | Same as ‘write’, data is not overwritten. It’s appended. |
‘a+’ | ‘a+b’ or ‘ab+’ | append and read | Same as ‘write’ data is not overwritten. It’s appended. Both read and write works |
f = open("list.txt") # file is opened
result = f.read()
print(result) # will print the whole file.
result = f.read(10)
print(result) # will print only the first 10 bytes i.e 10 characters of the file.
Note: 1 character has size of 1 bytes.
The readline() function: returns n bytes from the file. if n not given, returns all the bytes from one line.
f = open("list.txt") # file is opened
result = f.readline()
print(result) # will print the first line
result = f.realine(3)
print(result) # will print first 3 characters of second line.
result = f.readline()
print(result) # will print the remaining part of second line.
Note: readline() automatically add “\n” on the end of every string that it returns
The readlines() function: return all the lines in a from of list
f = open("list.txt")
result = f.readlines()
print(result) # will print list of lines
There’s an alternate way to read line by line
f = open("list.txt)
for i in f:
print(i) # i iterates till "\n", which was the delimiter.
# It's same as:
s = f.readline()
while s:
print(s)
s = f.readline()
with open("file.txt", 'w') as f:
f.write("Hello World!!)
When you open a file python creates an file object i.e some memory has been allocated to the file object if we forgot to clean this memory it can cause memory leak (we clean this memory by calling close() method i.e f.close()). But in case of with keyword when the code comes out the block scope of the with keyword it will automatically close the file object i.e clean the memory which was allocated to the file
writes string
f = open("list.txt", 'w')
f.write("Hello World!")
writes all string from the list
f = open("list.txt", 'w')
todo = ["Coding", "Binge Watching", "Football"]
f.writelines(todo)
A file pointer tells the current position in the file where reading or writing will take place.
try:
block.except:
statement, followed by a block of code which handles the problem as elegantly as possible.try:
# Runs first
< code >
except:
# If there is exception, then execute this block.
< code >
else:
# If there is no exception then execute this block.
<code>
finally:
# This code always executes
< code >
def divide(a,b):
try:
ans = a / b
except ZeroDivisionError:
print("Trying to divide by zero")
ans = float("Inf")
finally:
print("Division successful")
return ans