KEMBAR78
Unit_I-Introduction python programming (1).pptx
Course Title: PYTHON PROGRAMMING
What is Python?
● Python is a popular high-level programming language used in various
applications
○ Python is an easy language to learn because of its simple syntax
○ Python can be used for simple tasks such as plotting or for more complex tasks like
machine learning
Variables, Objects, and Classes
● A variable is a reference to a value stored in a computer’s memory.
● Variables can be sorted into a variety of categories (or data types) such
as numbers (int/float etc), Boolean values (true/false), and
sequences (strings, lists etc).
● An object is a collection of data from a computer’s memory that can be
manipulated.
○ ALL VARIABLES ARE OBJECTS although some objects can be defined by data
referred to by multiple variables.
○ Methods are the functions used to act on/alter an object’s data. They
describe what your object can “do.”
Variables, Objects, and Classes (cont.)
● A class is a collection of objects
who share the same set of
variables/methods.
○ The definition of the class provides a
blueprint for all the objects within it
(instances).
○ Instances may share the same
variables (color, size, shape, etc.), but
they do NOT share the same values
for each variable (blue/red/pink,
small/large, square/circular etc.)
Instance #1
Color: Pink
Name: Polo
Instance #2
Color: Red
Name: Mini
Instance #3
Color: Blue
Name: Beetle
Basic Syntax Rules
● The name of your variable (myInt etc.) is placed on the left of the “=“ operator.
○ Most variable names are in camel case where the first word begins with a lowercase letter and any subsequent words
are capitalized
○ Variable names may also appear in snake case where all words are lowercase, with underscores between words
● The assignment operator (“=“) sets the variable name equal to the memory location where your value is found.
● The value of your variable (“Hello, World”) is placed on the right of the “=“ operator.
○ The type of this value does NOT need to be stated but its format must abide by a given object type (as shown).
myString = “Hello, World” myInt = 7
myFloat = 7.0
myList = [7, 8, 9] myBoolean = true
Basic Syntax Rules
● Function Syntax
○ def...: indicates that you are defining a new function.
○ function() refers to the name of your function. By convention, this name is typically lowercase and represents a verb/action.
○ a,b refers to parameters (values or variables) that can be used within the statements of your function’s definition (......). If
your function has no parameters, an empty parenthetical () is used.
○ The return statement is an optional statement that will return a value for your function to your original call.
def function(a, b):
......
return a + b
Basic Syntax Rules (cont.)
● Calling a function
○ Call the function by referring to its name (function()) and by placing
any necessary arguments (1, 2) within the parenthesis separated by
commas. myValue = function(1, 2)
○ If you wish, you can set your function call equal to a variable (myValue). The value
returned by the function will be assigned to your variable name.
myValue = function(1, 2)
Common Data Types and Operators
● A data type is a means of classifying a value and determining what operations can
be performed on it. All objects have a data type.
● Operators are symbols used carry out specific functions/computations.
● https://www.youtube.com/watch?v=v5MR5JnKcZI
Input/Output
● Input functions (input()) allow users of a program to place values into
programming code.
○ The parameter for an input function is called a prompt. This is a
string (this can be indicated by “” or ‘’) such as “Enter a number: “
○ The user’s response to the prompt will be returned to the input
statement call as a string. To use this value as any other data
type, it must be converted with another function (int()).
● Print functions (print()) allow programs to output strings to users on a
given interface.
○ The parameter of this function is of any type. All types will
automatically be converted to strings.
xString = input(“Enter a number: “)
x = int(xString)
y=x+2
print(y)
strings and its operations
● Python string methods is a collection of in-built Python functions that
operates on strings.
● Python string is a sequence of Unicode characters that is enclosed in
quotation marks. In this class, we will discuss the in-built string functions
i.e. the functions provided by Python to operate on strings.
Case Changing of Python String Methods
The below Python functions are used to change the case of the strings. Let’s
look at some Python string methods with examples:
● lower(): Converts all uppercase characters in a string into lowercase
● upper(): Converts all lowercase characters in a string into uppercase
● title(): Convert string to title case
● swapcase(): Swap the cases of all characters in a string
● capitalize(): Convert the first character of a string to uppercase
# Python program to show the
# working of upper() function
text = ‘joy university‘
# upper() function to convert
# string to upper case
print("nConverted String:")
print(text.upper()) #output: JOY UNIVERSITY
# lower() function to convert
# string to lower case
print("nConverted String:")
print(text.lower()) #output: joy university
# converts the first character to
# upper case and rest to lower case
print("nConverted String:")
print(text.title()) #output: Joy University
# swaps the case of all characters in the string
# upper case character to lowercase and viceversa
print("nConverted String:")
print(text.swapcase()) #output: JOY UNIVERSITY
# convert the first character of a string to uppercase
print("nConverted String:")
print(text.capitalize()) #output: Joy University
# original string never changes
print("nOriginal String")
print(text) #output: JOY UNIVERSITY
List of String Methods in Python
Function Name Description
capitalize()
Converts the first character of the string to a
capital (uppercase) letter
casefold() Implements caseless string matching
center() Pad the string with the specified character.
count()
Returns the number of occurrences of a
substring in the string.
encode()
Encodes strings with the specified encoded
scheme
endswith()
Returns “True” if a string ends with the given
suffix
expandtabs()
Specifies the amount of space to be
substituted with the “t” symbol in the
find()
Returns the lowest index of the substring if it
is found
format() Formats the string for printing it to console
format_map() Formats specified values in a string using a dictionary
index()
Returns the position of the first occurrence of a substring
in a string
isalnum()
Checks whether all the characters in a given string is
alphanumeric or not
isalpha() Returns “True” if all characters in the string are alphabets
isdecimal() Returns true if all characters in a string are decimal
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
islower() Checks if all characters in the string are lowercase
isnumeric()
Returns “True” if all characters in the string are numeric
characters
isprintable()
Returns “True” if all characters in the string are printable
or the string is empty
isspace()
Returns “True” if all characters in the string are
whitespace characters
List of String Methods in Python
istitle() Returns “True” if the string is a title cased string
isupper() Checks if all characters in the string are uppercase
join() Returns a concatenated String
ljust() Left aligns the string according to the width specified
lower()
Converts all uppercase characters in a string into
lowercase
lstrip() Returns the string with leading characters removed
maketrans() Returns a translation table
partition()
Splits the string at the first occurrence of the
separator
replace()
Replaces all occurrences of a substring with another
substring
rfind() Returns the highest index of the substring
rindex()
Returns the highest index of the substring inside the
string
rjust()
Right aligns the string according to the width
specified
rpartition() Split the given string into three parts
rsplit()
Split the string from the right by the specified
separator
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
startswith()
Returns “True” if a string starts with the given
prefix
strip()
Returns the string with both leading and trailing
characters
swapcase()
Converts all uppercase characters to lowercase
and vice versa
title() Convert string to title case
translate()
Modify string according to given translation
mappings
upper()
Converts all lowercase characters in a string into
uppercase
zfill()
Returns a copy of the string with ‘0’ characters
padded to the left side of the string
Python String Methods – FAQs
● What are the common String Methods in Python?
Python provides a variety of string methods for manipulating and working with strings.
Some of the most common string methods include:
● upper(): Converts all characters in a string to uppercase.
● lower(): Converts all characters in a string to lowercase.
● find(substring): Returns the lowest index in the string where the substring is found.
● strip(): Removes any leading and trailing characters (space is the default).
● replace(old, new): Replaces occurrences of a substring within the string.
● split(delimiter): Splits the string at the specified delimiter and returns a list of
substrings.
● join(iterable): Concatenates elements of an iterable with a specified separator.
● startswith(prefix): Checks if the string starts with the specified prefix.
● endswith(suffix): Checks if the string ends with the specified suffix.
● How to Find a Substring in Python?
To find a substring in a string, you can use the find() method. It returns the lowest
index of the substring if it is found. If the substring is not found, it returns -1.
Example:
● text = "Hello, World!"
index = text.find("World")
print(index) # Output: 7
# If the substring is not found
index = text.find("Python")
print(index) # Output: -1
● How to Convert a String to Lower Case in Python?
You can convert all characters in a string to lowercase using the lower() method.
Example:
● text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text) # Output: hello, world!
● What is the strip() Method Used for in Python?
The strip() method is used to remove leading and trailing characters from a
string. By default, it removes whitespace, but you can specify a different
character or set of characters to remove.
Example:
● text = " Hello, World! "
stripped_text = text.strip()
print(stripped_text) # Output: "Hello, World!"
# Removing specific characters
text = "###Hello, World!###"
stripped_text = text.strip("#")
print(stripped_text) # Output: "Hello, World!"
● How to Replace Characters in a String in Python?
To replace characters or substrings in a string, you can use the replace() method.
It replaces all occurrences of the specified substring with another substring.
Example:
● text = "Hello, World!"
replaced_text = text.replace("World", "Python")
print(replaced_text) # Output: Hello, Python!
# Replacing characters
text = "banana"
replaced_text = text.replace("a", "o")
print(replaced_text) # Output: bonono
If-else Statements
● If-else statements allow programmers to adapt the function of their
code based on a given condition.
● If a given condition (i.e. x % 2 == 0) is true, then the statements
following the if statement (if) will be executed. If the condition is false,
the statements following the else statement (else) will be executed.
○ The condition is tested using the Boolean operators == (is equal
to), != (is not equal to), and (used to test multiple conditions),
and or (used to test if AT LEAST ONE condition is true).
○ Additionally, else-if statements (elif) can be used to provide
unique coding statements for multiple conditions.
xString = input(“Enter a number: “)
x = int(xString)
if x % 2 == 0:
print(“This is an even number”)
elif x == 0:
print(“This number equals 0”)
else:
print(“This is an odd number”)
For Loops
● For loops perform the same task (iterate) for the number of
times specified by an iterable (something that can be evaluated
repeatedly such as a list, string, or range).
● for defines the for loop
● x is the variable defining the number of times the statements
within the loop (print(myInt)) are executed.
● The range(start, stop, step) function is often used to define x.
○ The starting value is defined by start, the final value is
defined by stop – 1, and the magnitude at which x
changes between loops is defined by step.
● in is a Boolean operator that returns true if the given value (x) is
found within a given list, string, range etc.
myString = input(“Enter a number: “)
myInt = int(myString)
for x in range(0, 5, 1): print(myInt)
While Loops
● While loops are statements that iterate so long as a given
Boolean condition is met.
○ x (the variable determining whether or not the
condition is met) is defined and manipulated
OUTSIDE of the header of the while loop (while)
○ The condition (x < 5) is a statement containing a
Boolean variable.
○ break is a statement used to exit the current
for/while loop.
○ continue is a statement used to reject all
statements in the current for/while loop iteration
and return to the beginning of the loop.
myString = input(“Enter a number: “)
myInt = int(myString)
x = 0
while x < 5:
print(myInt)
x= x +1

Unit_I-Introduction python programming (1).pptx

  • 1.
  • 2.
    What is Python? ●Python is a popular high-level programming language used in various applications ○ Python is an easy language to learn because of its simple syntax ○ Python can be used for simple tasks such as plotting or for more complex tasks like machine learning
  • 3.
    Variables, Objects, andClasses ● A variable is a reference to a value stored in a computer’s memory. ● Variables can be sorted into a variety of categories (or data types) such as numbers (int/float etc), Boolean values (true/false), and sequences (strings, lists etc). ● An object is a collection of data from a computer’s memory that can be manipulated. ○ ALL VARIABLES ARE OBJECTS although some objects can be defined by data referred to by multiple variables. ○ Methods are the functions used to act on/alter an object’s data. They describe what your object can “do.”
  • 4.
    Variables, Objects, andClasses (cont.) ● A class is a collection of objects who share the same set of variables/methods. ○ The definition of the class provides a blueprint for all the objects within it (instances). ○ Instances may share the same variables (color, size, shape, etc.), but they do NOT share the same values for each variable (blue/red/pink, small/large, square/circular etc.) Instance #1 Color: Pink Name: Polo Instance #2 Color: Red Name: Mini Instance #3 Color: Blue Name: Beetle
  • 5.
    Basic Syntax Rules ●The name of your variable (myInt etc.) is placed on the left of the “=“ operator. ○ Most variable names are in camel case where the first word begins with a lowercase letter and any subsequent words are capitalized ○ Variable names may also appear in snake case where all words are lowercase, with underscores between words ● The assignment operator (“=“) sets the variable name equal to the memory location where your value is found. ● The value of your variable (“Hello, World”) is placed on the right of the “=“ operator. ○ The type of this value does NOT need to be stated but its format must abide by a given object type (as shown). myString = “Hello, World” myInt = 7 myFloat = 7.0 myList = [7, 8, 9] myBoolean = true
  • 6.
    Basic Syntax Rules ●Function Syntax ○ def...: indicates that you are defining a new function. ○ function() refers to the name of your function. By convention, this name is typically lowercase and represents a verb/action. ○ a,b refers to parameters (values or variables) that can be used within the statements of your function’s definition (......). If your function has no parameters, an empty parenthetical () is used. ○ The return statement is an optional statement that will return a value for your function to your original call. def function(a, b): ...... return a + b
  • 7.
    Basic Syntax Rules(cont.) ● Calling a function ○ Call the function by referring to its name (function()) and by placing any necessary arguments (1, 2) within the parenthesis separated by commas. myValue = function(1, 2) ○ If you wish, you can set your function call equal to a variable (myValue). The value returned by the function will be assigned to your variable name. myValue = function(1, 2)
  • 8.
    Common Data Typesand Operators ● A data type is a means of classifying a value and determining what operations can be performed on it. All objects have a data type. ● Operators are symbols used carry out specific functions/computations. ● https://www.youtube.com/watch?v=v5MR5JnKcZI
  • 9.
    Input/Output ● Input functions(input()) allow users of a program to place values into programming code. ○ The parameter for an input function is called a prompt. This is a string (this can be indicated by “” or ‘’) such as “Enter a number: “ ○ The user’s response to the prompt will be returned to the input statement call as a string. To use this value as any other data type, it must be converted with another function (int()). ● Print functions (print()) allow programs to output strings to users on a given interface. ○ The parameter of this function is of any type. All types will automatically be converted to strings. xString = input(“Enter a number: “) x = int(xString) y=x+2 print(y)
  • 10.
    strings and itsoperations ● Python string methods is a collection of in-built Python functions that operates on strings. ● Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this class, we will discuss the in-built string functions i.e. the functions provided by Python to operate on strings. Case Changing of Python String Methods The below Python functions are used to change the case of the strings. Let’s look at some Python string methods with examples: ● lower(): Converts all uppercase characters in a string into lowercase ● upper(): Converts all lowercase characters in a string into uppercase ● title(): Convert string to title case ● swapcase(): Swap the cases of all characters in a string ● capitalize(): Convert the first character of a string to uppercase # Python program to show the # working of upper() function text = ‘joy university‘ # upper() function to convert # string to upper case print("nConverted String:") print(text.upper()) #output: JOY UNIVERSITY # lower() function to convert # string to lower case print("nConverted String:") print(text.lower()) #output: joy university # converts the first character to # upper case and rest to lower case print("nConverted String:") print(text.title()) #output: Joy University # swaps the case of all characters in the string # upper case character to lowercase and viceversa print("nConverted String:") print(text.swapcase()) #output: JOY UNIVERSITY # convert the first character of a string to uppercase print("nConverted String:") print(text.capitalize()) #output: Joy University # original string never changes print("nOriginal String") print(text) #output: JOY UNIVERSITY
  • 11.
    List of StringMethods in Python Function Name Description capitalize() Converts the first character of the string to a capital (uppercase) letter casefold() Implements caseless string matching center() Pad the string with the specified character. count() Returns the number of occurrences of a substring in the string. encode() Encodes strings with the specified encoded scheme endswith() Returns “True” if a string ends with the given suffix expandtabs() Specifies the amount of space to be substituted with the “t” symbol in the find() Returns the lowest index of the substring if it is found format() Formats the string for printing it to console format_map() Formats specified values in a string using a dictionary index() Returns the position of the first occurrence of a substring in a string isalnum() Checks whether all the characters in a given string is alphanumeric or not isalpha() Returns “True” if all characters in the string are alphabets isdecimal() Returns true if all characters in a string are decimal isdigit() Returns “True” if all characters in the string are digits isidentifier() Check whether a string is a valid identifier or not islower() Checks if all characters in the string are lowercase isnumeric() Returns “True” if all characters in the string are numeric characters isprintable() Returns “True” if all characters in the string are printable or the string is empty isspace() Returns “True” if all characters in the string are whitespace characters
  • 12.
    List of StringMethods in Python istitle() Returns “True” if the string is a title cased string isupper() Checks if all characters in the string are uppercase join() Returns a concatenated String ljust() Left aligns the string according to the width specified lower() Converts all uppercase characters in a string into lowercase lstrip() Returns the string with leading characters removed maketrans() Returns a translation table partition() Splits the string at the first occurrence of the separator replace() Replaces all occurrences of a substring with another substring rfind() Returns the highest index of the substring rindex() Returns the highest index of the substring inside the string rjust() Right aligns the string according to the width specified rpartition() Split the given string into three parts rsplit() Split the string from the right by the specified separator rstrip() Removes trailing characters splitlines() Split the lines at line boundaries startswith() Returns “True” if a string starts with the given prefix strip() Returns the string with both leading and trailing characters swapcase() Converts all uppercase characters to lowercase and vice versa title() Convert string to title case translate() Modify string according to given translation mappings upper() Converts all lowercase characters in a string into uppercase zfill() Returns a copy of the string with ‘0’ characters padded to the left side of the string
  • 13.
    Python String Methods– FAQs ● What are the common String Methods in Python? Python provides a variety of string methods for manipulating and working with strings. Some of the most common string methods include: ● upper(): Converts all characters in a string to uppercase. ● lower(): Converts all characters in a string to lowercase. ● find(substring): Returns the lowest index in the string where the substring is found. ● strip(): Removes any leading and trailing characters (space is the default). ● replace(old, new): Replaces occurrences of a substring within the string. ● split(delimiter): Splits the string at the specified delimiter and returns a list of substrings. ● join(iterable): Concatenates elements of an iterable with a specified separator. ● startswith(prefix): Checks if the string starts with the specified prefix. ● endswith(suffix): Checks if the string ends with the specified suffix.
  • 14.
    ● How toFind a Substring in Python? To find a substring in a string, you can use the find() method. It returns the lowest index of the substring if it is found. If the substring is not found, it returns -1. Example: ● text = "Hello, World!" index = text.find("World") print(index) # Output: 7 # If the substring is not found index = text.find("Python") print(index) # Output: -1
  • 15.
    ● How toConvert a String to Lower Case in Python? You can convert all characters in a string to lowercase using the lower() method. Example: ● text = "Hello, World!" lowercase_text = text.lower() print(lowercase_text) # Output: hello, world!
  • 16.
    ● What isthe strip() Method Used for in Python? The strip() method is used to remove leading and trailing characters from a string. By default, it removes whitespace, but you can specify a different character or set of characters to remove. Example: ● text = " Hello, World! " stripped_text = text.strip() print(stripped_text) # Output: "Hello, World!" # Removing specific characters text = "###Hello, World!###" stripped_text = text.strip("#") print(stripped_text) # Output: "Hello, World!"
  • 17.
    ● How toReplace Characters in a String in Python? To replace characters or substrings in a string, you can use the replace() method. It replaces all occurrences of the specified substring with another substring. Example: ● text = "Hello, World!" replaced_text = text.replace("World", "Python") print(replaced_text) # Output: Hello, Python! # Replacing characters text = "banana" replaced_text = text.replace("a", "o") print(replaced_text) # Output: bonono
  • 18.
    If-else Statements ● If-elsestatements allow programmers to adapt the function of their code based on a given condition. ● If a given condition (i.e. x % 2 == 0) is true, then the statements following the if statement (if) will be executed. If the condition is false, the statements following the else statement (else) will be executed. ○ The condition is tested using the Boolean operators == (is equal to), != (is not equal to), and (used to test multiple conditions), and or (used to test if AT LEAST ONE condition is true). ○ Additionally, else-if statements (elif) can be used to provide unique coding statements for multiple conditions. xString = input(“Enter a number: “) x = int(xString) if x % 2 == 0: print(“This is an even number”) elif x == 0: print(“This number equals 0”) else: print(“This is an odd number”)
  • 19.
    For Loops ● Forloops perform the same task (iterate) for the number of times specified by an iterable (something that can be evaluated repeatedly such as a list, string, or range). ● for defines the for loop ● x is the variable defining the number of times the statements within the loop (print(myInt)) are executed. ● The range(start, stop, step) function is often used to define x. ○ The starting value is defined by start, the final value is defined by stop – 1, and the magnitude at which x changes between loops is defined by step. ● in is a Boolean operator that returns true if the given value (x) is found within a given list, string, range etc. myString = input(“Enter a number: “) myInt = int(myString) for x in range(0, 5, 1): print(myInt)
  • 20.
    While Loops ● Whileloops are statements that iterate so long as a given Boolean condition is met. ○ x (the variable determining whether or not the condition is met) is defined and manipulated OUTSIDE of the header of the while loop (while) ○ The condition (x < 5) is a statement containing a Boolean variable. ○ break is a statement used to exit the current for/while loop. ○ continue is a statement used to reject all statements in the current for/while loop iteration and return to the beginning of the loop. myString = input(“Enter a number: “) myInt = int(myString) x = 0 while x < 5: print(myInt) x= x +1