What is Python?
Common Uses of Python:
- Web Development: Python frameworks like Django and Flask are popular for building web applications.
- Data Science and Machine Learning: Python libraries like NumPy, Pandas, TensorFlow, and sci-kit-learn make it a powerful tool for data analysis and machine learning tasks.
- Automation: Python scripts can be used to automate repetitive tasks on your computer.
- Scripting: Python is often used for scripting various tasks, such as system administration, network automation, and testing.
- Scientific Computing: Python is used in scientific computing due to its numerical computing libraries like NumPy and SciPy.
- Python is Simple and easy.
- Python is Free and Open Source.
- Python High-level language.
- Python is portable.
- Python was developed by Guido Van Rossum.
Why to Use Python?
- Programming (for Placements/online contests/DSA)
- Development (using a backend framework called Django)
- Machine Learning / Data Science / Artificial Intelligence
What to Install IDE?
- Python (https://www.python.org/)
- PyScripter (https://rb.gy/bvnn69 )
- PyCharm (https://www.jetbrains.com/pycharm/)
- Visual Studio Code(https://code.visualstudio.com/download)
- jupyter(https://jupyter.org/install)
Python Character Sets-
- Letters – A to Z, a to z Digits – 0 to 9.
- Special Symbols - + - * / etc.
- Whitespaces – Blank Space, tab, carriage return, newline, formfeed.
- Other characters – Python can process all ASCII and Unicode characters as part of data or literals.
- Variables in Python-
- Variables Basic Types in Python- numbers(integers, floating), boolean, strings.
Python Data Types --
- String()
- Integers()
- Float()
- Boolean()
- complex()
- None()
- int(): Represents integers (whole numbers) like 42 or -100.
- float(): Represents floating-point numbers (decimals) like 3.14 or -9.25e+2 (scientific notation).
- complex(): Represents complex numbers with a real and imaginary part (a+bi), where i is the imaginary unit.
- ()str: Represents strings of text enclosed in single or double quotes. Example: "Hello world!" or 'This is a string'
- ()bool: Represents Boolean values, True or False.
Data Types --
- print(type(name)) ----- <class 'str'>
- print(type(age)) ------ <class 'int'>
- print(type(pi)) ----- <class 'float'>
- print(type(A)) ----- <class 'boolean'>
- Print(type(complex_num)) ----- <class 'complex'>
Python Keywords-
Here's a categorization of some important Python keywords:
Keywords-
and |
True |
nonlocal |
class |
with |
for |
else |
assert |
None |
from |
continue |
while |
in |
finaly |
or |
global |
def |
not |
return |
lambda |
pass |
if |
del |
yield |
as |
try |
false |
raise |
import |
elif |
except |
break |
is |
|
|
|
Comments in Python-
1-Single-Line Comments:
- These start with the hash symbol (
#
) and extend to the end of the line. - They are useful for brief explanations or comments next to code lines.
example
#single line comments
2-Multi-Line Comments:
- Python doesn't have a dedicated syntax for multi-line comments like some other languages.
- There are two common approaches to achieving multi-line comments.
example-
""" multi-line comment """
Operators in Python -
An operator is a symbol that performs a certain operation between operands. Operators in Python are the workhorses of your programs. They perform operations on variables and values, allowing you to manipulate data, perform calculations, compare values, and control the flow of your code.
- Arithmetic Operators - ( +, -, *, /, **, / .
ArithmeticOperators
print(6+3)
print(6-3)
print(6*3)
print(6/3)
print(6//3)
print(6%3)
print(6**3)
i=6
i=i+3
i+=3
i-=3
- Relational / Comparison Operators- (==, !=, >, <, >, <= )
- Assignment Operators - (=, +, -, *, /,%, **)
- Logical Operators - (not, and, or)
Type Conversion in Python-
- str()
- int()
- bool()
- float()
Correct -
a,b = 1,2
c=a+b
#error
a,b = 1, "2"
c= a+b
Type Casting in Python-
- int(y [base]) - It converts y to an integer, and Base specifies the number base. For example, if you want to convert the string in decimal numbers then you'll use 10 as base.
- float(y) - It converts y to a floating-point number..
- complex(real [imag]) - It creates a complex number.
- str(y) - It converts y to a string.
- tuple(y) - It converts y to a tuple.
- list(y) - It converts y to a list.
- set(y) - It converts y to a set.
- dict(y)It creates a dictionary and y should be a sequence of (key, value) tuples.
- ord(y) - It converts a character into an integer.
- hex(y) - It converts an integer to a hexadecimal string.
- oct(y) - It converts an integer to an octal string
Type Costing -
a,b = 2, "5"
c =int(b)
sum= a+b
print(sum)
Output- 7
or
a, b = "2" , "5"
c = int(2) + int(5)
print(c)
Output- 7
Input in Python -
input()
function. This function pauses your program's execution and waits for the user to enter some data. Here's a breakdown of how it works:- input( ) statement is used to accept values (using the keyboard) from the user.
- input() - result for input() always in str. ( "Rahulwebtech")
- int(input()) - int value (1, 2, 3, 4, 5)
- float(input()) - float value (1.0, 2.0, 3.2, 4.3)
String Example -
name=input("My Name Is Rahul Bharadwaj?")
print("Hello"+name)
print(" Thanks ....")
Strings
The string is a data type that stores a sequence of characters.
Basic Operations
concatenation “hello” + “world” ------>hello word
length of str
len(str)
Indexing in Python-
str = "Rahul_Bharadwaj"
str[0] is "R" str[1] is "a"
Slicing in Python -
Slicing in Python is a powerful technique for extracting subsets of elements from sequences like strings, lists, and tuples. It allows you to create new sequences based on specific criteria without modifying the original sequence itself.
Syntex -
str[ starting index : Ending index]
str = "Rahul_Bharadwaj"
str[ 2 : 4 ] is "hul"
str[ : 4] is same str[ 0 : 4]
str[ 2 : ] is same str[ 2 : len(str)]
String Functions in Python-
- str = “I am a coder.”
- str.ends with(“er.“) - returns true if string ends with substrate
- str.capitalize( ) - capitalizes 1st char
- str. replace( old, new ) - replaces all occurrences of old with new
- str.find( word ) - returns 1st index of 1st occurrence Apna College
- str.count(“am“) - counts the occurrence of substr in string
Conditional Statements -
Conditional statements are fundamental building blocks in any programming language. They allow your program to make decisions based on certain conditions, leading to different execution paths.
if-elif-else (SYNTAX)
if(condition) :
Statement1
elif(condition):
Statement2
else: StatementN
Conditional Statements Example-
Grade students based on marks
marks >= 90, grade = “A”
90 > marks >= 80, grade = “B”
80 > marks >= 70, grade = “C”
70 > marks, grade = “D”
Lists in Python
A built-in data type that stores a set of values It can store elements of different types (integer, float, string, etc.) Lists are one of the most fundamental and versatile data structures in Python. They are used to store collections of items in a specific order and allow you to access, modify, and iterate through these elements.
marks = [86, 62, 73, 65, 86]
student = [”Rahul”, 68, “Delhi”]
student[0] = “Arya”
len(student)
List Slicing in Python-Similar to String Slicing.
list_name[ starting_idx : ending_idx ] - ending idx is not included
marks = [87, 64, 33, 95, 76]
marks[ 1 : 4 ] is [64, 33, 95]
marks[ : 4 ] - is same as marks[ 0 : 4]
marks[ 1 : ] - is same as marks[ 1 : len(marks) ]
marks[ -3 : -1 ] - is [33, 95]
List Methods in Python -
- list = [2, 1, 3] list.append(4) - adds one element at the end
- list.sort( ) - sorts in ascending order [2, 1, 3, 4] [1, 2, 3]
- list.sort( reverse=True ) - sorts in descending order
- list.reverse( ) - reverses list [3, 1, 2] [3, 2, 1]
- list.insert( idx, el ) - insert element at index
- list = [2, 1, 3, 1] list.remove(1) - removes first occurrence of element
- list.pop( idx ) - removes element at idx [2, 3, 1]
Tuples in Python -
A built-in data type that lets us create immutable sequences of values. Tuples in Python are ordered, immutable collections of elements, similar to lists. However, unlike lists, tuples cannot be modified after they are created.
tuple = (87, 64, 33, 95, 76) - tup[0], tup[1]..
tuple[0] = 43 - NOT allowed in python tup1 = ( )
tup2 = ( 1, )
tup3 = ( 1, 2, 3 )
Tuple Methods in Python-
tup = (2, 1, 3, 1)
tup.index( el ) - returns index of first occurrence
tup.count( el ) - counts total occurrences tup.index(1) is 1 tup.count(1) is 2