0% found this document useful (0 votes)
1 views

Python

The document provides an overview of various Python programming concepts including string manipulation, data structures (lists, dictionaries), exception handling, file operations, and object-oriented programming. It covers libraries such as random, requests, and CSV, as well as tools for testing and code formatting like pytest and black. Additionally, it discusses advanced topics like decorators, type hints, and command-line arguments.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python

The document provides an overview of various Python programming concepts including string manipulation, data structures (lists, dictionaries), exception handling, file operations, and object-oriented programming. It covers libraries such as random, requests, and CSV, as well as tools for testing and code formatting like pytest and black. Additionally, it discusses advanced topics like decorators, type hints, and command-line arguments.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

stack-overflow-developer-survey-2019

f=format string
, will give space automatically and + will not give any space

Escape Sequence

String Methods

From multiple string it capitalize only 1st character

From multiple string it capitalize each String 1st character


Both output is :

Function in Python

Conditional Statement

If,elif,else keyword
Match Keyword
Loops in Python
While Loop

For Loop
List
Dictionary

//Only Keys get Printed

None Keyword and List of Dictionary


o/p ###
###
###

Exception Handling
else block get only executed when try block executed successfully

All three are correct


pass keyword is used to pass or not doing any thing after catching the code

raise Keyword
Module or Library (We have to import it)

● random module

It generate the number between 1,10


statistic Library

Command-line argument

sys module
sys.argv

sys.exit
slices
Packages

pyPI (python Package Index) contains all the packages


pip is come with python used to install package

● cowsays package
Using pip install package_name : we can install package in the machine

pip install cowsay : It install package cowsay in the machine

Will print cow

Will print trex


APIs

requests package
pip install requests

JSON : Java Script Object Notation

-> python fileName.py Name_of_Singer


https://itunes.apple.com/search?entity=song&limit=50&term=shreya
Keyword

-> python second.py David


o/p :: hello David

__name__ will set __main__ only when we will call its file name where it present
If we are importing it in another file and executing other file name then __name__ is not
set to __main__ therefore the it will not call main() method
PEP 8 Python Enhancement Proposal

For Style Guide insall tool pylint or pycodestyle or black


pip install pylint
pip install black

And run command like


To formatting the code run the following command
black name.py
Unit Test in Python

● Assert

here square() is a function


● Pytest
pip install pytest and import pytest
We have to run using command like
pytest test_fname.py
Function should return some value for comparison so we can test
open Keyword

Create File if not present and open the file name.txt in


“w” write format //erase and write the file
“a” append format // append to the file
“r” to read the file

with Keyword

It automatically close the file we don’t need to close it explicitly

OR rstrip() is used to remove \n from the string


To get Sorted

In Ascending Order , Store in File and Print it

In Reverse Order , Store in File and Print it

For only printing from the file


Comma Seperated Value

student.csv

Unpacking the List


For Dictionary

Improving the above code and sorting it

Here I can’t sort it because students is a list and it contains dictionary and each having 2 keys
Inside dictionary name we have to pass Key name quotes ‘-‘ or “-”

Key : is used to give the way that in which way we have to sort it
Above code is sorting using key name in reverse order
Lambda Function

csv Library
Giving Column and Row Name

Here we can replace switch the position value

Reading it using DictReader

As it returning the Dict so we can write it like

Writing and Reading the file


pil library

Import sys
from PIL import Image
regexes Expression

Here @. Is also valid so we have to improve it

Here raj@.edu is also valid so we have to improve it

re library
For Email ex malan@harward.edu
.+@.+ //s@a —>malan@harward
..*@..* //b@a —>malan@harward

r is used for raw string to remove the \n like extra meaning function

Improving above code


Here s@@@d.edu is also correct ->improving it

Here .edu@something still getting pass and not showing any error

^ Start with any character


[^@]Should not contain this set of character
+@ Need @ symbol
[^@] Should not contain this set of character
\.edu$ edu should present at the end of the line
\w :shows the word character

_.EDU if capital then if will not work here we can directly make it lowercase white taking it as
input
And flags are

Here malan@cs50.harvard.edu is showing wrong as we can have multiple . dot

All types of email work this time


Made for user entering lastname comma firstname ex deshmukh, sanket or sanket deshmukh
o/p hello sanket
:= Assing and comparison //Walrus Operator

So we can write above code as

Que: Get twitter username from user


For getting twitter user

re.search(---)

https://twitter.com/sanketdeshmukh
\
Object Oriented Programming

Tuple : Tuple is immutable therefore we can call its value by indexing created using ( )
Tuple is not support item assignment/imutable so we can not change its value
after assign

List : Tuple is mutable therefore we can call its value by indexing created using [ ]
List support item assignment/mutable so we can change its value after assign

We can not change the value of Tuple

We can change the value of List


Dictionary : Dictionary are mutable so we can call its value use its keys
We can change the value of key in Dictionary
Classes and Object

Classes are mutable but we can make it immutable

. . . Says that developer is working Student work


Methods

_ _ init_ _ ( ) Method are special method which influence the value of variable
Its also called as Dunder Method / Instance Method

raise Keyword
If user enter the space instead of name
_ _ methods _ _

1. _ _ init _ _
2. _ _name_ _ = _ _main_ _
3. _ _str _ _

_ _str _ _ Method to print object from its referrence as it printing only the Memory reference
It take only one argument that is self
properties : Its an property used to control the flow of class i.e getter and setter

Decorators :

@property :- getter
@instanceVariableName.setter

When we try to assing the instance variable value then it internally called the setter method
In the following code the setter, getter name are same so we have to give identical name to
instance variable inside the getter and setter so we are using the _ operator to avoid error

(Not Understud) Learn IT Again

class Student:
def __init__(self,name,house):
if not name:
raise ValueError
self.name=name
self.house=house

def __str__(self):
return f"{self.name} is from {self.house}"

@property
def name(self):
return self._name

@name.setter
def name(self,name):
if not name:
raise ValueError("Missing name")
self._name=name

@property
def house(self):
return self._house

@house.setter
def house(self, house):
if house not in
["Griffindor","Hufflepuff","Ravenclaw","Slytherin"]:
raise ValueError("Invalid House")
self._house=house

def main():
student=get_student()
print(student)

def get_student():
name=input("Name : ")
house=input("House : ")
return Student(name,house)

if __name__=="__main__":
main()
class int(x, base=10)
class str(object=’ ‘)
str.lower()
str.strip([chars])

class list([iterable])
list.append(x)

class dict( _ _ _ )

print(type(50)) # <class ‘int’>


print(type(“Hello”) #<class ‘str’>
print(type([])) #<class ‘list’>
print(type(list())) #<class ‘list’>
print(type({})) #<class ‘dict’>
print(type(dict())) #<class ‘dict’>
Class Methods / Properties

@classmethod : Its is not instance method it is class method


For Instance Method self is a mandatory argument

Static Method
@staticmethod property

Above code is for instance variable

Follwing code is using the class method sort()


One more example with cls ans @classmethod

Inheritance
Method Overloading

object.__add__(self, others)
Set : No duplicate and sorted
global variable: We can read the global variable can not change it value
To modify the value of global variable we have to write
global variable_name

To modify the global variable


Using OOPs

constants : variable value that should not changed


We should write constant in CAPITAL language
We can change its value whenever we want but as it is capital so we its a constant and
we should not change
types hints

pip install mypy


mypy program is used to check that we are using correct assignment i.e we should not assing
string to int variable

After writing program we should run the following command


mypy program_name.py
Then execute/run the code

And you can use annotation to find error quickly using mypy

-> used to tell the return value of function None->It is not returning any thing

-> str # we are telling program that it is returning str

It is example of operator overloading


docstring :

“““ —””” Use to automate the documentation Here we use 3rd party tool to generate the
document like pdf
Command Line Argument

Single - for single character


Double -- for multiple character or string
-n says that the value of n is 3

argparse #ArgumentParser
Always run python program eding with -h //help
Unpacking

With List

To unpact it we have to pass it like *variable_Name for list

With Dictionary

For Dictionary we have to pass it as **

It passes value like

We can pass default value as shown in above picture if we are passing default value then we
can skip that argument as default value is present
*args : Takes variable no of positional argument ,
**kwargs : optional/ Named parameter

Positional (100, 50, 25)

Positional (100, 50, 25, 5)

It print value in the dictionary format

example
Map
map(function, iterable, …)
list comprehensions
filter

For sorting it
Dictionary Comprehensions

We can achieve this using following code as well

Now Using Dictionary Comprehensions

Enumerate

enumerate(iterable, start=0)

Can achieve this using


Generator : If program is not able to run due to large program data then we have to use
generator and yield

As it is generating large no. of data so it is not getting run.


yield is used to tell return every single value that is generating

Here it is generating one row and returning it and our for loop is not getting stop
Yield is returning iterator
_ concept
You have to learn
● String Function
● Maths Fuction
● Datatypes
● Csv library

You might also like