0% found this document useful (0 votes)
13 views39 pages

Python Notes Unit 1

Uploaded by

ayushrawat8665
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
13 views39 pages

Python Notes Unit 1

Uploaded by

ayushrawat8665
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 39

Python Programming

Definition

 Python is an interpreted, object-oriented, high-level programming


language that is widely used in various fields including data science,
web development and artificial intelligence(AI).
Python Vs C++
Python C++

It includes a few lines of codes It includes long lines of code.


Python is easy to read and understand. C++ includes predefined syntaxes, and structure and
that makes it difficult to understand.
Python language runs through an interpreter. C++ is a compiled language.
Automatic memory management with garbage Manual memory management
collection
Dynamically typed; variable types are determined at Statically typed; variable types are declared and
runtime checked at compile time
Easier to debug due to its interpreted nature and Debugging can be more challenging due to compilation
dynamic typing and static typing.
Popular for web development, data science, AI, Commonly used in game development,
automation, and scripting. system/software development, and real-time
applications.
large standard library that covers a wide range of comprehensive standard library, but it is more focused
functionality. on system-level and performance-critical
functionalities.
Features Of Python
• Free and Open Source
• Portable language
• Interpreted Language
• GUI Programming Support
• High-Level Language
Application of Python

• Web Development
• Machine Learning and Artificial Intelligence
• Data Science
• Game Development
• Audio and Visual Application
• Software Development
Interpreter mode
• Interpreter mode refers to running Python scripts through a file. You write
the entire code in a Python file (usually with a .py extension) and then run it
using the Python interpreter.
• When you execute the above command, Python reads the script file from
top to bottom and runs it as a whole.
• Example:
python script.py
Interactive mode
• Interactive mode allows you to run Python commands individually in a
shell or a Python prompt. The Python shell is invoked by typing python
or python3 in your terminal or command line without specifying a
script.
• When you enter interactive mode, you can type Python expressions,
and the interpreter immediately executes them and gives feedback.
• Example –
$ python
>>> print("Hello, World!")
Hello, World!
DataTypes

Numeric Sequence Mapping Set Boolean

Int, String,
Float, List, Dictionary Set Bool
Complex Tuples
Numeric
Code:
a=7
print("Type of a: ", type(a))
b = 7.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Sequence (String)

Code:
String1 = 'Welcome to the Geeks
World’
print("String with the use of Single
Quotes: ")
print(String1)print(type(String1))
Sequence(List)
Code:
List = []
print("Initial blank List: ")
print(List)
List = ['GeeksForGeeks’]
print("\nList with the use of String: ")
print(List)List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values:
")
print(List[0])
print(List[2])
List = [['Geeks', 'For'], ['Geeks’]]
print("\nMulti-Dimensional List: ")
print(List)
Sequence (Tuples)

Code:
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)Tuple1 = ('Geeks', 'For’)
print("\nTuple with the use of String:
")
print(Tuple1)
list1 = [1, 2, 4, 7, 6]
print("\nTuple using List: ")
print(tuple(list1))
Boolean
Code:
a = True
Print(type(a))

b = False
Print(type(b))
Set
Code:
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)set1 = set([1, 2, 'Geeks', 4,
'For', 6, 'Geeks’])
print("\nSet with the use of Mixed
Values")
print(set1)
Dictionary
Code:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 6: 'Geeks’}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 6, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Geeks', 2: 'For', 6: 'Geeks’})
print("\nDictionary with the use of dict(): ")
Recap….
Types Description Example

Numeric Represents numerical values ‘int’, ‘float’, ‘complex’

Sequence Represents a collection of ordered and indexed value ‘str’, ‘list’, ‘tuple’
and sequence of Characters

Set Represents a collection of unique elements ‘set’

Boolean Represents a binary truth value ‘bool’

Mapping Represents a collection of key-value pairs ‘dict’


Operators

Arithmetic Bitwise

Assignment Membership

Comparison Identity

Logical
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Code:
x=7
y=3
print(x+y)
print(x-y)
print(x * y)
print(x/y)
print(x % y)
print(x**y)
print(x//y)
Precedence & Associativity

Operators Associativity

() Left to Right

** Right to Left

+x and -x Left to Right

*,/,// and % Left to Right

+ and - Left to Right


Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As

= x=7 x=7

+= x += 6 x=x+6

-= x -= 6 x=x-6

*= x *= 6 x=x*6

/= x /= 6 x=x/6

%= x %= 6 x=x%6

//= x //= 6 x = x // 6

**= x **= 6 x = x ** 6
Code:
a = 50
b = 10
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a/=b:', a/b)
Comparison operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Code:
a = 32
b = 73
print('Two numbers are equal or
not:',a==b)
print('Two numbers are not equal or
not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to
b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements is x < 5 or x < 4


true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Code:
a=7
print('Is this statement
true?:',a > 3 and a < 7)
print('Any one statement is
true?:',a > 3 or a < 7)
print('Each statement is
true then return False and
vice-versa:',(not(a > 3 and a
< 7)))
Bitwise Operators
Bitwise operators are used to compare (binary) numbers:

Operato Name Description Example


r
& AND Sets each bit to 1 if both bits are 1 x&y
| OR Sets each bit to 1 if one of two bits is 1 x|y
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y
~ NOT Inverts all the bits ~x
<< Zero fill left Shift left by pushing zeros in from the right and let x << 2
shift the leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in x >> 2
right shift from the left, and let the rightmost bits fall off
Code…
a=9
b=3
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
Identity Operators:
Identity operators are used to compare the objects, not if they are equal, but if they are
the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the x is y


same object

is not Returns True if both variables are not the x is not y


same object
Code(is):
num1 = 5
num2 = 7
lst1 = [1, 2, 3]
lst2 = [1, 4, 3]
str1 = "hello world“
str2 = "hello world“
print(num1 is num2)
print(lst1 is lst2)
print(str1 is str2)
Code(is not):
num1 = 5
num2 = 7
lst1 = [1, 2, 3]
lst2 = [1, 4, 3]
str1 = "hello world“
str2 = "hello world“
print(num1 is not num2)
print(lst1 is not lst2)
print(str1 is not str2)
Membership Operators
Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value x in y


is present in the object

not in Returns True if a sequence with the specified value x not in y


is not present in the object
Code(in):
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World“
set1 = {1, 2, 3, 4, 5}
print(2 in list1)
print('O' in str1)
print(6 in set1)
Code(not in):
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World“
set1 = {1, 2, 3, 4, 5}
print(2 not in list1)
print('O' not in str1)
print(6 not in set1)
Operator Operator Name
() Parentheses
** Exponent Right to left
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*,/,//,% Multiplication, division, Floor division, modulus
+,- Addition, Subtraction
<<,>> Bitwise Shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==,!=,>,>=,<,<=,is not ,is, in, not in Comparison, identity, membership
not Logical not
and Logical and
or Logical or
=,+=,-=,*=,/= Assignment Operator Right to left
Conditional (if):
Syntax:
if expression:
statement
Greatest number
a = int (input("Enter a: "))
b = int (input("Enter b: "))
c = int (input("Enter c: "))
if a>b and a>c:
print ("From the above three numbers given a is largest")
if b>a and b>c:
print ("From the above three numbers given b is largest")
if c>a and c>b:
print ("From the above three numbers given c is largest")
Alternatives(if-else)
if condition:
#block of statements
else:
#another block of statements
(else-block)

Eligible to vote or not:


age = int (input("Enter your ag
e: "))
if age>=18:
print("You are eligible to vote
!!");
else:
print("Sorry! you have to wait
!!");
Nested if else:
Syntax:
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
Code:
Whether the student fails or pass
marks = int(input("Enter the marks? "))

if marks > 85 and marks <= 100:


print("Congrats ! you scored grade
A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

You might also like