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

python ppt

Python is a high-level, interpreted scripting language created by Guido van Rossum in the late 1980s, with its first version released in 1991. It features easy coding, is free and open-source, supports object-oriented programming, and has a large standard library. Python data types are categorized into mutable and immutable types, and it includes various operators for arithmetic, comparison, logical, and bitwise operations.

Uploaded by

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

python ppt

Python is a high-level, interpreted scripting language created by Guido van Rossum in the late 1980s, with its first version released in 1991. It features easy coding, is free and open-source, supports object-oriented programming, and has a large standard library. Python data types are categorized into mutable and immutable types, and it includes various operators for arithmetic, comparison, logical, and bitwise operations.

Uploaded by

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

History

• Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van
Rossum at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
• The initial version was published at the alt.sources newsgroup in 1991, and version 1.0 was released
in 1994.
• Python 2.0 was released in 2000, and the 2.x versions were the prevalent releases until December
2008. At that time, the development team made the decision to release version 3.0.

• Python is still maintained by a core development team at the Institute, and Guido is still in charge,
having been given the title of BDFL (Benevolent Dictator For Life) by the Python community.

• The name Python, by the way, derives not from the snake, but from the British comedy troupe
Monty Python’s Flying Circus, of which Guido was, and presumably still is, a fan.
Features in Python

There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc.

2. Free and Open Source:


Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword.
Download Python
Since it is open-source, this means that source code is also available to the public. So you can
download it as, use it as well as share it.

3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in
python.
PyQt5 is the most popular option for creating graphical apps with Python.

5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember
the system architecture, nor do we need to manage the memory.

6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and
also we can compile that code in C/C++ language.

7. Python is Portable language:


Python language is also a portable language. For example, if we have python code for windows
and if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not
need to change it, we can run this code on any platform.

Feature cont.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with other
languages like c, c++, etc.

9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like
other languages C, C++, Java, etc. there is no need to compile python code this makes it easier to
debug our code. The source code of python is converted into an immediate form called bytecode.

10. Large Standard Library


Python has a large standard library which provides a rich set of module and functions so you do not
have to write your own code for every single thing. There are many libraries present in python for
such as regular expressions, unit-testing, web browsers, etc.

11. Dynamically Typed Language:


Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.)
for a variable is decided at run time not in advance because of this feature we don’t need to specify
the type of variable.

Feature cont.
Python variables

Rohit

puja Soham

How I
store
Data??

Rahul
student

Rohit

0X2258
Python Data Types

• Data type defines the type of the variable .


• Every variable associated with a datatype.

Python Data Types

Python data types are divided in two categories, mutable data types and immutable data
types.

Immutable Data types in Python


1. Numeric
2. String
3. Tuple

Mutable Data types in Python


1. List
2. Dictionary
3. Set
•Mutable Data Types: Data types in python where the value assigned to a variable
can be changed
•Immutable Data Types: Data types in python where the value assigned to a variable
Numeric Data Type in Python
Integer – In Python 3, there is no upper bound on the integer number which means we can
have the value as large as our system memory allows.

# Integer number
num = 100
print(num)
print("Data Type of variable num is", type(num))

Output
Float – Values with decimal points are the float values, there is no need to specify the data type in
Python. It is automatically inferred based on the value we are assigning to a variable. For example
here fnum is a float data type.

# float number
fnum = 34.45
print(fnum)
print("Data Type of variable fnum is", type(fnum))

Output:
Complex Number – Numbers with real and imaginary parts are known as complex numbers. Unlike
other programming language such as Java, Python is able to identify these complex numbers with the
values. In the following example when we print the type of the variable cnum, it prints as complex
number.

# complex number
cnum = 3 + 4j
print(cnum)
print("Data Type of variable cnum is", type(cnum))

Output:
Complex Numbers Data Types

• Complex numbers have a real and imaginary part, a + bc, where a is the real part and b is the
imaginary part
• Complex numbers are specified as <real part>+<imaginary part>j. .
(Example – 5 + 10j).

For example:
(2+3j)
type(2+3j)
Output:
complex
Boolean Data Types
• These values can be used for assigning and comparison.
• boolean values True and False.
• Booleans are a subtype of plain integers.
Example 1 Boolean Data Type: Example 3 Boolean Data Type :

A=True; var1 = 0
B=False; print(bool(var1))
print(A&B) ;
print(A|B); var2 = 1
Output: print(bool(var2))
False
True Output:
Example 2 Boolean Data Type : False
True
print(True+False+True)
Output:

2
Note: Python treats a True value as 1 and a False value as 0. So the above example returns 2(1+0+1).
Binary, Octal and Hexadecimal numbers
In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
prefixes.
0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number
0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number
0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number
Output:
# integer equivalent of binary number 101
num = 0b101
print(num)

# integer equivalent of Octal number 32


num2 = 0o32
print(num2)

# integer equivalent of Hexadecimal number FF


num3 = 0xFF
print(num3)
Operators are special
symbols in Python that
carry out arithmetic or
logical computation. The Arithmetic Operators
value that the operator
operates on is called the
Comparison Operators
operand.

Logical Operators
operator
Bitwise Operator

Assignment Operator

Identity Operator

Membership Operator
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like
addition, subtraction, multiplication, and division.

Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/
Division (float): divides the first operand by x/y
the second

//
Division (floor): divides the first operand by x // y
the second

%
Modulus: returns the remainder when the x%y
first operand is divided by the second

** Power: Returns first raised to power second x ** y


# Examples of Arithmetic Operator
a=9
b=4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
Output
mul = a * b 13
# Division(float) of number
5
div1 = a / b 36
# Division(floor) of number
2.25
div2 = a // b 2
# Modulo of both number
1
mod = a % b 6561
# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Comparison operators:

Comparison operators are used to compare values. It returns either True or False according to the condition.

Operator Description Syntax

> Greater than: True if the left operand is greater x>y


than the right

< Less than: True if the left operand is less than the x<y
right

== Equal to: True if both operands are equal x == y

!= Not equal to – True if operands are not equal x != y

>= Greater than or equal to True if the left operand is x >= y


greater than or equal to the right

<= Less than or equal to True if the left operand is less x <= y
than or equal to the right
# Examples of Relational Operators
a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True Output


print(a < b) False
True
# a == b is False False
print(a == b) True
False
# a != b is True True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)
Logical Operators

Logical operators perform Logical AND, Logical OR, and Logical NOT (and, or,
not )operations. It is used to combine conditional statements.

Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if the operand is false not x

# Examples of Logical Operator


a = True
b = False

# Print a and b is False


Output
print(a and b)
False
True
# Print a or b is True
False
print(a or b)

# Print not a is False


print(not a)
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to
operate on binary numbers.
Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<


# Examples of Bitwise operators
a = 10
b=4

# Print bitwise AND operation


print(a & b)

# Print bitwise OR operation


Output
print(a | b)
0
14
# Print bitwise NOT operation
-11
print(~a)
14
2
# print bitwise XOR operation
40
print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)
Assignment Operators
Assignment operators are used to assigning values to the variables.
Operator Description Syntax

= Assign value of right side of expression to left side operand x=y+z

+= Add AND: Add right-side operand with left side operand and then assign to left operand a+=b a=a+b

-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b

*= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b a=a*b

/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b

%= Modulus AND: Takes modulus using left and right operands and assign the result to left operand a%=b a=a%b

//=
Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left a//=b a=a//b
operand

**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b a=a**b

&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b

|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b

^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b

>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b

<<= Performs Bitwise left shift on operands and assign value to left operand a <<= b a= a << b
# Examples of Assignment Operators
a = 10

# Assign value
b=a
print(b)

# Add and assign value


b += a
print(b) Output
10
# Subtract and assign value 20
b -= a 10
print(b) 100
102400
# multiply and assign
b *= a
print(b)

# bitwise lishift operator


b <<= a
print(b)
Identity Operators
is and is not are the identity operators both are used to check if two values are located on the
same part of the memory. Two variables that are equal do not imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical

Example: Identity Operator

a = 10
b = 20
Output
c=a
True
True
print(a is not b)
print(a is c)
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence
Example: Membership Operator
# not 'in’ and in operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list): Output


print("x is NOT present in given list") x is NOT present in given list
else: y is present in given list
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Python Token:
A token is the smallest individual meaningful component in a python program
1. Keywords: Keywords are words that have some special meaning or significance
in a programming language. They can’t be used as variable names, function names,
or any other random purpose.
2. Identifiers: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language and it has some
rules and regulations to name an identifier.

Rules

1. Python is case-sensitive. So case matters in naming identifiers. And


hence Apple and apple are two different identifiers.
2. Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ).
It can’t start with any other character.
3. Except for letters and underscore, digits can also be a part of identifier but can’t be
the first character of it.
4. Any other special characters or whitespaces are strictly prohibited in an identifier.
5. An identifier can’t be a keyword.
Literals:
Literals are defined as raw value or data given in a variable or
constant.
(i) String Literals (ii) Character Literals:(iii) Numeric Literals: (iv) Boolean Literals:

(v) Special Literals(vi) Literals Collections

Integer Literal:
Float Literal:
List: Complex Literal:
Tuple:
Dictionary:
Set:
Python string:

• Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
• Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters.

‘’’ I am going to
‘Hello world’ “Hello world”
School ’’’
#Using single quotes
str1 = 'Hello Python' Output:
print(str1) Hello Python
#Using double quotes Hello Python

str2 = "Hello Python" Triple quotes are generally used for


represent the multiline or
print(str2) docstring

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example,
The string "HELLO" is indexed as given in the below figure.

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index does
n't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
The slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given
string. Consider the following example.
# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:

JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1. The second rightmost index indicates -2, and so on.
Consider the following image.

Consider the following example


str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings Example 2
Updating the content of the strings is as easy as str = "HELLO"
assigning it to a new string. The string object print(str)
str = "hello"
doesn't support item assignment i.e., A string can print(str)
only be replaced with new string since its content Output:
cannot be partially replaced. Strings are immutable
in Python. HELLO
hello
Consider the following example.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
Output:
Traceback (most recent call last):
File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.
str = "JAVATPOINT"
del str[1]
Output:

TypeError: 'str' object doesn't support item deletion


str1 = "JAVATPOINT"
del str1
print(str1)
Output:

NameError: name 'str1' is not defined


String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given either


side of the operator.

* It is known as repetition operator. It concatenates the multiple copies of the


same string.

[] It is known as slice operator. It is used to access the sub-strings of a


particular string.

[:] It is known as range slice operator. It is used to access the characters from
the specified range.

in It is known as membership operator. It returns if a particular sub-string is


present in the specified string.

not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where
we need to print the actual meaning of escape characters such as
"C://python". To define any string as a raw string, the character r or R is
followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers


used in C programming like %d or %f to map their values in python.
Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Description
Python string method upper() returns a copy of the string in which all case-based characters have been
uppercased.
Syntax
Following is the syntax for upper() method −
str.upper()

Example
The following example shows the usage of upper()
method.

str = (this is string example....wow!!!“)


print "str.capitalize() : ", str.upper()

When we run above program, it produces following result


str.capitalize() : THIS IS STRING EXAMPLE....WOW!!!


Python String find() method

Definition and Usage


• The find() method finds the first occurrence of the specified
value.
• The find() method returns -1 if the value is not found.
• The find() method is almost the same as the index() method,
the only difference is that the index() method raises an
exception if the value is not found
Syntax

string.find(value, start, end)

Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Example

txt = "Hello, welcome to my world." txt = "Hello, welcome to my world."

x = txt.find("welcome") x = txt.find("e", 5, 10)

print(x) print(x)

output 21 output
8

txt = "Hello, welcome to my world."

print(txt.find("q"))
print(txt.index("q"))

output -1
lower() method

Definition and Usage


• The lower() method returns a string where all characters are
lower case.

• Symbols and Numbers are ignored.

Syntax
string.lower()

Example

txt = "Hello my FRIENDS"

x = txt.lower()

print(x)
capitalize() Method

Definition and Usage


The capitalize() method returns a string where the first character is upper case, and the rest is lower case.

Example
txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

output

Hello, and welcome to my world.


String count() Method

Definition and Usage


• The count() method returns the number of times a specified value appears in the string.

Syntax

string.count(value, start, end)

Parameter Description
value Required. A String. The string to value to search for
start Optional. An Integer. The position to start the search. Default is 0
end Optional. An Integer. The position to end the search. Default is the end of the string
Example
txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

Example
Search from position 10 to 24:

txt = "I love apples, apple are my favorite


fruit"

x = txt.count("apple", 10, 24)

print(x)
String join() Method

Python String join() method is a string method and returns a string in which the elements of
the sequence have been joined by the str separator.

Syntax:
string_name.join(iterable)
Parameters:
The join() method takes iterable – objects capable of returning their
members one at a time. Some examples are List, Tuple, String,
Dictionary, and Set
Return Value:
The join() method returns a string concatenated with the elements
of iterable.
list1 = ['1','2','3','4']
s = "-"
s = s.join(list1)
print(s)

Output
1-2-3-4
len()

The len() function returns the number of items (length) in an object.

len() Syntax
The syntax of len() is: len(s)

len() Parameters
The len() function takes a single argument s, which can be

sequence - string, bytes, tuple, list, range OR,


collection - dictionary, set, frozen set
testString = ' '
print('Length of', testString, 'is', len(testString))

testString = 'Python'
print('Length of', testString, 'is', len(testString))

Output:
Length of is 0
Length of Python is 6
isalnum()
It checks if all the characters are alphanumeric then returns True

Syntax:
str_name.isalnum() name = "M234onica"
print(name.isalnum())

# contains whitespace
Output:
name = "M3onica Gell22er "
True
print(name.isalnum())
False
True
name = "Mo3nicaGell22er"
True
print(name.isalnum())

name = "133"
print(name.isalnum())
Working of isalnum()

name = "M0n1caG3ll3r"

if name.isalnum() == True:
print("All characters of string (name) are alphanumeric.")
else:
print("All characters are not alphanumeric.")
isalpha()

It checks if all the characters are alphabet (a-z) then returns True

Syntax: name = "Monica"


str_name.isalpha() print(name.isalpha())

# contains whitespace
name = "Monica Geller"
print(name.isalpha())

# contains number
name = "Mo3nicaGell22er"
print(name.isalpha())

Output:
True
False
False
name = "MonicaGeller"

if name.isalpha() == True:
print("All characters are alphabets")
else:
print("All characters are not alphabets.")

Output:
All characters are alphabets
isdigit() method
The isdigit() method returns True if all characters in a string are digits. If not, it returns False.

Example Syntax of String isdigit()


str1 = '342'
print(str1.isdigit()) string.isdigit()

str2 = 'python'
print(str2.isdigit()) s = '23455'
print(s.isdigit())
# Output: True
# False #s = '²3455'
# subscript is a digit
s = '\u00B23455'
print(s.isdigit())

# s = '½'
# fraction is not a digit
s = '\u00BD'
print(s.isdigit())
True
True
False
islower() islower() is a built-in method used for string handling. The islower() method returns True if
all characters in the string are lowercase, otherwise, returns “False”.

Syntax :
string.islower() string = 'geeksforgeeks'
print(string.islower())

string = 'GeeksforGeeks'
print(string.islower())

Output:

True
False
isupper() In Python, isupper() is a built-in method used for string handling. This
method returns True if all characters in the string are uppercase,
otherwise, returns “False”.

Syntax : Examples:

string.isupper() string = 'GEEKSFORGEEKS'


print(string.isupper())

string = 'GeeksforGeeks'
print(string.isupper())

Output:

True
False
isnumeric()
Definition and Usage
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.

Exponents, like ² and ¾ are also considered to be numeric values.

"-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be
numeric, and the - and the . are not.

Syntax
string.isnumeric()

str = "javatpoint12345"
str = "12345"
# Calling function
str2 = str.isnumeric()
str2 = str.isnumeric()
# Displaying result
print(str2)
print(str2)

Output: True Output: False


String isspace() Method

Definition and Usage


The isspace() method returns True if all the characters in a
string are whitespaces, otherwise False.

txt = " "

x = txt.isspace()

print(x)

Output: True
Python String split()
The split() method breaks up a string at the specified
separator and returns a list of strings.
Syntax of String split() text = 'Python is a fun programming language'
The syntax of split() is:
# split the text from space
str.split(separator, maxsplit) print(text.split(' '))

# Output: ['Python', 'is', 'a', 'fun', 'programming', 'language']

split() Parameters
The split() method takes a maximum of 2 parameters:

separator (optional)- Delimiter at which splits occur. If not


provided, the string is splitted at whitespaces.
maxsplit (optional) - Maximum number of splits. If not
provided, there is no limit on the number of splits.
text= "Love:thy:neighbor:hh" text= "Love:thy:neighbor:hh"

# splits at space # splits at space


print(text.split(":",1)) print(text.split(":",0))

['Love', 'thy:neighbor:hh'] ['Love:thy:neighbor:hh']

word = 'CatBatSatFatOr'

# Splitting at t
print(word.split('t'))

['Ca', 'Ba', 'Sa', 'Fa', 'Or']


replace() method
Definition and Usage
The replace() method replaces a specified phrase with another
specified phrase.
Syntax
string.replace(oldvalue, newvalue, count)
Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to
replace. Default is all occurrences

txt = "one one was a race horse, two two


txt = "I like bananas"
was one too."
x = txt.replace("bananas", "apples")
x = txt.replace("one", "three", 2)
print(x)
print(x)
Python User Input | Python Input () Function | Keyboard Input

To take user input in Python, we use input() function in Python Programming


Language, it asks for an input from the user and returns a string value, no matter what
value you have entered, all values will be considered as strings values.

Taking Input Using input ( ) Function

For example,
name = input("Give me your name: ")
print("Your name is " + name)

Give me your name: Mini


Your name is Mini
Example 2 of Python User Input
val1 = input("Enter any value: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))

val2 = input("Enter another value: ")


print("value of val2: ", val2)
print("type of val2: ", type(val2))

val3 = input("Enter another value: ")


print("value of val3: ", val3)
print("type of val3: ", type(val3))
Output

Enter any value: 10


value of val1: 10
type of val1: <class 'str'>
Enter another value: 10.23
value of val2: 10.23
type of val2: <class 'str'>
Enter another value: Hello
value of val3: Hello
type of val3: <class 'str'>
Accept an Integer as User Input
we use input() function to read input and convert
it into a integer using float() function.

Example 1 of Integer Python User Input Example 2 of Integer Python User Input
a = int(input()) a = input('Please Enter the first number = ')
b = int(input()) b = input('Enter the second number = ')
s=a+b c = int(a) + int(b)
print(s) print("Summation of a + b = %s + %s = %s" % ( a, b, c ))
Output Output:

56 Please Enter the first number = 45


12 Enter the second number = 12
68 Summation of a + b = 45 + 12 = 57
Get Float Input from the user
we use input() function to read input and convert
it into a float using float() function.
Example Taking Python User Input as Float
val1 = input("Enter any number: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))

val2 = float(input("Enter any number: "))


print("value of val2: ", val2)
print("type of val2: ", type(val2))
Output

Enter any number: 123.456


value of val1: 123.456
type of val1: <class 'str'>
Enter any number: 789.123
value of val2: 789.123
type of val2: <class 'float'>
Get multiple values from the user
In Python user can take multiple values or inputs in several way these are:

Using split() method :


• This function helps in getting multiple inputs from the
user.
• It breaks the given input by the specified separator.
• If the separator is not provided then any white space is a
separator. Generally, user use a split() method to split a
Python string but one can use it in taking multiple inputs.

Syntax :

input().split(separator, maxsplit)
Example
a, b = input("Enter two of your lucky number: ").split()
print("First lucky number is: ", a)
print("Second lucky number is: ", b)

Output
Enter two of your lucky number: 7,9
First lucky number is: 7
Second lucky number is: 9
input ()
You can take multiple inputs in one single line by using the raw_input function several times as
shown below.

#multiple inputs in Python using input


x, y = input("Enter First Name: "), input("Enter Last Name: ")
print("First Name is: ", x)
print("Second Name is: ", y)
Output:
Enter First Name: FACE
Enter Last Name: Prep
First Name is: FACE
Second Name is: Prep
map()
map() is another function that will help us take multiple inputs from the user. In general,
the syntax for map function is a map (fun, iter). Here fun is the function to which the
map function passes each iterable.
The syntax for multiple inputs using map()
An example to take integer input from the user.
variable 1, variable 2, variable 3 = map(int, input().split())
#multiple inputs in Python using map
x, y = map(int, input("Enter two values: ").split())
print("First Number is: ", x)
print("Second Number is: ", y)
Output:
Enter two values: 7 1
First Number is: 7
Second Number is: 1
An example to take string input from the user.

#multiple inputs in Python using map


x, y = map(str, input("Enter your first and last name ").split())
print("First Name is: ", x)
print("Second Name is: ", y)
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.)
to another data type is called type conversion. Python has two types of type
conversion.
1.Implicit Type Conversion
2.Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to
another data type. This process doesn't need any user involvement.

Example: output will be:


num_int = 123
num_flo = 1.23 datatype of num_int: <class 'int'>
num_new = num_int + num_flo datatype of num_flo: <class 'float'>
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo)) Value of num_new: 124.23
datatype of num_new: <class 'float'>
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object to required data type. We use the
predefined functions like int(), float(), str(), etc to perform explicit type conversion.
• This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
Example:
Output:
num_int = 123 Data type of num_int: <class 'int'>
num_str = "456" Data type of num_str before Type Casting: <class 'str'>
print("Data type of num_int:",type(num_int)) Data type of num_str after Type Casting: <class 'int'>
print("Data type of num_str before Type Sum of num_int and num_str: 579
Casting:",type(num_str)) Data type of the sum: <class 'int'>
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
Python if Statement Syntax Python if...else Statement
if test expression: Syntax of if...else
statement(s) if test expression:
Body of if
else:
Body of else
Example:
num = 3
Example:
if num > 0:
num = 3
print(num, "is a positive number.")
if num >= 0:
print("This is always printed.")
print("Positive or Zero")
num = -1
else:
if num > 0:
print("Negative number")
print(num, "is a positive number.")
print("This is also always printed.")

Output:
3 is a positive number Output:
This is always printed Positive or Zero
This is also always printed.
Python if...elif...else Statement
num = 3.4
Syntax of if...elif...else
# Try these two variations as well:
if test expression:
# num = 0
Body of if
# num = -4.5
elif test expression:
Body of elif
if num > 0:
else:
print("Positive number")
Body of else
elif num == 0:
print("Zero")
else:
print("Negative number")
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block
of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block.

if True: and
print('Hello')
a=5 if True: print('Hello'); a = 5

Both are valid


What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true

Syntax of while Loop in Python While loop with else


while test_expression: The else part is executed if the condition in the while loop
Body of while evaluates to False.
Example: Example:
n = 10 counter = 0
# initialize sum and counter while counter < 3:
sum = 0 print("Inside loop")
i=1 counter = counter + 1
while i <= n: else:
sum = sum + i print("Inside else")
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Output
Output:
The sum is 55 Inside loop
Inside loop
Inside loop
Inside else
What is for loop in Python?
The for loop in Python is used to iterate over a
sequence (list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]


Syntax of for Loop sum = 0
for val in numbers:
for val in sequence: sum = sum+val
loop body print("The sum is", sum)
• Here, val is the variable that takes the value of the item
inside the sequence on each iteration.
Output:
• Loop continues until we reach the last item in the sequence. The sum is 48
The body of for loop is separated from the rest of the code
using indentation.
range()
Definition and Usage
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.

Syntax
range(start, stop, step)

Example
Create a sequence of numbers from 3 to 5, and
print each item in the sequence:
x = range(3, 6) Example
for n in x: Create a sequence of numbers from 3 to 19, but
print(n) increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for
loop exhausts.

digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

Output:
0
1
5
No items left.
Python break and continue

What is the use of break and continue in Python?


• In Python, break and continue statements can alter the flow
of a normal loop.

• Loops iterate over a block of code until the test expression is


false, but sometimes we wish to terminate the current
iteration or even the whole loop without checking test
expression.
Python break statement
a="pineapple" • The break statement terminates the loop containing it.
for val in a: Control of the program flows to the statement immediately
if val == "i": after the body of the loop.
break
print(val) • If the break statement is inside a nested loop (loop inside
print("The end") another loop), the break statement will terminate the
innermost loop.
Output:
p Syntax of break
The end break
Python continue statement
The continue statement is used to skip the rest of the code
inside a loop for the current iteration only.
Loop does not terminate but continues on with the next
iteration.
Syntax of Continue
continue

a="pineapple"
for val in a:
if val == "i":
continue
print(val)

print("The end")
What is a function in Python?
In Python, a function is a group of related statements that performs a specific task.

There are mainly two types of functions.


•User-define functions - The user-defined functions are those define by the user to perform
the specific task.
•Built-in functions - The built-in functions are those functions that are pre-defined in
Python.

Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is given below.
Syntax:
def my_function(parameters):
function_block
return expression

Let's understand the syntax of functions definition.


•The def keyword, along with the function name is used to define the function.
•The identifier rule must follow the function name.
•A function accepts the parameter (argument), and they can be optional.
•The function block is started with the colon (:), and block statements must be at the same
indentation.
•The return statement is used to return the value. A function can have only one return
How to call a function in python?

To call a function we simply type the function name with appropriate


parameters.
Example of a function with return
Example of a function and call
# Defining function
def hello_world(): def sum():
print("hello world") a = 10
# function calling b = 20
hello_world() c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
def sum (a,b):
def func (name): return a+b;
print("Hi ",name)
#calling the function #taking values from the user
func("Devansh") a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b


print("Sum = ",sum(a,b))
Python – Call function from another file

1
2

def displayText(): from test import *


print( "Geeks 4 Geeks !") # calling functions
displayText()
• Change notebook name by clicking untitled
• Rename suppose test • Change notebook name by clicking untitled
• Download filename.py (test.py)in specified • Rename suppose xyz.py
folder • Download filename.py (test.py)in specified
folder
What is recursion?
Recursion is the process of defining something in
terms of itself.
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))
List
Python List
• A list in Python is used to store the sequence of various types
of data.
• Python lists are mutable type its mean we can modify its
element after it created.

Create Python Lists


• In Python, a list is created by placing elements inside square
brackets [], separated by commas.

# list of integers
my_list = [1, 2, 3]

# empty list
my_list = []

# list with mixed data types


my_list = [1, "Hello", 3.4]

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Access List Elements
There are various ways in which we can access the elements of a list.

List Index
• We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list
having 5 elements will have an index from 0 to 4.

• Trying to access indexes other than these will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result in TypeError.
my_list = ['p', 'r', 'o', 'b', 'e']

# first item Output:


print(my_list[0]) # p

# third item p
print(my_list[2]) # o o
e
# fifth item a
print(my_list[4]) # e 5
Traceback (most recent call last):
# Nested List File "<string>", line 21, in <module>
n_list = ["Happy", [2, 0, 1, 5]] TypeError: list indices must be integers or slices, not float

# Nested indexing
print(n_list[0][1])

print(n_list[1][3])

# Error! Only integer can be used for indexing


print(my_list[4.0])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.

# Negative indexing in lists


my_list = ['p','r','o','b','e'] Output

# last item e
print(my_list[-1]) p

# fifth last item


print(my_list[-5])
List Slicing in Python
We can access a range of items in a list by using the slicing operator :.

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements from index 2 to index 4 Output


print(my_list[2:5])
['o', 'g', 'r']
# elements from index 5 to end ['a', 'm', 'i', 'z']
print(my_list[5:]) ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

# elements beginning to end


print(my_list[:])

Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example, my_list[2: 5] returns a list with elements at
index 2, 3 and 4, but not 5.
Add/Change List Elements
• Lists are mutable, meaning their elements can be changed unlike string
• Weor can
tuple.
use the assignment operator = to change an item or a
range of items.

# Correcting mistake values in a list


odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1 Output

print(odd) [1, 4, 6, 8]
[1, 3, 5, 7]
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]

print(odd)
1. append()
We can append values to the end of the list. We use the append() method for
this. You can use this to append single values to the list – value, list, tuple.
nums=[1,2,3]
nums.append(4)
nums.append([5,6])
nums.append((7,8))
print (nums)
Output:
[1, 2, 3, 4, [5, 6], (7, 8)]

2. insert()
You can insert values in a list with the insert() method. Here, you specify a
value to insert at a specific position.
nums=[1,2,3]
nums.insert(2,4)
print (nums)
Output:
[1, 2, 4, 3]
3. extend()
extend() can add multiple items to a list.
Learn by example:
nums=[1,2,3]
nums.extend([[4,5,6],(7,8),9])
Print(nums)
Output:
[1, 2, 3, [4, 5, 6], (7, 8), 9]
Deleting Elements in Python Lists

Lists have methods for deleting elements. They are remove() and pop() and are
slightly different from each other.

odd = [1, 9 ,4 , 8] odd = [1, 9 ,4 , 8]


odd.pop() odd.pop(0) Pop element
print(odd) Remove in specified
print(odd)
element of list position if not
which provide provide index
Output: in remove then delete
Output:
[9,4,8] method(only last element of
[1,9,4]
first list
occurrence)

odd = [1, 9 ,4 , 8,1]

odd.remove(1)

print(odd)

Output:
[9,4,8,1]
Looping on Lists in Python
Since lists are collections of elements, we can use them in for-loops. You can do
this if you want to do something for every value in a list.
Code:
for num in [1,2,3,4,5,6]: nums=[10,45,89,4]
print(num) for index in range(len(nums)):
print(nums[index])
Output:
1 Output: Nums[0]
2 [10,45,89,4] Nums[1]
3 Nums[2]
4 Nums[3]
5
6

Python Lists Length


Like for strings, we can calculate the length of a list. For this, we use
the in-built len() function.
nums=[1,2,3,4,5]
len(nums)
Python List Methods
Python has many useful list methods that makes it really easy to work with
lists. Here are some of the commonly used list methods.

Methods Descriptions

append() adds an element to the end of the list

extend() adds all elements of a list to another list

insert() inserts an item at the defined index

remove() removes an item from the list


returns and removes an element at the given
pop()
index
clear() removes all items from the list

index() returns the index of the first matched item

returns the count of the number of items passed


count()
as an argument

sort() sort items in a list in ascending order

reverse() reverse the order of items in the list

copy() returns a shallow copy of the list


Difference between lists and strings in python
• We can also use + operator to combine two lists. This is also called concatenation.

• The * operator repeats a list for the given number of times.

# Concatenating and repeating lists


odd = [1, 3, 5] Output

print(odd + [9, 7, 5]) [1, 3, 5, 9, 7, 5]


['re', 're', 're']

odd=[10,50]

[[10,50],[10,50]
print( [odd] * 2)

You might also like