0% found this document useful (0 votes)
4 views64 pages

1-Introduction To Python

The document provides an introduction to Python, detailing its history, features, and applications. It covers fundamental concepts such as data types, variables, operators, control statements, and loops, along with examples. Additionally, it explains Python's syntax for comments, keywords, and identifiers.

Uploaded by

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

1-Introduction To Python

The document provides an introduction to Python, detailing its history, features, and applications. It covers fundamental concepts such as data types, variables, operators, control statements, and loops, along with examples. Additionally, it explains Python's syntax for comments, keywords, and identifiers.

Uploaded by

ShaaN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Python

Why the name is Python ?


• The Python programming language was created by the Dutch
programmer Guido van Rossum in the late 1980s.
• Python programming language comes from an old BBC television comedy
sketch series called Monty Python’s Flying Circus.
• Python was first publicly released in February 1991 with version 0.9.0. It is
currently maintained by the non-profit Python Software Foundation (PSF).

Guido van Rossum


What is Python?
• Python is a high-level, interpreted programming language
• Simple syntax, easy to learn and use
• Widely used in education, industry, and research
Features of Python
• Simple and easy to learn
• Interpreted language
• Object-Oriented
• Platform independent
• Large standard library
• Free and open source
Python Applications (Diagram)
Web Development AI & ML
• Django • TensorFlow
• Flask • PyTorch

Data Science Automation


• NumPy • Scripting
• Pandas • Testing
Data Types in Python
• Numeric: int, float, complex
• Text: str
• Boolean: bool
• Sequence: list, tuple, range
• Set and Dictionary
Numeric Types
These represent various forms of numbers.

int : Represents whole numbers (positive or negative) without a decimal point and has
unlimited length in Python 3.

float : Represents real numbers with a decimal point.

complex : Represents numbers with a real and an imaginary part, denoted by the suffix j
(e.g., 3 + 4j).

Text Type
str : An immutable sequence of characters used to represent text, enclosed in single,
double, or triple quotation marks.
Sequence Types: Ordered collections like list, tuple, and range.
Mapping Type: The dict (Dictionary), an unordered collection of key-value pairs.
Set Types: Unordered collections of unique values such as set and frozenset.
Boolean Type: bool, representing True or False.
Binary Types: Handle raw binary data, including bytes, bytearray, and memoryview.
None Type: Represents a null value with a single value None.
Data type Description Example
int To store integer values n = 20
float To store decimal values n = 20.75
To store complex numbers (real and
complex n = 10+20j
imaginary part)
str To store textual/string data name = 'Jessa'
bool To store boolean values flag = True
list To store a sequence of mutable data l = [3, 'a', 2.5]
tuple To store sequence immutable data t =(2, 'b', 6.4)
dict To store key: value pair d = {1:'J', 2:'E'}
To store unorder and unindexed
set s = {1, 3, 5}
values
frozenset To store immutable version of the set f_set=frozenset({5,7})
range To generate a sequence of number numbers = range(10)
bytes To store bytes values b=bytes([5,10,15,11])
Python Comments
• the hash (#) symbol to start writing a comment.

#This is a long comment


#and it extends
#Multiple lines

• Multiline Comments
- Python does not really have a syntax for
multiline comments.
"""
Or, you can use a multiline string.
This is a comment
Since Python will ignore string literals that
written in
are not assigned to a variable, you can add a
more than just one line
multiline string (triple quotes) in your code,
"""
and place your comment inside it.
Python Keywords
• Keywords are the reserved words in python
• We can't use a keyword as variable name, function name or any other
identifier
• Keywords are case sensitive
#Get all keywords in python
import keyword
print([Link])
print("Total number of keywords ", len([Link]))

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',


'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield’]
Total number of keywords 35
Identifiers
• Identifier is the name given to entities like class, functions, variables
etc. in Python.
• It helps differentiating one entity from another.
Rules for Writing Identifiers:
• Allowed Characters: Identifiers can only contain letters (a-z, A-Z), digits (0-9), and
underscores (_).
• Cannot Start with a Digit: An identifier must begin with a letter or an underscore,
never a digit (e.g., user1 is valid, 1user is invalid).
• Case-Sensitive: Python treats identifiers as case-sensitive. For example, Name, name,
and NAME are considered three different identifiers.
• Reserved Keywords are Forbidden: You cannot use any of Python's reserved keywords
(like if, for, class, def, return, True, False, etc.) as identifiers. The full list of keywords can
be found using the [Link] function in Python.
• No Special Characters or Spaces: Special symbols such as !, @, #, $, %, or embedded
spaces are not allowed. The underscore (_) is the only exception.
• Length: There is no hard limit on the length of an identifier, though it is best practice to
keep names concise and descriptive for readability.
Variables
• Variables are used to store data values
• No need to declare variable type
• Value assignment uses '=' operator
• Example: x = 10
Variable Assignments
Examples:
#We use the assignment operator (=) to assign values to a variable
a = 10
b = 5.5
c = “Python“
#Multiple Assignments
a, b, c = 10, 5.5, “Python“
a = b = c = “Cisco"
Python Statement
• Examples:
a = 1 #single statement
Multi-Line Statement
# Multiple variable assignment with parentheses
(var_one, var_two, var_three,
var_four, var_five, var_six) = (
1, 2, 3,
4, 5, 6
)
Python Statement (cont…)
• Using the Backslash \ Character
# Multiple variable assignment with backslashes
var_one, var_two, var_three, \
var_four, var_five, var_six = 1, 2, 3, \
4, 5, 6
# put multiple statements in a single line using ;
Literals
• Literal is a fixed value assigned to a variable
• Numeric literals: 10, 3.14
• String literals: 'Python', "Hello"
• Boolean literals: True, False
The import statement
• Python is made up of several modules.
• Before you can use a module, you must “import” it.

import math
print ([Link])
print ([Link](10))
--------------------------------------------------------------------------
#The import statement with as name
import math as m
print ([Link])
print ([Link](10))
Input and Output Statements
• input() is used to take input from user
• print() is used to display output
print(10) Converting Input to Numbers
print(5 + 3) # Use int() or float() to convert input
# Required for mathematical operations
#Use commas to print multiple items
#Python adds spaces automatically age = int(input("Enter your age: "))
print("You will be", age + 1, "next year")
name = "Alex"
age = 15 a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Name:", name, "Age:", age) print("Sum:", a + b)
name = input("Enter your name: ") print("Difference:", a - b)
print("Hello", name) print("Product:", a * b)
Using print() Formatting

• Format output using f-strings


• Makes output cleaner and readable

name = input("Enter your name: ")


marks = int(input("Enter marks: "))
print(f"Student {name} scored {marks} marks")
Operators
Arithmetic Operators

Operator Description Example


+ Addition 5+3 #8
– Subtraction 5–3 #2
* Multiplication 5 * 3 # 15
/ Division 5 / 2 # 2.5
// Floor Division 5 // 2 # 2
% Modulus (Remainder) 5%2 #1
** Exponentiation 5 ** 2 # 25
Assignment Operators
Operat Description Example
or
= Assign value x=5
+= Add and assign x += 3 # x = x + 3
-= Subtract and assign x -= 2 # x = x – 2
*= Multiply and assign x *= 4 # x = x * 4
/= Divide and assign x /= 2 # x = x / 2
//= Floor divide and assign x //= 2 # x = x // 2
%= Modulus and assign x %= 3 # x = x % 3
**= Exponentiate and assign x **= 2 # x = x ** 2
Comparison (Relational) Operators
Operator Description Example

== Equal to 5 == 3 # False

!= Not equal to 5 != 3 # True

> Greater than 5>3 # True

< Less than 5<3 # False

>= Greater than or equal to 5 >= 5 # True

<= Less than or equal to 5 <= 3 # False


Logical Operators
Operator Description Example
and Returns True only if both statements (5 > 3) and (3 > 1)
are True; otherwise, it returns False. # True
or Returns True if at least one of the (5 > 3) or (3 < 1)
conditions is True. # True
not Negates a Boolean value, not(5 > 3)
turning True into False and vice versa. # False
(Reverses the result)
Bitwise Operators
Operator Description Example
& AND 5&3 #1

| OR 5 | 3 # 7

^ XOR 5^3 #6

~ NOT ~5 # -6

<< Left Shift 5 << 1 # 10


>> Right Shift 5 >> 1 # 2
Identity Operators
Operator Description Example
is Returns True if two variables x is y
point to the same object in
memory.
is not Returns True if they refer to x is not y
different objects.
Membership Operators
Operator Description Example
in Returns True if the specified ‘a’ in ‘apple’
value is present in the sequence # True
not in Returns True if value is not in ‘b’ not in ‘apple’
sequence # True
Precedence and Associativity
• Precedence decides order of operation
• Associativity decides direction of evaluation
• Example: *, / have higher precedence than +, -
• Use parentheses () to control precedence
Expressions
• Combination of variables, operators, and values
• Evaluated to produce a result
• Example: x + y * 10
• Can be arithmetic or logical
Control Statements
• Used to control the flow of program execution
• Decision making: if, if-else, elif
• Looping: for, while
• Jumping: break, continue, pass
Indentation in Python
Python uses indentation to define a block of code, such as the body of an
if statement.

For example,
x=1
total = 0

# start of the if statement


if x != 0:
total += x
print(total)
# end of the if statement

print("This is always executed.")


if Statement

Syntax
if condition1:
# code block 1

[ elif condition2:
# code block 2

else:
# code block 3 ]
for Loop
to iterate over sequences such as lists, strings, dictionaries, etc.
Syntax
for iterating_var in sequence:
statements
For example,
languages = ['Swift', 'Python', 'Go'] language = 'Python'

# start of the loop # iterate over each character in language


for lang in languages: for x in language:
print(lang) print(x)
print('-----')
# end of the for loop # iterate from i = 0 to i = 3
for i in range(0, 4):
print(i)
print('Last statement')
break and continue Statement
The break and continue statements are used to alter the flow of loops.

languages = ['Swift', 'Python', 'Go', 'C++']

for lang in languages:


if lang == 'Go':
break
print(lang)

languages = ['Swift', 'Python', 'Go', 'C++']

for lang in languages:


if lang == 'Go':
continue
print(lang)
Nested for loops
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print(i * j, end=" ")
print() # moves to the next line

for i in range(1, 5):


for j in range(i):
print("*", end="")
print()
Using for loop without accessing sequence items
If we don't intend to use items of sequence inside the body of a loop, it is clearer to use
the _ (underscore) as the loop variable.

For example,

# iterate from i = 0 to 3
for _ in range(0, 4):
print('Hi')

Output ?

Hi
Hi
Hi
Hi
while Loop
Syntax
while condition:
# body of while loop

For example,

# Print numbers until the user enters 0 while True:


number = int(input('Enter a number: ')) user_input = input('Enter your name: ')

# iterate until the user enters 0 # terminate the loop when user enters end
while number != 0: if user_input == 'end':
print(f'You entered {number}.') print(f'The loop is ended')
number = int(input('Enter a number: ')) break

print('The end.') print(f'Hi {user_input}')


In Python, a while loop can have an optional else clause - that is executed
once the loop condition is False.

counter = 0

while counter < 2:


print('This is inside loop')
counter = counter + 1
else:
print('This is inside else block')
pass Statement
the pass statement is a null statement which can be used as a placeholder for future code.

n = 10

# use pass inside if statement


if n > 10:
pass

print('Hello')
Conditional statement – if

# Read two numbers from the user


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

# Find the largest using conditional operator


largest = a if a > b else b

# Display the result


print("The largest number is:", largest)
For loop examples
Q . Sum of first n natural numbers Q. Print even numbers from 1 to 20
n = int(input("Enter a number: ")) for i in range(2, 21, 2):
sum = 0 print(i)

for i in range(1, n + 1):


sum += i

print("Sum =", sum)

Q. Print multiplication table of a number


n = int(input("Enter a number: "))

for i in range(1, 11):


print(n, "x", i, "=", n * i)
Q. Factorial of a number
n = int(input("Enter a number: "))
fact = 1

for i in range(1, n + 1):


fact *= i

print("Factorial =", fact)

Q. Print characters of a string

name = input("Enter a string: ")

for ch in name:
print(ch)
Q. Count digits in a number
number = int(input("enter a Number"))
num_char= str(number)
count = 0
sum = 0
for n in num_char:
count = count + 1
sum = sum + int(n)
print(count,sum)

Q. Check prime number


n = int(input("Enter a number: "))
flag = True
for i in range(2, n):
if n % i == 0:
flag = False
break
if flag and n > 1:
print("Prime number")
else:
print("Not a prime number")
Pyramid pattern

n=5
for i in range(n):
print(" " * (n - i - 1) + "*" * (2*i + 1))

Inverted pyramid
n = 5
for i in range(n, 0, -1):
print(" " * (n - i) + "*" * (2*i - 1))
Number triangle
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end="")
print()

Floyd’s Triangle
num = 1
for i in range(1, 5):
for j in range(i):
print(num, end=" ")
num += 1
print()
Diamond pattern
while loop examples
i=1 n = int(input("Enter a number: "))
while i <= 10: i=1
print(i) total = 0
i += 1
while i <= n:
Print numbers from 1 to 10
total += i
i += 1

print("Sum =", total)


Sum of first n natural numbers
n = int(input("Enter a number: "))
Reverse a number
fact = 1
num = int(input("Enter a number: "))
while n > 0:
rev = 0
fact *= n
n -= 1
while num > 0:
digit = num % 10
print("Factorial =", fact)
rev = rev * 10 + digit
num //= 10
Factorial of a number
print("Reversed number =", rev)
Check palindrome number Count digits in a number
num = int(input("Enter a number: "))
temp = num num = int(input("Enter a number: "))
rev = 0 count = 0

while num > 0: while num > 0:


rev = rev * 10 + num % 10 count += 1
num //= 10 num //= 10

if temp == rev: print("Number of digits =", count)


print("Palindrome number")
else:
print("Not a palindrome")
Q. Check Whether a Number is a Strong Number
A number is called a Strong Number if the sum of the factorial of its digits is equal to
the number itself.
Example:145 → 1! + 4! + 5! = 1 + 24 + 120 = 145 ✅
123 → 1! + 2! + 3! = 9 ❌

Q: Menu-Driven Program
Write a Python program using a while loop to perform the following
operations until the user chooses Exit:
[Link] Factorial of a number
[Link] Prime number
[Link] Palindrome number
[Link]
Q: Write a Python program to check whether a given number is a Perfect Number
using a while loop.
Definition: A perfect number is a positive integer that equals the sum of its own
positive divisors, excluding the number itself (its proper divisors). For example, 6 is
a perfect number because its proper divisors (1, 2, 3) add up to 6 (1 + 2 + 3 = 6)

Q : Print Digits of a Number in Words (While Loop)


Complex Number
Syntax of complex() function
1. Without any arguments: complex() returns 0j.
2. With one argument: complex(x) returns x + 0j.
3. With two arguments: complex(x, y) returns x + yj.
4. With a string argument: complex(string) interprets the string as a complex
number.
# Creating complex numbers
c = complex(3, 4) c1 = complex(3, 4)
print("Complex number:", c) c2 = complex(5)
print("Real part:", [Link]) c3 = complex()
print("Imaginary part:", [Link])
print(c1)
real = float(input("Enter real part: ")) print(c2)
imag = float(input("Enter imaginary part: ")) print(c3)

c = complex(real, imag)
print([Link])
print("Complex number:", c) print([Link])
complex() with String inputs Arithmetic of Complex Numbers
#complex() with String inputs #Arithmetic of Complex Numbers
c1 = complex("5.5") c1 = complex(4, 3)
c2 = complex(2, -5)
print(c1)
print(c1+c2) # adds c1 and c2
c2 = complex("-2") print(c1-c2) # subtracts c1 and c2
print(c2) print(c1*c2) # multiplies c1 and c2
print(c1/c2) # divides c1 and c2
c3 = complex("3+4j")
print(c3) (6-2j)
(2+8j)
(23-14j)
(-0.24137931034482757+0.896551724137931j)
(5.5+0j)
(-2+0j)
(3+4j)
Python String
Strings can be created using either single ('...') or double ("...") quotes. Both behave the same.
Use triple quotes ('''...''' ) or ( """...""") for strings that span multiple lines. Newlines are preserved.

s = """I am Learning
Python at Silicon"""
print(s)

s = '''I'm a
Student'''
print(s)

I am Learning
Python at Silicon
I'm a
Student
Accessing characters in String

Strings are indexed sequences. Positive indices start at 0 from the left; negative indices start
at -1 from the right
s = "Silicon"
print(s[0]) # first character S
print(s[4]) # 5th character c
l
print(s[-5]) # 5th character from end
String Slicing
# String Slicing
s = "Silicon"
print(s[1:4]) # characters from index 1 to 3 ili
Sil
print(s[:3]) # from start to index 2 icon
print(s[3:]) # from index 3 to end nociliS
print(s[::-1]) # reverse string
String Iteration
s = "Python"
for char in s:
print(char)

String Immutability
Strings are immutable, which means that they cannot be changed after they are created.
If we need to manipulate strings then we can use methods like concatenation, slicing or
formatting to create new strings based on original.

s = "silicon University"
s = "S" + s[1:] # create new string
print(s)

Silicon University
Deleting a String
In Python, it is not possible to delete individual characters from a string since
strings are immutable.
However, we can delete an entire string variable using the del keyword.

s = "GfG" After deleting the string if we try to access s then it will


del s result in a NameError because variable no longer
print(s) exists.

Concatenating and Repeating Strings

• concatenate strings using + operator


• repeat them using * operator.
Common String Methods
1. len(): The len() function returns the total number of characters in a string
(including spaces and punctuation).
2. upper() and lower(): upper() method converts all characters to uppercase
whereas, lower() method converts all characters to lowercase.
3. strip() and replace(): strip() removes leading and trailing whitespace from the
string and replace() replaces all occurrences of a specified substring with
another.

s = " Gfg "


print([Link]())

s = "Python is fun"
print([Link]("fun", "awesome"))
Gfg
Python is awesome
Formatting Strings
1. Using f-strings

name = "Gopal"
age = 22
print(f"Name: {name}, Age: {age}")

2. Using format()

s = "My name is {} and I am {} years old.".format("Gopal", 22)


print(s)
String Membership Testing

in keyword checks if a particular substring is present in a string.

s = "Silicon"
print("con" in s)
print("cin" in s)
Question:
Write a Python program to count the
Q. Check Whether a String is Palindrome
number of vowels and consonants in
a string.
Q. Write a Python program to count the
s = input("Enter a string: ")
vowels = 0 number of words in a string. (use
consonants = 0 split() function)
Q. Write a Python program to remove all
for ch in s: spaces from a string.
if [Link]():
if ch in "aeiouAEIOU":
vowels += 1
else:
consonants += 1

print("Vowels:", vowels)
print("Consonants:", consonants)
isinstance() Function
The isinstance() function returns True if the specified object is of the specified
type, otherwise False.

Syntax
isinstance(object, type)

x = isinstance(5, int)
print(isinstance("Hello", (float, int, str, list, dict, tuple)))
type() Function
The type() function in Python tells what kind of data an object is or creates a new
class dynamically.
Output
a=5
b = "Hi" <class 'int'>
c = [1, 2] <class 'str'>
<class 'list'>
print(type(a))
print(type(b))
print(type(c))

You might also like