Python

I. Python Programming

II. What is Python?

  • Python is a popular programming language created by Guido van Rossum in 1991.

  • Uses:

    • Web development (server-side)

    • Software development

    • Mathematics

    • System scripting

III. Variables

  • Variables in Python are created by assigning a value:

    • Example:

      • num1 = 5

      • message = "Hello"

      • num2 = 3.2

A. Variable Names

  • Can be short (e.g., x, y) or descriptive (e.g., age, carname, total_volume).

  • Rules for Python Variables:

    • Must start with a letter or underscore.

    • Cannot start with a number.

    • Can only contain alphanumeric characters and underscores (A-z, 0-9, _).

    • Variables are case-sensitive (e.g., age, Age, and AGE are different).

B. Assigning Values to Multiple Variables

  • Multiple variables can be assigned in one line:

    • Example:

      • x, y, z = "Orange", "Banana", "Cherry"

      • a, b, c = 5, 7, 9

  • Same value for multiple variables:

    • Example:

      • X = Y = Z = "ORANGE"

      • A = B = C = 5

IV. Data Types

  • Python has built-in data types classified as follows:

    • Text Type: str

    • Numeric Types: int, float, complex

    • Sequence Types: list, tuple, range

    • Mapping Type: dict

    • Set Types: set, frozenset

    • Boolean Type: bool

    • Binary Types: bytes, bytearray, memoryview

A. Setting the Data Type

  • The data type is set upon assignment:

    • Example:

      • x = "Hello World"

      • x = 20

      • x = 20.5

      • x = 1j

      • x = ["apple", "banana", "cherry"]

      • x = ("apple", "banana", "cherry")

      • x = range(6)

      • x = True

B. Setting a Specific Data Type

  • Examples for casting:

    • x = str("Hello World")

    • x = int(20)

    • x = float(20.5)

    • x = complex(1j)

    • x = list(("apple", "banana", "cherry"))

    • x = tuple(("apple", "banana", "cherry"))

V. Python Numbers

  • Three numeric types:

    • int

    • float

    • complex

  • Example of variable creation:

    • x = 1 # int

    • y = 2.8 # float

    • z = 1j # complex

A. Python Casting

  • Use constructor functions for casting:

    • Function int() creates an integer from literals or strings representing integers.

    • Function float() creates a float from integers, floats, or strings.

    • Function str() creates a string from various data types.

VI. Random Number Generation

  • Use import statement to access the random module:

    • Example:

      • import random

      • print(random.randrange(1, 10))

VII. Print Function

  • Use print() to display output:

    • Example:

      • print("Welcome")

      • print('Welcome')

VIII. User Input

  • User input can be taken using the input() function:

    • Example:

      • name = input("Enter Name: ")

      • print("Hi " + name)

    • Convert input to integer:

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

      • print(n)

IX. Python Strings

A. String Literals

  • Can be enclosed in single or double quotes:

    • Example:

      • print("Hello")

      • print('Hello')

B. Multiline Strings

  • Use triple quotes for multiline strings:

    • Example:

      • a = '''The quick brown fox jumps over the lazy dog'''

      • print(a)

C. Strings are Arrays

  • Strings are considered arrays of bytes representing characters.

  • Access elements using square brackets:

    • Example:

      • print(a[1]) # get character at position 1

D. String Slicing

  • Use slice syntax (start:end) to extract parts of the string:

    • Example:

      • print(b[2:5]) # returns characters from position 2 to 5

E. Negative Indexing

  • Allows counting from the end:

    • Example:

      • print(b[-5:-2]) # characters from the end

F. String Length

  • Use len() function to find the length of a string:

    • Example:

      • print(len(a))

G. String Methods

  • Various built-in methods:

    • strip(): Removes whitespace.

    • lower(): Converts to lowercase.

    • upper(): Converts to uppercase.

    • replace(): Replaces specific substring.

    • split(): Splits into substrings.

H. Check String Existence

  • Use in or not in to check for phrases or characters:

    • Example:

      • x = "ain" in(txt)

      • print(x)

I. Combining Strings and Numbers

  • Use format() method for combining:

    • Example:

      • txt = "My name is John, and I am {}".format(age)

J. String Concatenation

  • Combine strings using + operator:

    • Example:

      • c = a + b

K. Escape Characters

  • Use backslash to insert special characters:

    • Example:

      • txt = "We are the so-called \"Vikings\" from the north."

X. Python Operators

  • Divided into groups:

    • Arithmetic operators

    • Assignment operators

    • Comparison operators

    • Logical operators

    • Identity operators

    • Membership operators

    • Bitwise operators

XI. Arithmetic Operators

  • Performing mathematical operations on numeric values:

    • +: Addition

    • -: Subtraction

    • *: Multiplication

    • /: Division

    • %: Modulus

    • **: Exponentiation

    • //: Floor division

XII. Comparison Operators

  • Compare two values:

    • ==: Equal

    • !=: Not equal

    • >: Greater than

    • <: Less than

    • >=: Greater than or equal

    • <=: Less than or equal

XIII. Logical Operators

  • Combine conditional statements:

    • and: True if both statements are true

    • or: True if one is true

    • not: Reverses the truth value

XIV. Identity Operators

  • Compare objects by memory location:

    • is: True if both are the same object

    • is not: True if they are not the same object

XV. Membership Operators

  • Test for presence in a sequence:

    • in: True if value is present

    • not in: True if value is absent

XVI. Bitwise Operators

  • Used to compare binary numbers:

    • &: AND

    • |: OR

    • ^: XOR

    • ~: NOT

    • <<: Left shift

    • >>: Right shift

XVII. Conditional Statements

A. If Statements

  • Written using the keyword if:

    • Example:

      • if condition: statements

B. Short Hand If

  • Used for single statement:

    • Example:

      • if condition: statement

C. If...Else

  • Syntax:

    • if condition: statements else: statements

D. Short Hand If...Else

  • Ternary operator syntax:

    • Example:

      • print("Equal") if a==b else print("Not Equal")

E. If..Elif..Else

  • Syntax:

    • Example:

      • if condition: statements elif condition: statements else: statement

F. Logical Operators with If

  • Combined conditions:

    • Example:

      • if g>=75 and g<=100: print("Passed")

      • if g>75 or g==75: print("Passed")