Python
Python
Python is a very easy language comapre with c++and Java any other language. It very Easy to learn and code also have a possiblity .
Python basic programming
Print is a statement
1. Print(āPython is easyā)
Print (āhrfcreationā)
2. String - Series of character
3. Integer -WIthout using decimal point
4. Python will run line by line ex: if you give a 1
st statement value is 10 and next
statement value is 20 it will execute line by line defenitely 2
nd
line statement 20 will
be print as a output;
Price =10
Price =20
Print(āPriceā)
Question 1
Ask a person name :
name = input (āWhat is your name? ā)
Print (āHIā +name )
Output
Question 2
Ask a person name and favourite colur and print a message like āthe so and so
person like the so ans so colour? ā(note :after a question mark need a space )
name = input(āWhat is your name? ā)
favourite_colour = input(āWhat is your favourite colour ā)
Print(name +ālikesā+favourite colour)
Output
Question 3
Ask a person biirth year and subtract with the current year and print person age as a
output
birth _year =input(āBirth year: ā)
Print(type(birth_year))
age=2019 - int(birth_year)
Print(type(age))
Print(age)
Output
Queston 4
Ask a user weight in pounds convert in to kilogram and print on the terminal
weight_lbs =input(āweight(lbs): ā)
weight_kg=int(weight_lbs)*0.45
Print(weight_kg)
course = āPython for Beginersā Print (Course [0])
:- P
course = āPython for Beginersā Print (Course [-2])
o/P :- -2
Print (course [0:3])
Python
0 1 2 3
o/p :- pyt
name = ācreationā Print (āname [1:-7]ā)
o/p :- reation
Formatted Strings:- 1. First = āhrfā Last = ācreationā Message = First + ā[ā + Last + ā] is a coderā Print (Messsage)
o/p:-hrf[creation]is a coder
2. First = āhrfā Last = ācreationā Message = First + ā[ā + Last + ā] is a coderā msg=fā{first}[{last}]is a coderā Print (msg)
o/p:-hrf[creation]is a coder
2. course=āPython for beginnersā Print(len(course))
o/p:-20
Upper use to print uppper case
4.course=āPython for beginnersā Print(course.upper())
o/p:-PYTHON FOR BEGINNERS
Upper use to print uppper case
Lower use to print lower case
5.course=āpythonā Print(course.upper())
Print(course.lower())
Print(course)
o/p:- PYTHON//upper case
Python// lower cas
Python//first letter is upper case remainning are lower case
Atoz character- 1to26 numeric letter
P y t h o n = 0 1 2 3 4 5
P=0, y=1, t=2, h=3, o=4, n=5
6.course=āpythonā Print(course find(āyā))
Print(course find(āhā))
o/p:-1
3
7. course=āPython is a base of Machine learningā Print(course. Replace(āMachine learningā,āArtificial intelligenceā))
o/p:-Python is a base of Artificial intelligence
8. course=āPythonā Print(āPythonāin course)
O/p:-True//Python statementsāPā is upper case so program run as a true statement
9. course=āPythonā Print(āpythonāin course)
O/p:-True//python statement āpā is lower case so program run as a false statement
10.course=āPythonā Len()
Course.upper()//output will be in a capital letters
Course.lower()//output will be in small letters
Course.title()
Course.find()//findin value (python-012345)
Course.replace()//Replacing a function.. in course
Arithmatic operation
1. print(10//3)//o/p:-3
2. Print(10/3)//o/p:-3.3333335
3. Print(10**3)//o/p:-1000
4. Print(10%3)//o/p:-1
Addition
x=5
x=x+3
Print(x)
O/p:-8
subtraction
x=5
X-=3
Print(x)
O/p:-2
Addition
x=5
x=x+3
x+=4
Print(x)
O/p:-12
Operator precedcence
X=5+5*2
Print(x)
O/p:-15//10+(5*2)=15
Exponentiation 2**3//power 2^2=4
You can use multiplication or division and addtion or subtraction
x=5+4*2**2
Operator precedence
x=(5+3)*10-3
Print(x)
O/p:-77//5+3=8*10=80-3
x=5+3*2**2
Print(x)
o/p:-17
Math function
x=2.9
Print(round(x))
O/p:-3
x=2.9
Print(abs(-2.9)) o/p:-2.9//absolute always have a positive number.
Python basics
PYTHON
Basic
a = 1 (integer)
b = 1.1 (float)
c = 1 + 2j (complex)
d = āaā (string)
e = True (boolean)
Variables Escape sequences
\ā
\ā
\\
\n
x = āPythonā
len(x)
x[0]
x[-1]
x[0:3]
Strings
name = fā{first} {last}ā
Formatted strings
x.upper()
x.lower()
x.title()
x.strip()
x.find(āpā)
x.replace(āaā, ābā) āaā in x
String methods
round(x)
abs(x)
Numer functions
int(x)
float(x)
bool(x)
string(x)
Type conversion
Falsy values
0āāNone
if x == 1:
print(āaā)
elif x == 2:
print(ābā)
else:
print(ācā)
Conditional statements Chaining comparison operators
if 18 <= age < 65:
x = āaā if n > 1 else ābā
Ternary operator
x and y (both should be true)
x or y (at least one true)
not x (inverses a boolean)
Boolean operators
For loops
for n in range(1, 10): ā¦While loops
while n > 10: ā¦
== (equal)
!= (not equal)
Equality operators
codewithmosh.com
Functions
def increment(number, by=1):
return number + by
increment(2, by=1)
Keyword arguments
Defining functions
Variable number of arguments
def multiply(*numbers):
for number in numbers:
print number
multiply(1, 2, 3, 4)
Variable number of keyword arguments
def save_user(**user): ā¦
save_user(id=1, name=āMoshā)
codewithmosh.com
Shortcuts
Start Debugging F5
Step Over F10
Step Into F11
Step Out Shift+F11
Stop Debugging Shift+F5
DEBUGGING CODING (Windows) CODING (Mac)
End of line fn+Right
Beginning of line fn+Left
End of file fn+Up
Beginning of file fn+Down
Move line Alt+Up/Down
Duplicate line Shift+Alt+Down
Comment Cmd+/
End of line End
Beginning of line Home
End of file Ctrl+End
Beginning of file Ctrl+Home
Move line Alt+Up/Down
Duplicate line Shift+Alt+Down
Comment Ctrl+/
codewithmosh.com
Lists codewithmosh.com
Creating lists
letters = ["a", "b", "c"]
matrix = [[0, 1], [1, 2]]
zeros = [0] * 5
combined = zeros + letters
numbers = list(range(20))
Accessing items
letters = ["a", "b", "c", "d"]
letters[0] # "a"
letters[-1] # "d" Slicing lists
letters[0:3] # "a", "b", "c"
letters[:3] # "a", "b", "c"
letters[0:] # "a", "b", "c", "d"
letters[:] # "a", "b", "c", "d"
letters[::2] # "a", "c"
letters[::-1] # "d", "c", "b", "a" Unpacking
first, second, *other = letters
Looping over lists
for letter in letters:
... for index, letter in enumerate(letters):
... Adding items
letters.append("e")
letters.insert(0, "-")
Removing items
letters.pop()
letters.pop(0)
letters.remove("b")
del letters[0:3]
Lists codewithmosh.com
Finding items
if "f" in letters:
letters.index("f")
Sorting lists
letters.sort()
letters.sort(reverse=True)
Custom sorting
items = [
("Product1", 10), ("Product2", 9), ("Product3", 11)
]
items.sort(key=lambda item: item[1])
Zip function
list1 = [1, 2, 3]
list2 = [10, 20, 30]
combined = list(zip(list1, list2))
# [(1, 10), (2, 20)]
Unpacking operator
list1 = [1, 2, 3]
list2 = [10, 20, 30]
combined = [*list1, āaā, *list2]
Tuples
point = 1, 2, 3
point = (1, 2, 3)
point = (1,)
point = ()
point(0:2)
x, y, z = point
if 10 in point: ā¦
Swapping variables
x = 10
y = 11
x, y = y, x
Arrays
from array import array
numbers = array(āiā, [1, 2, 3])
Sets
first = {1, 2, 3, 4}
second = {1, 5}
first | second # {1, 2, 3, 4, 5}
first & second # {1}
first - second # {2, 3, 4}
first ^ second # {2, 3, 4, 5}
Dictionaries
point = {"x": 1, "y": 2}
point = dict(x=1, y=2)
point["z"] = 3
if "a" in point:
... point.get("a", 0) # 0
del point["x"]
for key, value in point.items():
... Comprehensions codewithmosh.com
List comprehensions
values = [x * 2 for x in range(5)]
values = [x * 2 for x in range(5) if x % 2 == 0]
Set comprehensions
values = {x * 2 for x in range(5)}
Dictionary comprehensions
values = {x: x * 2 for x in range(5)}
Generator expressions
values = {x: x * 2 for x in range(500000)}
Exceptions codewithmosh.com
Handling Exceptions
try: ā¦
except (ValueError, ZeroDivisionError): ā¦
else:
# no exceptions raised
finally:
# cleanup code
Raising exceptions
if x < 1:
raise ValueError(āā¦ā)
The with statement
with open(āfile.txtā) as file: ā¦
Classes codewithmosh.com
Creating classes
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self): ā¦
Instance vs class attributes
class Point:
default_color = āredā
def __init__(self, x, y):
self.x = x
Instance vs class methods
class Point:
def draw(self): ā¦@classmethod
def zero(cls):
return cls(0, 0)
Magic methods
__str__() __eq__() __cmp__()
Classes codewithmosh.com
Private members
class Point:
def __init__(self, x):
self.__x = x
Properties
class Point:
def __init__(self, x):
self.__x = x
@property
def x(self):
return self.__x
@property.setter:
def x.setter(self, value):
self.__x = value
Inheritance
class FileStream(Stream):
def open(self):
super().open() ā¦Multiple inheritance
class FlyingFish(Flyer, Swimmer): ā¦Abstract base classes
from abc import ABC, abstractmethod
class Stream(ABC):
@abstractmethod
def read(self):
pass
Classes codewithmosh.com
Named tuples
from collections import namedtuple
Point = namedtuple(āPointā, [āxā, āyā])
point = Point(x=1, y=2)
1. String - Series of character
2. Integer -WIthout using decimal point
Comments
Post a Comment