0% found this document useful (0 votes)
27 views20 pages

PYTHON

Every thing about Python. It is personally written by me. I am a employee at Microsoft with 5+ years of experience. Hope this helps you study!

Uploaded by

ahmalik1012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views20 pages

PYTHON

Every thing about Python. It is personally written by me. I am a employee at Microsoft with 5+ years of experience. Hope this helps you study!

Uploaded by

ahmalik1012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PYTHON

INTRODUCTION

● Python is a popular programming language. It was created by Guido Van Rossum and
was released in 1991.
● It is used for
Web development (server-side)
Software development
Mathematics
System scripting

WHAT CAN PYTHON DO?

● It can be used on a server to create web applications.


● It can be used alongside software to create workflows
● It can connect data based systems. It can also read and modify files
● It has syntax that allows developers to write programs with fewer lines than some other
programming languages
● It runs an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be a very quick
● Software development
● Game development
● Web development
● Artificial intelligence and machine learning
● Data analisis

FEATURES OF PYTHON

● Python is object oriented


● Python is procedure oriented
● High level language
● Easy to learn - python has few key words, simple structures, and a clearly defined syntax
● Easy to read - python code is more clearly defined and visible to eyes
● Interactive - python has support for interactive testing and debugging
● Portable - python can run on wide variety of hardware platforms
● It is an open source

CAN IT RUN ON MY DEVICE

● It can run on almost any platform including WINDOWS, LINUX, MAC OS X, UNIX etc

print() function

● Functions in python is written using parentheses ()


● It is similar to say block in scratch
● The print function prints the specified message to the screen, or other standard output
device

time.sleep() function

● It is similar to the block repeat in scratch


● It will only work if you import time
Syntax - It is a set of rules that defines how a python program will be written and interpreted.

Indentation - It refers to the spaces at the beginning of a code line. In other programming
languages, the indentation in code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code.

TURTLE
Turtle is nothing, but a way to draw with Python script. With the turtle module, one can open a
screen and see the output.Turtle was introduced in 1967 via a language called logo.
We need three commands to launch the turtle screen ( from turtle import, turtle=turtle,
screen=screen )

INPUT FUNCTION
Inputs are a form of data that is accepted from the user or other external environment. The
inputs once taken are processed, then generate a corresponding output.

INPUT DEVICES
The devices which allow us to take input from the user are known as Input devices, for example
keyboard, mouse, etc…

DATA TYPES
Data types are nothing, but that tells a computer how we want to use the data entered. The user
input captures the number of strings (a sequence of characters), and first are defined and then
only they become ready to execute
BASIC DATA TYPES
● String - a sequence of characters including punctuation, numbers and letters.
● Integer - a number with no decimals points
● Float - a number with a decimal point

POINTS TO REMEMBER
● By default the input function considers the variables as string data type
● Strings should always be written in double quotes ( “ “ )
● If x = 3.23 then the int (x) = 3
● Integer short form int
● String short form str
● There are 2 types of print - Print a string: print(“hello world”) and print a variable:
print(variable name)

VARIABLE
● A variable is a reserved memory location to store values.
● In other words, a variable in a program gives data to a computer for processing.
● The value stored in a variable can be changed during program execution.
● Python has no command for declaring a variable
● A variable is created the moment you first assign a value to it
● Variables don't need to be declared with any particular type, and can even change its
type after they have been set

RULES FOR CREATING VARIABLE IN PYTHON


● A variable name should start with a letter or an under score
● A variable name can never start with a number
● Variable name can contain only alphanumeric characters and underscores (A-Z, 0-9,_)
● Variable names are case sensitive (name, Name and NAME are three different
variables)
● The reserved words (keywords) cannot be used to name a variable

ASSIGN MULTIPLE VALUES


● Python allows you to assign values to multiple variables in one line
● Python allows to assign the same value to multiple variables in one line
● If you have a collection of values in a list, tuple, etc, python allows you to extract the
values into variables. This is called unpacking

USES OF VARIABLES
● In software programming variables are used to hold 1 or more values.
● Calculations
● Database call
● Game attributes like score, lifes, etc…
● Database query
● Maintaining records

LOGICAL OPERATORS
● == : values must be equal
● != : values must not be equal
● < : left value is less than right value
● <= left value is less than or equal to right value
● > left value is greater than right value
● >= left value is greater than or equal to right value

POINTS TO REMEMBER
● Addition of integer - operator to add 2 integers is in math block
● Addition of string - operator to add 2 strings is in statement block
● Print the string - to print a string, use print hello world from the statement block
● Print a variable - to print a variable ue print variable for the statement block

FLOW CONTROLS (switch cases / conditional statements)


● Just like humans, computers also make decision, but according to the user
● The statement which are conditional or can switch to true or false statements are termed
as flow controls of the program for helping user to make decisions for the computer
● Decision making is required when we want to execute a code only if a certain condition
is satisfied. The if…else statement is used in python for decision making.
PROPERTIES OF FLOW CONTROLS
● Programming languages provide various control structures that allow for more
complicated execution paths
● A control statement allows us to execute a statement or group of statements multiple
times or on condition based
● It reduces the program size

TYPES OF FLOW CONTROLS


● If - if statement contains a logical expression using which data is compared and the
decision is made based on the result of comparison.
● If else - An else statement can be combined with an if statement. An else statement
contains a block of code that executes if the conditional expression in the if statement
resolves to 0 or a false value
● Nested if else
● Nested loops
● For loop - For loop has the ability to Iterate over a sequence (list, tuple, dictionary, etc..).
It works exactly like the repeat block in scratch
● While loop - A while loop statement in python programming language repeatedly
executes a target statement as long as a given condition is true. While loop in python
works exactly like forever block in scratch

FOR LOOP WHILE LOOP

For loop has a more rigid syntax While loop has a looser syntax

There are 3 steps in for loop (initialization, While loops are executed ass long as the
expression, increment) test expression evaluates to be true

All the above mentioned flow controls are also called as control statement

IF STATEMENT
● The program evaluates the test expression and will execute the statements only if the
test expression is true
● If the test expression is false, the statement is not executed
● In python, the body of the if statement is indicated by the indentation. The body starts
with an indentation and the first unindented line marks the end
● Python interprets non 0 values as true. None and 0 are interpreted as false
● Syntax -
if test expression:
statement(s)
IF… ELSE STATEMENT
● The if…else statement evaluates the test expression and will execute the body of if only
when the test condition is true
● If the condition is false, the body of else is executed. Indentation is used to separate the
blocks
● Syntax:
If test expression:
body of if
else:
body of else
IF…ELIF…ELSE STATEMENT
● The elif is short for else if. It allows us to check for multiple expressions
● If the condition for if is false, it checks the condition of the next elif block and so on
● If all the conditions are false, the body of else is executed
● Only one block among the several if…elif…else blocks is executed according to the
condition
● The if block can have only one else block. But it can have multiple elif blocks
● Syntax:
If test expression:
body of if
elif test expression:
body of elf
else:
body of else
FUNCTIONS
● A function is a block of code which only runs when it is called
● You can pass data, known as parameters into a function
● A function can return data as a result
● In python, a function is a group of related statements that performs a specific task

SYNTAX
def function_name(parameters):
statement(s)
● Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable
● Furthermore, it avoids repetition and makes the code reusable

HOW DOES A FUNCTION BLOCK WORK?


● Keyword def that marks the start of a function header
● A function name to uniquely identify the function
● Function naming follows the same rules of writing identifiers in python
● Parameters(arguments) through which we pass values to a function. They are optional
● A colon to mark the end the function of a header
● Optional documentation string(docstring) to describe what the function does
● One or more valid python statements that makeup the function body. Statements should
have the same level of indentation
● An optional return statement to return the value from the function

DOCSTRING
● The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does

RETURN STATEMENT
The return statement is used to exit a function and go back to the place from where it was
called.

SYNTAX
Return[expression_list]
● This statement can contain an expression that gets evaluated and the value is returned
● If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the none object

CREATING A FUNCTION
In python, a function is defined using the def keyword

CALLING A FUNCTION
To call a function, use the function name followed by parenthesis

ARGUMENTS
● Information can be passed into functions as arguments
● Arguments are specified after a function name, inside the parenthesis. You can add as
many arguments as you want, just separate them with a comma
WHY ARE FUNCTIONS USEFUL?
● They are subroutines, small sequences of code inside the main code
● We can call the function, and come out of the main code, do the function, then again
come back to the code
● They enable us to reuse sections of code
● They keep our code tidy, and with fewer lines to write

PARAMETERS OR ARGUMENTS?
The terms parameter and argument can be used for the same thing - information that is passed
into a function. From a functions perspective:
● A parameter is the variable listed inside the parenthesis in the function definition
● An argument is the value that is sent to the function when it is called

LISTS
● List’s are the most versatile data storage in python
● They are used to store data and that data can be changed based on different list
properties.
● In python, list is created by placing all the items in square bracket and separated by
commas
● It can have any number of items of different data types

LIST INDEXING
● List indexing is done in such a way that the first element that enters the list takes the 0
index. The elements of listing are denoted in the given way Listname[index] = element.
● Lists are heterogeneous in nature (the items can be of different data types).
● Forward indexing: 0 to n-1
● Backward/Negative indexing: -1 to -n

OPERATIONS ON LIST
● list.append() - to add an element at the end of the list
● list.extend() - to add another list inside the list
● list.pop() - to remove the element from the given position using its index number
● list.remove() - to remove the particular element from the list
● list.insert() - to insert the later element at the position shown as the first element
LOGICAL OPERATORS
The logical operators in python are used to combine the true or false values of the variables so
you can figure out the resultant value

AND LOGICAL OPERATOR(&&)


Both the conditions should be true to make further execution of the program

OR LOGICAL OPERATOR(||)
If anyone of the conditions are true, program can be further executed

COMMENTS(#)
● In computer programming a comments is a programer readable explanation on
annotation in the source code of a computer program
● Comments in python began with a hash mark and white space character and continue to
the end of the line
● Because the comments don't execute, when you run a program you will not see any
indication of a comments there
● Comments are in a source code for the humans to read, not for the computers to
execute
● There are two types of comments: single line comment and multiline comment
● A single line comment starts and end in the same line
● Python doesn't have a separate way to write multiline comments. However, we can use
hash at the beginning of each line of a comment on multiple lines

ALGORITHM
● An algorithm is a procedure or formula for solving a problem, based on conducting a
sequence of specified actions

INDENTATION
● It refers to the spaces at the beginning of the code
● Python uses indentation to indicate a block of code
● Python will give you an error if you skip the indentation
● The number of spaces is up to you as a programmer, but it has to be at least one
● You have to use the same number of spaces in the same block of code, otherwise
python will give you an error

BINARY NUMBER
A number system where a number is represented by using only two digits (0,1) with the base 2
is called as a binary number system

DECIMAL NUMBER
A decimal number system is also known as the base 10 numeral system. It uses 10 digits from
0-9.

WHAT IS BINARY TO DECIMAL CONVERSION?


● Binary to decimal conversion is done to convert a number in a binary system to a
number in decimal system

DATA TYPES
Data types are defined as the data storage format that a variable can store to perform a specific
operation

PROPERTIES OF DATA TYPE


● Data types are used to define a variable before you use them in a program
● The size of the variable, constant and array a determined by data types

DATA TYPES CLASSES DESCRIPTION

Numeric Int, float, complex Holds numeric values

String Str Holds sequence of characters

Sequence List, tuple, range Holds collection of items

Mapping Dict Holds data in key - value pair


form
Boolean Bool Holds either true or false
value

NUMERIC DATA TYPE


Numeric data type is used to hold numeric values. Integers, floating point and complex numbers
fall under this category. They are defined as int, float and complex classes
● Int - Holds integers of non limited length
● Float - Holds decimal points and its accurate up to 15 decimal places
● Complex - Holds complex numbers. A complex number contains 2 parts - imaginary and
real number

Note: The type() function is used to know the class of a variable

STRING DATA TYPE


String is a sequence of characters represented by either single or double quotes

SEQUENCE DATA TYPE


● List - a list contains items separated by commas and enclosed by square brackets
● Tuple - a tuple is an ordered sequence of items the same as a list. They are enclosed in
parenthesis () and cannot be updated

MAPPING DATA TYPE


DICTIONARIES(DICT)
Dictionary is an ordered collection of items. It stores elements in key/value pairs. They are
enclosed by curly brackets and the values can be assigned and accessed using square
brackets

BOOLEAN DATA TYPE


The python data type bool is used to store 2 values (true or false). Bool is used to test whether
the result of an expression is true or false
DATA TYPE CONVERSION
There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value

1. int(x) - converts x to an integer


2. float(x) - converts x to a floating point number
3. complex(x) - converts x to a complex number

STRING OPERATIONS
1. Concatenation() - adds values on either side of the operator(+) and returns both the
strings as one
2. Repetition() - creates new strings, concatenating multiple copies of the same string
3. Slice() - gives the character from the given index
4. Range slice() - gives the character from the given range
5. Membership() - returns true if a character exists in the given string
6. Membership() - returns true if a character doesn't exist in the given string

ARITHMETIC OPERATORS
1. Addition (+) - adds two operands
2. Subtraction (-) - subtracts right operand from the left
3. Multiplication (*) - multiplies two operands
4. Division (/) - divides left operands from the right
5. Modulus (%) - remainder of the division of left operand by the right>
6. Floor division (//) - division that results into a whole number
7. Exponent (**) - left operand raised to the power of right

COMPARISON OPERATORS
1. Greater than (>) - true if left operand is greater than the right
2. Less than (<) - true if left operand is lesser than the right
3. Equal to (=) - true if both operands are equal
4. Greater than equal to (>=) - true if left operand is greater than equal to the right
5. Less than equal to (<=) - true if left operand is lesser than equal to right
6. Not equal to (!=) - true if operands are not equal
LOGICAL OPERATORS
1. And (&&) - true if both operands are true
2. Or (||) - true if anyone of the operand in true
3. Not (!) - true if operand is false (complements the operand)

BITWISE OPERATORS
Bitwise operators act on operants as if they were a string of binary digits. They operate bit by
bit, hence the name

OPERATOR NAME DESCRIPTION SYNTAX

& Bitwise and Result bit 1, if both x&y


operand bits are 1;
otherwise results bit 0

| Bitwise or Result bit 1, if any of x|y


the operand bit is 1;
otherwise results bit 0

~ Bitwise not Inverts individual bits ~x

^ Bitwise xor Results bit 1, if any of x^y


the operand bit is 1,
but not both, or
otherwise the result
bit 0

>> Bitwise right shift The left operands x >>


value is moved
toward the right by
the number of bits
specified by the right
operand

<< Bitwise left shift The left operands x <<


value is moved
toward the left by the
number of bits
specified by the right
operand
ASSIGNMENT OPERATORS

OPERATOR DESCRIPTION SYNTAX

= Assigned value of the right x=y


side of the expression to left
side operand

+= Add and assign a += b

-= Subtract and assign a -= b

*= Multiply and assign a *= b

/= Divide and assign a /= b

%= Modulus and assign a %= b

//= Floor division and assign a //= b

**= Exponent and assign a **= b

&= Bitwise and and assign a &= b

|= Bitwise or and assign a |= b

^= Bitwise xor and assign a ^= b

>>= Bitwise right shift and assign a >>= b

<<= Bitwise left shift and assign a <<= b

IDENTITY OPERATORS

OPERATOR DESCRIPTION EXAMPLE

is Returns true if both variables x is y


are the same object

is not Returns true if both variables x is not y


are not of the same object
MEMBERSHIP OPERATOR

Operator Description Example

in Returns true if a sequence x in y


with the specified is present
in the object

not in Returns true if a sequence x not in y


with the specified is not
present in the object

FOR LOOP
● For loop is used for iterating over a sequence (a list, tuple, dictionary, set or a string)
● Syntax:
for val in sequence:
body of for
● Here, val is the variable that takes the value of the item inside the sequence on each
iteration
● Loop continues until we reach the last item in the sequence =
● The body of for loop is separated from the rest of the code using indentation
RANGE FUNCTION
● W-e can generate a sequence of numbers using range functions. Range(10) will
generate numbers from 0 to 9 (10 numbers)
● Syntax: range(x)
● We can also define the start, stop and step signs as range(start, stop, stepsize)
● Step Size defaults to 1 if not provided
● This function does not store all the values in memory: it would be inefficient. So it
remembers start, stop, step size and generate the next number on the go
● To force this functions to output all the items, we can use the function list

ELSE IN FOR LOOP


● A for loop can have an optional else block as well
● The else part is executed if the items in sequence used in for loop exhausts

SYNTAX
for val in sequence:
body of for
else:
Body of else
● The break keyword can be used to stop a for loop, in such cases, the else part is ignored
● Hence, a for loops else part runs if no break occurs

WHILE LOOP
The while loop in python is used to iterate over a block of code as long as the test expression is
true. We generally use this loop when we don't know the number of times to iterate before hand

SYNTAX
while test_expression:
body of while loop
● In while loop, test expression is checked first the body of the loop is entered only if the
test expression evaluates to true
● After 1 iteration, the test expression is checked again. This process continues until the
test expression evaluates to false
FLOW CHART
● In python, the body of while loop is determined through indentation
● The body starts with indentation and the first unindented line marks the end
● Python interprets any non zero value as true. None and 0 are interpreted as 0

WHILE LOOP WITH ELSE


● Same as with for loops, while loops can also have an optional else block
● The else part is executed if the condition in the while loop evaluates to false

SYNTAX
while test_expression:
body of while
else:
body of else

● The while loop can be terminated with a break statement. In such cases the else part is
ignored
● Hence, a while loops else part runs if no break occurs and the condition is false

BREAK STATEMENT
With the break statement, we can stop the loop even if the while condition is true

CONTINUE STATEMENT
With the continue statement, we can stop the current iteration and continue with the next

You might also like