Translate

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

Popular Posts

bot

Popular post