0% found this document useful (0 votes)
3 views4 pages

Python??

The document provides an overview of Python, highlighting its characteristics as an interpreted language, its application areas such as web development, game development, and data science, and the use of Integrated Development Environments (IDEs) like IDLE and Jupyter Notebook. It also covers Python's data types, operators, control flow statements, functions, and the advantages of using functions in programming. Additionally, it explains the concept of type conversion, loops, and built-in functions, particularly from the math module.

Uploaded by

jesrarshin
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)
3 views4 pages

Python??

The document provides an overview of Python, highlighting its characteristics as an interpreted language, its application areas such as web development, game development, and data science, and the use of Integrated Development Environments (IDEs) like IDLE and Jupyter Notebook. It also covers Python's data types, operators, control flow statements, functions, and the advantages of using functions in programming. Additionally, it explains the concept of type conversion, loops, and built-in functions, particularly from the math module.

Uploaded by

jesrarshin
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

Python Interpreter Application Areas of Python IDE

◾ Python is an interpreted language similar to how 1. Web Applications An IDE (or Integrated Development Environment) is a
java operates with bytecode Web application framework libraries like django, program dedicated to software development. IDEs
◾ Once Python starts, you will see the interpreter Pyramid, Flask etc. make it very easy to develop and contains several tools like:
startup message, indicating version and platform. deploy simple as well as complex web applications. An editor designed to handle code (with, for
◾ You will also be given the python interpreter These frameworks are used extensively by various IT example, syntax highlighting and auto-completion)
prompt, i.e., ">>>" which is also known as python companies. Build, execution, and debugging tools
chevron prompt. 2. Game Development The different IDE"e for python are IDLE, Jupyter
◾ The ">>>"indicates that Python interpreter is Python is also used in the development of Notebook etc.
waiting for an expression or command. interactive games. PyGame which provides IDLE
◾ The interactive environment where we are functionality and a library for game development. Every Python installation comes with an Integrated
interacting with the Python interpreter is called the 3. Data Science and Data Visualization Development and Learning Environment, which
console or command shell Huge amount of data is being generated today by you'll see shortened to IDLE or even IDE. These are a
Advantages of Python web applications, mobile applications and other class of applications that help you write code more
◾ Most programs in Python require considerably devices. Companies need business insights from this efficiently. While there are many IDEs for you to
less number of lines of code to perform the same data. Python libraries like NumPy, Pandas and choose from, Python IDLE is very bare-bones, which
task compared to other languages like C. Matplotlib are extensively used in the process of makes it the perfect tool for a beginning
◾ So less programming errors and reduces the data analysis, including the collection, processing programmer.
development time needed also. and cleansing of data Python IDLE comes included in Python installations
◾ Simple and Easy to learn on Windows and Mac. If you're a Linux user, then you
◾ It's Opensource and Free
Variables
should be able to find and download Python IDLE
◾ Python is famous for being the "batteries are
Python has no command for declaring a variable.
Variables are created when you assign a value to it.
using your package manager. Once you've installed
included" language. it, you can then use Python IDLE as an interactive
◾ There are over 300 standard library modules
Data type of variable is determined based on data
given by user. So Python is known as dynamically
interpreter or as a file editor.
which contain modules and classes for a wide
typed language.
variety of programming tasks.

An Interactive Interpreter Python Data types 3. Boolean


The best place to experiment with Python code is in Data types are the classification or categorization of In a programming language, mostly data is stored in
the interactive interpreter, otherwise known as a data items. In Python programming everything is the form of alphanumeric but sometimes we need
shell. The shell is a basic Read-Eval-Print Loop treated as object. Data types are actually classes and to store the data in the form of 'Yes' or 'No'.
(REPL). It reads a Python statement, evaluates the variables are instance (object) of these classes. In terms of programming language, Yes is similar to
result of that statement, and then prints the result Following are the standard or built-in data type of True and No is similar to False.
on the screen. Then, it loops back to read the next Python: This True and False data is known as Boolean Data
statement. 1. Numeric and the data types which stores this Boolean data
The Python shell is an excellent place ui to 2. Sequence Type are known as Boolean Data Types
experiment with small code snippets. You can access 3. Boolean 4. Set:- Set is an unordered collection of data type
it through the terminal or command line app on your 4. Set that is iterable, mutable and has no duplicate
machine. You can simplify your workflow with Python 5. Dictionary elements. The order of elements in a set is undefined
IDLE, which will immediately start a Python shell 1. Numeric though it may consist of various elements.
when you open it. Numeric data type represent the data which has The lists and dictionaries in Python are known as
A File Editor numeric value. Numeric value can be integer, floating sequence or order collection of data.
Every programmer needs to be able to edit and save number or complex numbers. These values are However, in Python we also have one data type which
text files. Python programs are files with thepy defined as int, float and complex class in Python is an unordered collection of data known as Set.
extension that contain lines of Python code. Python 2. Sequence Type 5. Dictionary
IDLE gives you the ability to create and edit these In Python, sequence is the ordered collection of A Python dictionary is an unordered collection of
files with ease. similar or different data types. Sequences allows to key-value pairs.
Python IDLE also provides several useful features store multiple values in an organized and efficient When we have the large amount of data, the
that you'll see in professional IDEs, like basic syntax fashion. There are several sequence types in Python dictionary data type is used. Keys and values can be
highlighting, code completion, and auto-indentation. String of any type in a dictionary.
Professional IDEs are more robust pieces of software List Items in dictionary are enclosed in the curly-braces()
and they have a steep learning curve. If you're just Tuple and separated by the comma (,). A colon (:) is used to
beginning your Python programming journey, then separate key from value.
Python IDLE is a great alternative!

Python Tokens Operators Relational operators


Python tokens are keywords, identifiers, literals and An Operator is a symbol used to perform an action.
operators. Different operators are
Identifiers 1. Arithmetic Operators
Identifiers represents user-defined names, 2. Comparison (Relational) Operators
variables, modules, and other objects. 3. Assignment Operators
Rules 4. Logical Operators
• An identifier can be a sequence of lower case (or) 5. Bitwise Operators
upper case (or) integers (or) a combination of any. 6. Membership Operators
• The identifier name should start with the lower 7. Identity Operators
case or upper case or must not start with digits) Arithmetic Operators
•The length of the identifier name should not be
more than 79 characters
Keywords
These are the reserved words with special meaning.
Logical operator
User cannot use them as constants or variables or
any other identifier names.
Literals
Literals are used to define the data as a variable (or)
constants. Python has 6 literals tokens.
[Link]
[Link]
[Link]
[Link] literals
[Link] Literals
[Link]
Assignment operators Statement Implicit Type Conversion
A statement is an instruction that the Python In Implicit type conversion, Python automatically
interpreter can execute. We have normally two basic converts one data type to another data type.
statements, the assignment statement and the print Example 1
statement. Some other kinds of statements that are a=10 b=20.5 res=a+b print(res) 30.5 //float number
if statements, while statements, and for statements Example 2 a=10 b=20+5j res=a+b print(res) 30+5j
generally called as control flows. #Complex number
Explicit Type Conversion
Expression
In Explicit Type Conversion, users convert the data
An expression is a combination of variables,
type of an object to required data type. This type of
operators, values. An expression is
conversion is also called typecasting because the
evaluated using assignment operator.
user casts (changes) the data type of the objects.
sum=a+b+c
Syntax: <required_datatype><expression>
avg=sum/3
Typecasting can be done by assigning the required
Type Casting in python data type function to the expression.
The process of converting the value of one data Boolean expressions
type (integer, string, float, etc.) to another data type ◾ A Boolean expression is an expression that may
is called type conversion. Python has two types of have only one of two values: True or False.
type conversion. ◾ Boolean expressions are used to denote the
1. Implicit Type Conversion conditions for selection and iterativecontrol
Bitwise operators
2. Explicit Type Conversion statements
Functions ◾ Python's comparison operators can be used to
A function is a block of organized, reusable code that make Boolean expressions
is used to perform a single, related action. Functions ◾ The simplest Boolean expressions in Python are
provide better modularity for your application and a True and False.
high degree of code reusing. ◾ bool is the name of the class representing
Python's Boolean expressions.

Boolean Operators for Flow Control if elif else Multiway Decision Statement Loops in python
Decision making statements available in python are Here, a user can decide among multiple options. A loop statement allows us to execute a statement or
• if statement The if statements are executed from the top down. group of statements multiple times as long as the
• if..else statements As soon as one of the conditions controlling the if is condition is true. Repeated execution of a set of
• nested if statements true, the statement associated with that if is statements with the help of loops is called iteration.
• if-elif ladder executed, and the rest of the ladder is bypassed. Loops statements are used when we need to run same
if statement If none of the conditions is true, then the final else code again and again, each time with a different value.
The simplest selection control statement is if statement will be executed. In Python Iteration (Loops) statements are of three
statement Syntax: if condition: Nested if types:
statements When you have an if statement(or if else or if elif 1. While Loop 2. For Loop 3. Nested Loops
Here, the condition after evaluation will be either else) inside another ifstatement(or if else or if elif [Link] Loop
true or false. else), it is called nesting The while loop in Python is used to iterate over a
if statement accepts boolean values - if the value is if (condition1): block of code as long asthe test expression
true then it will execute the block of statements statement (condition) is true.
below it otherwise not. if (condition2): We generally use this loop when we don't know the
if-else statement statement number of times toiterate beforehand.
If-else is called alternative execution # if Block is end here Syntax: while test_expression:
It provides two possibilities. The condition determines # if Block is end here Body of while
which possibility isexecuted. Built-in Functions Nested loop
If the condition is TRUE, the first block is executed but The python interpreter has several functions that Using loop inside another loop is known as nested
if condition isFALSE, another block of code is are always present for use. These functions are loop.
executed if (condition): known as Built-in Functions. Example #nested for loopSyntax:
statement(s) # Executes this block if There are some built-in functions in the Python n=eval(input("Enter number :"))
# condition is true programming language that can convert one type of for i in range(1,n):
else: data into another type. print("Multiplication Table of ",i)
statement(s)# Executes this block if For example, the int function can take any number for j in range(1,11):
# condition is false value and convert it into an integer. print(j,"*",i,"=",j*i)

for loop
Loop Control Statements Advantage of Functions in Python
The for loop is used to iterate over a sequence
Loop control statements change execution from its There are the following advantages of Python
It goes through the elements in any ordered
normal sequence. They are used to control the order functions.
sequence list, i.e., string, lists, tuples, the keys of
dictionary and other iterables.
of execution of the program based on the values and ◾ Using functions, we can avoid rewriting the same
logic. Sometimes we wish to terminate the current logic/code again and again in a program.
In each iteration step, a loop variable is set to a
value. It does not require the loop variable to set
iteration or even the whole loop without checking ◾ We can call Python functions multiple times in a
test expression. Python provides 3 types of Control program and anywhere in a program.
beforehand Syntax >>>for x in y :
Block 1
Statements: ◾ We can track a large Python program easily when
1. break it is divided into multiple functions.
else:
# Optional
2. continue ◾ Reusability is the main achievement of Python
3. pass functions.
Block 2 # excuted only when
the loop exits normally break and continue statements Mathematical functions
Range()
The break and continue statements are often useful The math module is used to access mathematical
The range() function is a built-in function in Python
in a while loop as wellas in a for loop. functions in the Python. All methods of this
that helps to iterate over asequence of numbers.
The break statement exits from the loop and functions are used for integer or real type objects,
It works only with integers
transfers the execution fromthe loop to the not for complex numbers.
It produces an iterator that follows arithmetic
statement that is immediately following the loop. To use this module, we should import that module
progression.
The continue statement causes execution to into our code.
range(n) generates a sequence of numbers that
immediately continue at the start of the loop, import math
starts with 0 and ends with (n-1).
Constant of math module
for-else loop Categories of functions
Pi: Return the value of pi: 3.141592
For loop executes the block until a condition is Two categories of functions are existing in Python.
Example
satisfied. When the condition becomes false, the [Link]-in-functions.
import math
statement immediately after the loop is executed. The [Link] defined functions
print("Value of PI:", [Link])
else clause is only executed when your for condition
Output
becomes false. If you break out of the loop, or if an
Value of PI: 3.141592653589793
exception is raised, it won't be executed.
Functions of math module [Link] definition Calling a function
Numeric functions Function definition is used specify name of the Once we have defined a function, we can call it from
[Link](x): Return the Ceiling value. It is the function, arguments and block of statements that another function, program or even from the Python
smallest integer, greater or equal to the number x. will execute when the function is called. prompt. To call a function we simply type the
[Link](x): Returns the absolute value of x. Syntax function name with appropriate parameters. User can
[Link](x): Returns factorial of x. where x ≥ 0 def function_name(parameters): call a function multiple times.
[Link](x): Return the Floor value. It is the largest """docstring""" Parameters and Arguments
integer, less or equal to the number x. statement(s) Parameters and arguments are the values or
[Link](x, y): Find remainder after dividing x return(expression) expression passed to the functions between
by y. 1. Keyword def that marks the start of the function parentheses. Arguments are variables/values passed
2. DateTime functions header. The first line of the function is known as with functions at the time of function calling. The
Module named datetime is used to work with dates. header and the rest of the function is known as body value of the arguments are always assigned to
Functions of the function. The header line must end with a variables and these variables are known as
[Link](): Returns date only. The colon. Add a little bit
parameters. Parameters areof body text
included at the time of
returned date contain year, month, and day. 2. A function name to uniquely identify the function. function definition within function header.
[Link](): Returns date and time. The Function naming follows the same rules of writing Formal Arguments
returned date contains year, month, day, hour, identifiers in Python. Formal arguments are arguments passed at the time
minute, second, and microsecond. 3. Parameters (arguments) through which we pass of function calling.
strftime() Method: The datetime object has a method values to a function. They are optional. Recursion
for formatting date objects into readable strings. The 4. A colon (:) to mark the end of the function header. Recursion is the process of function to call itself.
method is called strftime(), and takes one parameter, 5. Optional documentation string (docstring) to Every recursive function must have a base condition
format, to specify the format of the returned string: describe what the function does. that stops the recursion or else the function calls
6. One or more valid python statements that make itself infinitely. The Python interpreter limits the
𝗟𝗲𝗻 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 depths of recursion to help avoid infinite recursions,
up the function body. Statements must have the
len is a built in function in Python. resulting in stack overflows. By default, the
same indentation level (usually 4 spaces).
When used with a string, len returns the length or maximum depth of recursion is 1000. If the limit is
7. An optional return statement to return a value
the number of characters in the string. crossed, it results in RecursionError
from the function.

Advantages of Recursion String Traversal


1. Recursive functions make the code look clean and Traversal is a process in which we access all the
elegant. elements of the string oneby one using some
2. A complex task can be broken down into simpler conditional statements such as for loop, while loop,
sub-problems using recursion. etc.
3. Sequence generation is easier with recursion than String traversal is an important pattern since there
using some nested iteration. will be many situations in different programs where
Disadvantages of Recursion we need to visit each element of the string anddo
1. Sometimes the logic behind recursion is hard to some operations, continuing till the end of the
follow through. string.
2. Recursive calls are expensive (inefficient) as they >>>var= 'banana'
take up a lot of memory and time. Formatting Strings using format() String Concatenation
3. Recursive functions are hard to debug. The format() method that is available with the string String Concatenation is the technique of combining
object is very versatile and powerful in formatting two strings.
Global and Local variables
strings. Format strings contain curlybraces {} as String Concatenation can be done using + operator.
global Variables: In Python, a variable declared
placeholders or replacement fields which get Simplest method is to use + operator to add multiple
outside of the function or in global scope is known
replaced. We can use positional arguments or strings [Link], the arguments must be a
as a global variable. A global variable can be
keyword arguments to specify the order. string.
accessed inside or outside of the function.
Local Variables Strings varl = "Hello"
print("hello "* 3)
A variable declared inside the function's body or in Strings are one of the most popular data types in var2 = "World"
hello hello hello
the local scope is known as a local variable. Python. var3 = var1 + var2
#output
Strings are created by enclosing various characters print(var3)
within quotes. Python does notdistinguish between 'Hello World' #output
single quotes and double quotes. String Repetition
■Creating strings is very simple in Python The Concatenating strings with the "*" operator can
>>varI= 'Hello Python!' create multipleconcatenated copies of same string.

TUPLE LIST METHODS Dictionary


◾ Tuples are the sequence or series values of append():- Add an element to the end of the list. The Python dictionary is an unordered collection of
different types separated by commas(,) and count():- Returns the count of number of items items or elements.
enclosed in paranthesis(). passed as an argument. All other compound data types in Python have only
◾ Just like strings and lists, values in tuples can also extend():- Add all elements of a list to the another list. values as their elements or itemswhereas the
be accesed by their indexvalues, which are integers index():- Returns the index of the first matched item. dictionary has a key: value pair. Each value is
starting from 0. insert():- Insert an item at the defined index. associated with a key.
◾ Major differences from lists are pop():- Removes and returns an element at the given In the list and the tuple, there are indices that are
▪ Immutable index. only of integer type but in dictionary, we have keys
▪ Enclosed in parentheses copy():- Returns a shallow copy of the list and they can be of any type.
▪ A tuple with a single element must have a remove():- Removes an item from the list. Dictionary is said to be a mapping between some set
comma inside the parentheses:a = (11,) reverse():- Reverse the order of items in the list. of keys and values. Each key isassociated to a value.
>>> mytuple = (11, 22, 33) sort():- Sort items in a list in ascending order. The mapping of a key and value is called as a key-
LIST
◾ List is a sequence of values called items or Sets
value pair and together they arecalled one item or
element.
elements. Mathematically a set is a collection of items not in
◾ The elements can be of any data type. any particular order.
A key and its value are separated by a colon (:)

◾ The list is a most versatile data type available in A Python set is similar to this mathematical
between them.
The items or elements in a dictionary are separated
Python which can bewritten as a list of comma- definition with some additionalfeatures.
by commas and all the elementsmust be enclosed in
separated values (items) between square brackets. The elements in the set cannot be duplicates.
◾ List are mutable, meaning, their elements can be The elements in the set are immutable(cannot be
curly braces.
A pair of curly braces with no values in between is
changed. modified) but the set as a whole ismutable.
◾ In Python programming, a list is created by There is no index attached to any element in a
known as an empty dictionary.
The values in a dictionary can be duplicated, but the
placing all the items(elements) inside a square python set. So they do not supportany indexing or
keys in the dictionary are unique.
bracket [], separated by commas. slicing operation
◾ It can have any number of items and they may be
of different types(integer, float, string etc.).
◾.Differentiate between Type Conversion and ◾. What are the rules that we need to keep in mind ◾. What is the Role of Indentation in Python?
Type Casting while creating Python variables? The identification of a block of code in Python is
Type Conversion is the conversion of object from There are some rules that we need to keep in mind done using Indentation. Most of the programming
one data type to another data type. Implicit Type while creating Python variables. languages like C, C++, and Java use braces { }
Conversion is automatically performed by the • Name of a variable cannot start with a number. It to define a block of code. Python, however, uses
Python interpreter. Explicit Type Conversion is also should start with either an alphabet or the under- indentation. A code block (body of a function, loop,
called Type Casting, the data types of objects are score character. etc.) starts with indentation and ends with the first
converted using predefined functions by the user. • Variable names are always case sensitive and unindented line
◾ Differentiate between Mutable and Immutable can contain alphanumeric characters and the Tuple Assignment
Types underscore character. It allows the assignment of values to a tuple of
Data are stored in a computer’s memory for pro- • Reserved words cannot be used as variable variables on the left side of the assignment from the
cessing. Some of these values can be modified names. tuple of values on the right side of the assignment.
during processing, but contents of others can’t
be altered once they are created in the memory.
◾ . What are the two categories of statements in Union of Sets:- The union operation on two sets
python? produces a new set containing all the distinct
Numbers, strings, and Tuples are immutable, There are two categories of statements in Python: elements from both the sets.
which means their contents can’t be altered after • Expression Statements Intersection of Sets:- The intersection operation on
creation. On the other hand, items in a List or • Assignment Statements two sets produces a new set containing only the
Dictionary object can be modified. It is possible to With the help of expressions, we perform operations common elements from both the sets.
add, delete, insert, and rearrange items in a list or like addition, subtraction, concatenation etc. In oth- Difference of Sets:- The difference operation on two
dictionary. Hence, they are mutable objects. er words, it is a statement that returns a value. sets produces a new set containing only the
Accessing Elements of a List With the help of assignment statements, we create elements from the first set and none from the
Index operator [] is used to access an item in a list new variables, assign values and also change second set.
Index starts from 0 values. Compare Sets:- We can check if a given set is a
Ages=[32,25,40,18]
subset or superset of another set.
print(Ages[0])
The result is True or False depending on the
Output: 32
elements present in the sets.

Change Elements Of a List Deleting Elements from a List List Operators


To change elements use = operator with index[] [Link]() Method 1. Concatenation
>>> ages=[90,18,20] pop() method is used to remove an item at the given This operator concatenates two lists. This is done by
>>> print(ages) index. >>> list1 = [80,20,70,10] the + operator in Python
[90,18,20] >>> [Link](1) 2. Repetition
>>> ages[1]=19 >>> print(list1) [80,70,10] # Output The repetition operator works as suggested by its
>>> print(ages) [90, 19, 20] [Link] opearator name; it repeats the list for a given number of times.
Add Elements to a List del Operator: The del operator deletes the value on Repetition is performed by the * operator.
A new element or item can be added to an existing the provided index, but it does not store the value 3. In Operator
list using append() method. for further use. >>> list1 = ['p','q','r','s'] The In operator tells the user whether the given
This method adds the item to the end of the list >>> del (list1[0]) string exists in the list or not.
>>> ages=[70,60,90] >>> print(list1) ['q', 'r', 's'] # Output It gives a Boolean output, i.e., True or False.
>>> [Link](50) 3. remove Operator [Link]
>>> print(ages) We use the remove operator if we know the item List can be sliced in the same way as strings
>>> [70, 60, 90, 50] #output that we want to remove or delete from the list (but list[start:stop:step]
To insert one item at a desired location use the not the index). >>> list = [10,20,30,40] list[n:m] produces a slice with elements from index
method insert() >>> [Link](10) n to index m-1
>>> print(list) [20,30,40] # Output The Anonymous Functions
The Return Statement The anonymous functions are the functions created
The return statement is used to exit a function. A using a lambda keyword.
function may or may not return a value. Python recursive Functions They are not defined by using def keyword. For this
If a function returns a value, it is passed back by the If a function, procedure or method calls itself, it is reason, they are called anonymous functions.
return statement as argument to the caller. called recursive. We can pass any number of arguments to a lambda
If it does not return a value, simply write return with In Python, also it is possible that a function calls form functions, but still they return only one value in
no arguments itself. the form of expression.
def fact(x): if x == 1: return 1 else: return(x* An anonymous function cannot directly call print
fact(x-1)) command as the lambda needs an expression.

Compound Boolean expression


Formal Arguments
Simple boolean expressions constructed using
Python interpreter figure
Keyword arguments:- The idea is to allow caller to
specify argument name with values so that caller comparison operators can be chained using logical
does not need to remember order of parameters. operators and, or, not to make complex boolean
Example: operators.
Python Comments :-
def student(firstname, lastname):
Comments in Python can be used to explain any
print(firstname, lastname)
program code. It can also be used to hide the code
default argument:- A default argument is a
as well.
parameter that assumes a default value if a value is
Python supports two types of comments:
not provided in the function call for that argument.
1) Single Line Comment:
The following example illustrates Default arguments.
In case user wants to specify a single line comment,
Required arguments:- When we assign the
then comment must start with #
parameters to a function at the time of function
2) Multi Line Comment:
definition, at the time of calling, the arguments
Multi lined comment can be given inside triple
should be passed to a function in correct positional
quotes.
order; furthermore, the number of arguments should
match the defined number of parameters
Variable length arguments:- There are many cases
where we are required to process a function with
more number of arguments than we specified in the
function definition.
The names for these arguments are not specified in
the function definition.
Instead we use an asterisk(*) before the name of the
variable which holds the value for all non keyword
variable arguments

You might also like