0% found this document useful (0 votes)
7 views

Unit I

Parts Python Programming Language
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit I

Parts Python Programming Language
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Unit I

Parts of Python Programming


Language
Identifiers
• An identifier is a name given to a variable, function, class or module.
• Identifiers may be one or more characters in the following format:
• Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). Names like myCountry, other_1
and good_morning, all are valid examples. A Python identifier can begin with
an alphabet (A – Z and a – z and _).
• An identifier cannot start with a digit but is allowed everywhere else. 1plus is
invalid, but plus1 is perfectly fine.
• Keywords cannot be used as identifiers.
• One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
• Identifier can be of any length.
Keywords
• Keywords are a list of reserved
words that have predefined
meaning. Keywords are special
vocabulary and cannot be used
by programmers as identifiers
for variables, functions,
constants or with any identifier
name.
Statements and Expressions
• A statement is an instruction that the Python interpreter can execute.
• Python program consists of a sequence of statements. Statements are
everything that can make up a line (or several lines) of Python code.
• Expression is an arrangement of values and operators which are
evaluated to make a new value. Expressions are statements as well.
• A value is the representation of some entity like a letter or a number
that can be manipulated by a program.

• Example
Variables
• Variable is a named placeholder to hold any type of data which the
program can use to assign and modify during the course of execution.
• In Python, there is no need to declare a variable explicitly by
specifying whether the variable is an integer or a float or any other
type.
• To define a new variable in Python, we simply assign a value to a
name.
Legal Variable Names
• Variable names can consist of any number of letters, underscores and
digits.
• Variable should not start with a number.
• Python Keywords are not allowed as variable names.
• Variable names are case-sensitive. For example, computer and
Computer are different variables.
Best Practices to be followed while naming a
variable
• Python variables use lowercase letters with words separated by
underscores as necessary to improve readability, like this whats_up,
how_are_you. Although this is not strictly enforced, it is considered a best
practice to adhere to this convention.

• Avoid naming a variable where the first character is an underscore. While


this is legal in Python, it can limit the interoperability of your code with
applications built by using other programming languages.

• Ensure variable names are descriptive and clear enough. This allows other
programmers to have an idea about what the variable is representing.
Reading Input
• variable_name = input([prompt])
Writing Output
• print(“Your text here”)

• print(variable name)
• There are two major string formats which are used inside the print()
function to display the contents onto the console as they are less
error prone and results in cleaner code.

• str.format();
• f=strings
str.format()
f-strings()
Assigning Values to Variables

• variable_name = expression
Operators
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
Arithmetic Operator
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
Precedence and Associativity
Data Types
• Numbers
• Boolean
• Strings
• None
Numbers
• Integers, floating point numbers and complex numbers fall under
Python numbers category.
• They are defined as int, float and complex class in Python. Integers
can be of any length; it is only limited by the memory available.
• A floating point number is accurate up to 15 decimal places.
• Integer and floating points are separated by decimal points.
• 1 is an integer, 1.0 is floating point number.
• Complex numbers are written in the form, x + yj, where x is the real
part and y is the imaginary part.
Boolean
• Boolean value, either True or False
• The Boolean values, True and False are treated as reserved words.
Strings
• A string consists of a sequence of one or more characters, which can
include letters, numbers, and other types of characters.
• A string can also contain spaces.
• You can use single quotes or double quotes to represent strings and it
is also called a string literal.
• Multiline strings can be denoted using triple quotes, ''' or """.
Indentation
• In Python, Programs get structured through indentation, Usually, we
expect indentation from any program code,
• but in Python it is a requirement and not a matter of style.
Comments
• Single Line Comment
• use the hash (#) symbol to start writing a comment.

#This is single line Python comment

• Multi Line Comment


• use triple quotes, either ''' or """.

'''This is
multiline comment
in Python using triple quotes'''
Type Conversions
• int()

• float()
Type Conversions
• str()

• chr()
Type Conversion
• complex()
Type Conversion
• ord()
Type Conversion
• hex()

• oct()
Control Flow Statements
Control Flow Statements
The if Decision Control Flow Statement
The if…else Decision Control Flow Statement
The if…elif…else Decision Control Statement
Nested if Statement
The while Loop
The for Loop

• range([start ,] stop [, step])


• start → value indicates the beginning of the sequence. If the start argument is not
specified, then the sequence of numbers start from zero by default.
• stop → Generates numbers up to this value but not including the number itself.
• step → indicates the difference between every two consecutive numbers in the
sequence. The step value can be both negative and positive but not zero.
The continue and break Statements
Functions
Built in Functions
• The Python interpreter has a number of functions that are built into it

• input(), print(), range()


Commonly Used Modules
• Modules in Python are reusable libraries of code having .py extension,
which implements a group of methods and statements.
• Python comes with many built-in modules as part of the standard
library.
• To use a module in your program, import the module using import
statement.
• All the import statements are placed at the beginning of the program.
Commonly Used Modules
Function Definition and Calling the Function
Function Definition and Calling the Function
• In Python, a function definition consists of the def keyword, followed
by
• The name of the function. The function’s name has to adhere to the same
naming rules as variables: use letters, numbers, or an underscore, but the
name cannot start with a number. Also, you cannot use a keyword as a
function name.
• A list of parameters to the function are enclosed in parentheses and
separated by commas. Some functions do not have any parameters at all
while others may have one or more parameters.
• A colon is required at the end of the function header. The first line of the
function definition which includes the name of the function is called the
function header.
• Block of statements that define the body of the function start at the next line
of the function header and they must have the same indentation level.
Function Call
• Defining a function does not execute it.
• Defining a function simply names the function and specifies what to
do when the function is called.
• Calling the function actually performs the specified actions with the
indicated parameters.
Executing the Function

• Before executing the code in the source program, the Python interpreter
automatically defines few special variables.
• If the Python interpreter is running the source program as a stand-alone main
program, it sets the special built-in __name__ variable to have a string value
"__main__".
• After setting up these special variables, the Python interpreter reads the program
to execute the code found in it.
• All of the code that is at indentation level 0 gets executed. Block of statements in
the function definition is not executed unless the function is called.
Sample Programs
Sample Programs
Sample Programs
The return Statement and void Function
Example
Scope and Lifetime of Variables
• Python programs have two scopes: global and local.
• A variable is a global variable if its value is accessible and modifiable
throughout your program.
• A variable that is defined inside a function definition is a local variable.
Scope and Lifetime of Variables
Scope and Lifetime of Variables
Default Parameters
Keyword Arguments
• Until now you have seen that whenever you call a function with some
values as its arguments, these values get assigned to the parameters in the
function definition according to their position.
• In the calling function, you can explicitly specify the argument name along
with their value in the form kwarg = value.
• In the calling function, keyword arguments must follow positional
arguments.
• All the keyword arguments passed must match one of the parameters in
the function definition and their order is not important.
• No parameter in the function definition may receive a value more than
once.
Example
Example
Strings
Creating and Storing Strings
• Strings are another basic data type available in Python.
• They consist of one or more characters surrounded by matching
quotation marks.
Creating and Storing Strings
The str() Function
• The str() function returns a string which is considered an informal or
nicely printable representation of the given object.

• str(object)
Basic String Operation
• In Python, strings can also be concatenated using + sign and *
operator is used to create a repeated sequence of strings.
String Comparison
• You can use (>, <, <=, >=, ==,
!=) to compare two strings
resulting in either Boolean
True or False value.
• Python compares strings using
ASCII value of the characters.
Built-In Functions Used on Strings
Accessing Characters in String by Index
Number

• The syntax for accessing an individual character in a string is as shown


below.
• string_name[index]
Accessing Characters in String by Index
Number
• Negative Indexing
• You can also access individual characters in a string using negative indexing.
• If you have a long string and want to access end characters in the string, then
you can count backward from the end of the string starting from an index
number of −1.
String Slicing and Joining
• The "slice" syntax is a handy way to refer to sub-parts of sequence of
characters within an original string. The syntax for string slicing is,

• With string slicing, you can access a sequence of characters by


specifying a range of indexnumbers separated by a colon.
String Slicing and Joining (Cont.,)
Specifying Steps in Slice Operation
• In the slice operation, a third argument called step which is an
optional can be specified along with the start and end index numbers.
• This step refers to the number of characters that can be skipped after
the start indexing character in the string.
• The default value of step is one.
Palindrome Example
Joining Strings Using join() Method
• Strings can be joined with the join() string.
• The join() method provides a flexible way to concatenate strings.
• The syntax of join() method is,

string_name.join(sequence)
Example
Split Strings Using split() Method
• The split() method returns a list of string items by breaking up the
string using the delimiter string.
• The syntax of split() method is,

string_name.split([separator [, maxsplit]])
Strings Are Immutable
• As strings are immutable,
it cannot be modified.
The characters in a string
cannot bechanged once a
string value is assigned to
string variable.
String Traversing
• Since the string is a sequence of characters, each of these characters
can be traversed using the for loop.
String Methods
String Methods
String Methods
String Methods
String Methods
String Methods

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy