Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Python

 Print function:

Print()

Ex- Print(“Hello World”)

Output: Hello world

 Comment:

Ex- # This is a comment

 Variable :

Words that store values in computer memory.

(Always starts with an alphabet, cannot start with a number or special character, can be a mixture of
upper case and lower case, cannot contain space, use underscore _ to join words )

Ex- var, var1, var1_var2, variable.

 Data Types:

Float – stores float values

Ex- a = 3.14 , -6.12

Int – integer values

Ex- a = 2, b = 45, c = -7.45

Boolean – Stores True or False

Ex- var1 = True , var2 = False

 Maths Operator’s:

SEQUENCE - () > ** > %, /, //, * > +, -

Addition = 3 + 5

Subtraction = 7 – 6

Multiply = 4 * 3
Division = 6 / 2

Exponentiation = 4 ** 4 # 256

Floor_division = 16 // 5 #3

Modulo = 7 % 3 #1

float_sum = 3.14 + 2.17

print(“The Sum is :”, float_sum)

Output = 5.310000000005

Round(float_sum, 2)

print(“The Sum is :”, Round(float_sum, 2))

Output = 5.31

 String:

Written in single quote or double quote

ex_1 = ‘This is a string’

ex_2 = “This is also a a string”

Each character or number in a string is assigned with an index

ex_3 = “01234567”

STRING SLICING – Slicing a given string or a variable

Ex-

String = “apricot”

print(String[:3])

print(String[2:5])

print(String[4:])

Output-

apr

ric
icot

 CONCATENATION :
#can only concatenate string not int with str

Ex- print (“python” +” “+ “Lab”)

Output-

Python Lab

 type() function:
use to tell the datatype of data

Ex- ex_1 = False


ex_2 = 342
ex_3 = 3.14
print(type(ex_1))
print(type(ex_2))
print(type(ex_3))

Output:

<class 'bool'>

<class 'int'>

<class 'float'>

 str() function :
Use to convert whatever is put into the function to convert into a string.

Ex-
ex_4 = str(False)
ex_5 = str(342)
ex_6 = str(3.14)
print(type(ex_4))
print(type(ex_5))
print(type(ex_6))

Output:
<class 'str'>
<class 'str'>
<class 'str'>

 Escape sequences :
Use to change line or add extra space in output
\t – add space
\n – change line
\’ – single quote in a string
\” – double quote in a string
\\ - back slash in the string

Ex- print("*******\n ***** \n *** \n * ")


Output –
*******
*****
***
*

 Input() function :
Get input from the user in output

Ex- name = input("Please enter your name.")


print("Your name is " +name+ ".")
print(type(name))

Output-
Please enter your name.Sakshi
Your name is Sakshi.
<class 'str'>

#No matter what datatype input is given by user , it always recognize input() as a string
EX- fav_num = input("Your favourite number is : ")
print(name + "'s favourite number is " +fav_num+ ".")
print(type(fav_num))

Output-
Your favourite number is : 4
Sakshi's favourite number is 4.
<class 'str'>

 Int() and float() function :

Used to convert datatype into integer and float.


Ex- num = int(input("Please enter and integer: "))
print("Integer is:", num)
print(type(num))

float = float(input("Please enter the float number: "))


print("The float is:", float)
print(type(float))

Output:
Please enter and integer: 6
Integer is: 6
<class 'int'>
Please enter the float number: 7.8
The float is: 7.8
<class 'float'>

 Function()

With the use of function we can use a group of codes again and again in a program by just calling it.

Ex- def function():

print(1 +5)

print(“Sum is :”, function())

Output: 6

#we can pass single or multiple parameters to function

def func(parameter)

print(parameter + 5)

print(“Sum is : “ , func(7)) # 7 is an argument

Output: 7 + 5 = 12

def func(p1, p2, p3)

return 3 * 4 + 5

print(func(1,2,p3))

Output: 7

print(func(1,p2,p3))

Output: 9

print(func(p1,2,6))

output: 12

 MODULES:
1. Generic import :

import random #random is the module name


print(random.randint(1, 10)) #randint() is the function which print’s

any random number from 1 to 10

2. Function import :

from random import randint

print(randint(10, 20))

3. Universal import: in this every function from random module is imported and can be
called anywhere under the module .

from random import *

print(random()) #random function is used to print any


float number between 0.0 and 0.1
print(uniform(1,5)) #print any float number from 1 to 5

# For other random module function’s visit :


https://www.w3schools.com/python/module_random.asp

 VARIABLE SCOPE:

Each variable has either a local scope or a global scope

Local scope Variable : variable which is defined within a function

Global scope Variable : variable which is defined outside a function and can be called anywhere

Important Point’s:

 Local variable cannot be used by code in the global scope.


 Global variables can be accessed by code in a local scope as well.
 The local scope of one function can’t use variable from another function’s local scope.
 You can use same name for different variables as long as they are in different scope.

Ex-
example = "My name is Sakshi"

def loc_ex():
example = "My age is 24"
return example

print(example)
print(loc_ex())

Output-

My name is Sakshi
My age is 24

Global Statement’s: if we want to assign a global variable a new value from within a function we can
do that through global statements.

Ex- #Global Statement's

def loc():
global fruit
fruit = "banana"
return fruit

fruit = "pear"
print(loc())
print(fruit)

Output-
banana
banana

Point of scopes in python : it helps us to determine the problem in long codes, we can easily find out
the issue with the local variable within their particular function local scope.
Local variables are created and destroyed within the functions. So it is easy to check the issue with
the global variables as well.

 FLOW CHART’S:
Type of diagram which has a starting point and can have multiple end points,
It depends on the intermediate conditions and it executes according to the conditions.

COMPARISON OPERATOR’S:
1) >
2) <
3) >=
4) <=
5) != (is not equal to)
6) ==

Comparison returns either True or False

EX- print(4 >= 2)


print(1.98 >= 5)

Output- True
False

print(“Hello” == “Hello”)
print(“Hello” != “world”)
print(“Hello” == “hello”)

True
True
False

#comparison is case sensitive and in comparison float is equal to integer

print(4.0 == 4)
print(4.0 >= 4)
print(4.0 <= 4)

True
True
True

Note: “=” is used to assign values and “==” is used to compare


BOOLEAN OPERATOR’S:
a) and
b) or
c) not

TRUTH Table:
AND

Statement Result
True and True True
True and False False
False and False False
False and True False
Ex-
print(4 > 1 and “word” == “word”)
print(8.76 == 8.7600 and 2 != 2)
print(“earth” == “Earth” and 6 <= 3)
print(10 == 5 and 10 != 5)

Output-
True
False
False
False

OR

Statement Result
True or True True
True or False True
False or False False
False or True True

Not

Statement Result
Not True False
Not False True

EX-
print(not 654 > 0)
print(not “Python” != “Python”)

Output-
False
True
 IF STATEMENT’S

Syntax:
if True(condition):
“Do the stuff here”

Ex- veg = input("Type the name of a vegetable. ")

if veg == "corn":
print("The vegetable is corn. ")
Output-
Type the name of a vegetable. corn
The vegetable is corn.

Process finished with exit code 0

Or
Type the name of a vegetable. Tomato

Process finished with exit code 0

 ELSE STATEMENT:

Syntax:

If False:
“Do the stuff here”
else:
“Do this instead”

 NESTED if else:
Using if and else statement within other if and else statement.

Ex- gpa = float(input("What is applicant's gpa: "))


inst_app = input("Is the applicant going to be educated from an approved institution? ")

if gpa >= 3.7:


if inst_app == "yes":
print("Applicant qualifies for low APR loan.")
else:
print("Applicant does not qualify for loan.")
else:
print("Applicant needs higher gpa to qualify.")

Output-
What is applicant's gpa: 4
Is the applicant going to be educated from an approved institution? yes
Applicant qualifies for low APR loan.

Process finished with exit code 0

Note : the else statement should be under the same level of its if statement

 ELIF statement:
Also known as else if statement allows to provide as many additional conditions to check as you
need without the messiness that comes with having to use multiple nested if statement and if
else statement block’s.

Ex- user_num = int(input("Enter an integer. "))

if user_num < 0:
print("The number you entered is smaller than 0.")
elif user_num == 0:
print("The number you entered is 0.")
elif 0 < user_num <= 100:
print("The number you entered is either 0 or 100 or in between them.")
else:
print("The number you entered is greater than 100.")

Output-
Enter an integer. -1
The number you entered is smaller than 0.

Process finished with exit code 0

 Truthy and falsy values for strings:

string = input(“Enter any string other than an empty one. ”)

If string:
print(“Thank you for entering the string.”)
else:
print(“You did not enter any string.“)

Ex-
Enter any string other than an empty one. This is a string
Thank you for entering the string.

Or
Enter any string other than an empty one.
You did not enter any string.

string = input(“Enter any string other than an empty one. ”)

If string != “”:
print(“Thank you for entering the string.”)
else:
print(“You did not enter any string.“)
truthy and falsy values for integers and floats

Falsey values
Integer’s 0
floats 0.0

 Bool() function
Used to give the Boolean value of the function put in parenthesis

Ex- print(bol(0))

Output – False

Print(bol(400))

True

Print(bol(0.0))

False
Print(bol(1.8))

True

Print(bol(“”))

False

Print(bol(“This is a string))

True

 WHILE LOOP:

Loops are useful tool for when you want to have code run on every item in a piece of data that has
indexes such as string.

Syntax:

counter = 0
condition

while counter < 3:

code

print(“something”)

counter += 1

While loops runs each time it evaluates its condition and that condition evaluates to true.
Ex- counter = 0

while counter < 3:


print("something")
counter += 1

Output-
something
something
something

Process finished with exit code 0

 FOR LOOPS:
It is particularly used to perform the fixed number of iterations.
Controlled by iterrable piece of data.

Syntax:
word = “house”
var
for letter in word:
print(letter)

Output:
h
o
u
s
e

 Range():
Range is a function that returns a sequence of number and is usually used for iterating over with a
for loop.

Three argument’s: (Start, stop, step)

Can be used with all three at a same time.

Using range with one argument:


num = range(5) #range has it’s own datatype called range

for seq in num:


print(seq)

Output:
0
1
2
3
4

Process finished with exit code 0

Using range with two argument:


two_input = range(5, 10)

for seq in two_input:


print(seq)

Out-
6
7
8
9

Process finished with exit code 0

Using range with three argument:


three_input = range(20, 1, -3)

for seq in three_input:


print(seq)

Out-
19
16
13
10
7
4
3
1

 String methods:

1) lower() : used to change the string in lower case.


2) upper() : used to change the string in all upper case.
3) islower() : return true if the string is in lower case.
4) isupper() : return true if the string is in upper case.

You might also like