2nd Week Python Experience

2nd Week Python Experience

1.CLI VS GLI

CLI:

The Command-Line Interface (CLI) is a text-based interface used to interact with a computer's operating system

GUI:

"Graphical User Interface" (GUI) refers to a type of user interface that allows users to interact with electronic devices or software through graphical elements such as icons, buttons, and windows. GUIs are designed to make it easier for users to interact with computers and software applications by providing visual representations of the system's features.

2.SHELL

"shell" in the context of the Command-Line Interface (CLI) is a user interface for access to an operating system's services. The term "shell" in the context of computing refers to a command-line interface (CLI) that allows users to interact with the operating system by typing commands. In the context of CLI, the shell is the command interpreter that allows users to interact with the operating system by typing commands.

There are different shells available for various operating systems. For example:

  1. Bash (Bourne Again SHell): Commonly used on Unix-like systems, including Linux and macOS.

  2. **Command Prompt:**The default shell on Windows systems.

  3. PowerShell: A more advanced shell and scripting language available on Windows.

3.KERNEL AND OPERATING SYSTEM

A kernel is the core component of an operating system. It is also a system program. It is the part of Operating System which converts user commands into machine language.

An operating system (OS) is a software program that acts as an intermediary between computer hardware and the computer user. It provides a set of services and manages the hardware resources of a computer system

FOR MORE INFO ON O/S AND KERNEL

4.SOME TIPS FOR VARIABLES

Instructions for writing reader-friendly variables -

1. Make the variable self-explanatory.

2. Add comments.

chem_bonus_marks = 3 #this contains bonus marks of subject chemistry

5.DYNAMIC TYPING IN PYTHON

Dynamic typing in Python refers to the ability of variables to change their type during runtime. Unlike languages with static typing, where the type of a variable is explicitly declared and cannot be changed, Python allows you to assign values of different types to a variable without specifying its type beforehand.

Here's an example to illustrate dynamic typing in Python:

# Dynamic typing in Python

# Integer assignment
x = 5
print("x is of type" , type(x))

# Change type to string
x = "Hello, World!"
print("x is of type" , type(x))

# Change type to list
x = [1, 2, 3]
print("x is of type" , type(x))

6.More on Variables, Operators and Expressions

Python, there are some words like and, or, not, if, else, for, while,... which are referred to as 'Keywords'. We can not use these keywords as variable names.

and = 12
print (and)

Rules for writing variable names :-

1. Variable names can contain alphanumeric (all alphabets from A-Z in lower and uppercase and numbers 0-9) characters and underscores.

2. We can start a variable name with an alphabet or an underscore but we cannot start it with a number.

3. Variable names are case sensitive.

roLL = 5
ROLL = 10
Roll = 15
print(roLL, ROLL, Roll)

!!!!! Even though the spellings are the same, the computer treats all three variables as unique variables. This shows that in Python variable names are case sensitive.!!!!!

Multiple Assignment :-

x,y,z=0,0,1  #Note that the order matters
print(x,y,z)   # op : 0 0 1 
x=y=z=1
print(x,y,z)    # op : 1 1 1

Swapping the values of the variables :-

x,c=1,2
x,c=c,x
print(x,c)  # op : 2,1

Deleting a Variable :-

f=12
print(f)
del f 
print(f)

o/p: 12

Traceback (most recent call last): File "/home/runner/17More- on- Variables-Operators-and-Expressions/main.py", line 4 in print(f) Name Error: name 'f' is not defined

Shorthand Operators :-

f=12
print(f)

f += 1 # READ AS (f=f+1)
print(f)

f -= 1 # READ AS (f=f-1)
print(f)

f *= 1 # READ AS (f=f*1)
print(f)

f /= 1 # READ AS (f=f/1)
print(f)

new info :- the division operation/between two integers results in a floating-point division, even if the result is a whole number. This behavior was changed from Python 2.x to Python 3.x for improved precision and to avoid unexpected results, especially when working with mixed-type operations.

in Operator :-

print('alpha' in 'A variable name can only contain alpha-numeric characters and underscores')
print('alpha' in 'A variable name must start with a letter or the underscore character')

op : true

false

1. It checks if the string 'alpha' is in the next string or not.

2.The result of the ‘ in’ operator is always a Boolean value.

Chaining operator :-

  1. When two or more relational operators are used together.

  2. always gives Boolean values.

x=5
print(1<x<10)
print(10<x<20)
print(x<10<x*10<100)
print(10>x<=9)
print(5==x>4)

7.Escape characters

print('It's a beautiful day')

 #returns error

\> so here are some escape characters for tackle this problem .

Backslash (\) :-

print('It\'s a beautiful day') 
#prints It's a beautiful day 
print("We are from "IIT" Madras") 
#returns error ::: The reason the statement print("We are from "IIT" Madras") does not work is due to the incorrect use of double quotes within the string. In Python, if you want to include double quotes within a string that is also delimited by double quotes, you need to use either single quotes around the string or escape the inner double quotes with a backslash. 
print("We are from \"IIT\" Madras")
#prints We are from "IIT" Madras

# print('We are from "IIT" Madras') this also works instead of code on Line 3

Backslash t (\t) :-

  • Used to add tab space. Can be used repetitively. Ex - \t\t\t, etc

  •     print('My name is Fulkit.\t I am from Rijnob')
        #prints My name is Fulkit.    I am from Rijnob
    

Backslash n (\n) :-

print('I am not here. \n This isn\'t happening') 
#prints : I am not here 
#         This isn't happening

to sum-up : \n: Represents a newline character.

  • \t: Represents a tab character.

  • \\: Represents a literal backslash character.

  • \" and \': Represent double and single quotes within a string.

8.Types of quotes

we have studied about single quotes('..') and double quotes("..").

one more is there that is triple quotes ('''....''').

Triple quotes ('''....''')

a. They allow us to create strings that span multiple lines without using escape characters.

multiline_string = '''This is a
multiline
string.'''

b. To comment out more than 1 line .

''' comment1 
    comment2 
    comment3 '''

9.String Methods

String methods in Python are built-in functions that operate on strings, allowing you to perform various operations and manipulations on string data.

We can assume these ‘methods' as some commands which we can execute on STRINGS.

#some tutorials
text = "Hello, World!"
print(text.upper())  # Output: HELLO, WORLD!
print(text.lower())  # Output: hello, world!
print(text.startswith("Hello"))  # Output: True
print(text.endswith("World"))    # Output: True
a= "my python good code"
print(a.rstrip("code"))   # Output: my python good
print(a.rstrip("good"))   # Output: my python  
print(a.lstrip("my"))     # output: python good code 
print(a.lstrip("python")) #output: good code
''' in the comments for the rstrip and lstrip methods, 
you can mention that using multi-character strings may 
not accurately represent the functionality of the code.'''

10.Caesar cipher

The Caesar cipher is a simple and classic encryption technique that involves shifting the letters of the alphabet by a fixed number of positions.

It adds a key to the string and prints the encrypted string as the output -

a='abcdefghijklmnopqrstuvwxyz'
n='anish' #i expect to see output as "bjpqk"

i=0       # position(index) on n (string)
k=20      # shift of position on alphabet index  
t=''

t= t + a [ (((a.index(n[i]))   + k) % 26)] #concatination of string 
t= t + a [ (((a.index(n[i+1])) + k) % 26)] 
t= t + a [ (((a.index(n[i+2])) + k) % 26)]
t= t + a [ (((a.index(n[i+3])) + k) % 26)]
t= t + a [ (((a.index(n[i+4])) + k) % 26)]  
print(t)   # print : uhcmb

11."if" statement

an "if statement" is a control structure that allows you to execute a block of code based on a certain condition.

dob=int(input("Enter your dob:")) 
currentyear=2022 
age = currentyear - dob 
if (age<18):  
    print("Sorry you can't enter") 
else:  
    print("Welcome aboard")

In Python, indentation is used to denote blocks of code, including those within control structures like if statements. Unlike many other programming languages that use braces or keywords to indicate the beginning and end of a block of code, Python uses indentation.

x = 5

if x > 0:
    print("x is positive")
    if x % 2 == 0:
        print("x is even")
    else:
        print("x is odd")
else:
    print("x is non-positive")

12.'if-else' and 'else-if'

if-else:

The "if-else" statement is a control flow structure in Python used for decision-making. It allows a program to execute different code blocks based on whether a given condition is true or false. The basic syntax is as follows:

if condition:
    # code to be executed if the condition is true
else:
    # code to be executed if the condition is false

taking a basic problem to demonstrate this if - else

else-if(elif) :

if condition1:
    # code block to execute if condition1 is True
elif condition2:
    # code block to execute if condition1 is False and condition2 is True
elif condition3:
    # code block to execute if condition1 and condition2 are False and condition3 is True
...
else:
    # code block to execute if all conditions are False

solving using elif for problem 3

# grading marks code
marks=int(input("Enter marks obtained:")) 
if(marks>=0 and marks <=100):   
    if (marks>=90):     
        print("A grade")   
    elif (marks>=80):     
        print("B grade")   
    elif (marks>=70):    
        print("C grade")
    elif (marks>=60):     
        print("D grade")   
    else:     
        print("E grade") 

else:   print("Invalid output")

13.Library

In Python, a library (also referred to as a module) is a collection of functions and classes that shares a common theme . Libraries contain pre-written code that can be imported into your Python script, allowing you to leverage existing functionality without having to write the code from scratch.

To import a library in Python, you can use theimportkeyword, followed by the name of thelibrary.

for example (math library) :

# Import the math library
import math

# Example using functions from the math library
x = 16

# Square root
sqrt_result = math.sqrt(x)
print(f"The square root of {x} is: {sqrt_result}")

# Ceiling (smallest integer greater than or equal to x)
ceiling_result = math.ceil(sqrt_result)
print(f"The ceiling of the square root is: {ceiling_result}")

for example (Random library) :

Certainly! The random module in Python provides functions for generating random numbers. Here's an example using the random module to generate a random integer and a random floating-point number:

# Import the random module
import random

# Generate a random integer between 1 and 10 (inclusive)
random_integer = random.randint(1, 10)
print(f"Random integer: {random_integer}")

# Generate a random floating-point number between 0 and 1
random_float = random.random()
print(f"Random float: {random_float}")

In this example:

  • random.randint(1, 10) generates a random integer between 1 and 10 (inclusive).

  • random.random() generates a random floating-point number between 0 and 1.

You can also use the random.choice() function to randomly select an element from a sequence, such as a list:

# Generate a random choice from a list
fruits = ['apple', 'orange', 'banana', 'grape', 'watermelon']
random_fruit = random.choice(fruits)
print(f"Random fruit: {random_fruit}")

In this case, random.choice(fruits) randomly selects a fruit from the list fruits

These are just a few examples of what you can do with the random module. It's a versatile library that can be used for various applications where randomness is required.

for example (calander library) :

import calendar
print(calendar. Month(2024, 1))


import calendar
print(calendar. Calendar(2024))

14.Different ways to import a library

In Python, there are multiple ways to import a library/module. Here are some common methods:

  • Importing the Entire Module:

    • This is the most straightforward way to import the entire library.

    • It imports the whole ‘calendar’ library and to use any function from it we will have to write ‘calender.function_name’

    • Pros:

      • Simple and straightforward.

      • Maintains a clear link to the original module name.

    • Cons:

      • Can lead to namespace pollution if the module has many functions, potentially causing naming conflicts.
    import calendar

    # Example usage
    cal = calendar.month(2024, 1)
    print("January 2024:\n", cal)

2.From calendar import :

  • Asterisk(*) brings everything inside the calendar library into this python program, now we don't have to write ‘ calendar . ’ before any function to use it.

  • You can import everything from a module into the current namespace. This is generally discouraged to avoid naming conflicts.

  • Pros:

    • Allows using functions directly without specifying the module name.
  • Cons:

    • Strongly discouraged due to potential naming conflicts and reduced code readability.

    • May make it challenging to identify the origin of functions or classes.

from calendar import *

# Example usage
full_calendar = month(2024, 1)
print("January 2024:\n", full_calendar)

3.Importing Specific Functions/Classes:

  • You can import specific functions or classes from a library, reducing the need to use the library name when calling them.

  • Pros:

    • Selectively imports only what is needed, reducing memory usage.

    • Improves code readability by explicitly showing which functions/classes are used.

  • Cons:

    • If many functions are imported, it can still lead to some namespace pollution.

    • Potential naming conflicts if functions have the same name as existing ones in your code.

from calendar import month,year

# Example usage
january_calendar = month(2024, 1)
print("January 2024:\n", january_calendar)
2024_calendar = calendar(2024)
print("2024 calender:",2024_calendar)

4.Importing with an Alias:

You can import a library with an alias (a shorter name) to make it easier to reference.

  • Pros:

    • Provides a shorter and more convenient name for the module.

    • Reduces the chance of naming conflicts.

  • Cons:

    • The chosen alias should be clear and not create confusion.
import calendar as cal

# Example usage
month_calendar = cal.month(2024, 1)
print("January 2024:\n", month_calendar) 
# or like this 
from calendar import month as m
print(builtuary 2024:\m",m)

/// this were all in-buit libraries in python .

15.Some Extra Shit

a. Code 1 and Code 2 have equivalent behavior in terms of producing output. Both will print 'works' when flag is True, and no output will be produced if flag is False or not defined.

Here's a breakdown of each code:

Code 1:

flag = True
if flag:
    print('works')  # This line will execute because flag is True

Code 2:

flag = True
if flag == True:
    print('works')  # This line will execute because flag is True

In Python, theifstatement checks whether the expression or condition provided evaluates toTrueorFalse. If the expression evaluates toTrue, the code block associated with theifstatement will be executed. Otherwise, if the expression evaluates toFalse, the code block will be skipped. But by defaultifchecks for True and executes automatically .

b.

c. Slicing is a concept in Python that allows you to extract a subset of elements from a sequence like a string, list, or tuple.

Here's how slicing works:

sequence[start:stop:step]
  • start: The starting index for the slice. It specifies the position from where the slice begins.

  • stop: The ending index for the slice. It specifies the position where the slice ends. Note that the character at this index is not included in the slice.

  • step: The step size or the increment between the elements selected in the slice.

If any of these parameters are omitted, Python uses default values: start defaults to the beginning of the sequence, stop defaults to the end of the sequence, and step defaults to 1.

Here's a basic example:

alphabets = 'abcdefghijklmnopqrstuvwxyz'
subset = alphabets[3:10:2]
print(subset)

This will output:

dfhj

Explanation:

  • alphabets[3:10:2] selects characters starting from index 3 ('d') up to index 9 ('j') with a step size of 2, so it selects every other character between 'd' and 'j', resulting in the subset 'dfhj'.

d.

In Python, when you use the input() function, it reads a line of input from the user and returns it as a string. If you provide no argument to input(), it expects the user to enter a single line of input.

Now, when you do a, b, c, d = input(), Python will try to unpack the input string into individual variables a, b, c, and d. Here's how it works:

  • The input string "1234" is treated as a single string.

  • Python tries to unpack this string into four variables (a, b, c, and d).

  • Each character of the string is assigned to a separate variable.

So, in this case, the input "1234" will be unpacked like this:

  • a will be assigned the character '1'

  • b will be assigned the character '2'

  • c will be assigned the character '3'

  • d will be assigned the character '4'

In Python, unpacking refers to the process of extracting values from iterable objects like lists, tuples, or dictionaries, also strings and assigning them to variables in a single statement. It's a convenient way to access individual elements of a data structure without needing to index them individually.

e. In Python, you can reverse a string using slicing. Here's a simple way to do it:

my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string)

Output:

olleh

Let's break down how this works:

  • my_string[::-1]: This slicing syntax [start:end:step] specifies that we want to slice the entire string (start and end are omitted, so it starts from the beginning and ends at the end) with a step of -1. This means it will traverse the string from end to start, effectively reversing it.

  • reversed_string = my_string[::-1]: This assigns the reversed string to the variable reversed_string.

  • print(reversed_string): This prints the reversed string.

So, my_string[::-1] is a concise way to reverse a string in Python using slicing.

f. How to replace a particular character from a string?

word = 'g00d'
word = word.replace('0', 'o')
print(word)

g. Lets go for a fun question :: Accept four integers as input and write a program to print these integers in non-decreasing order.

The input will be four integers in four lines. The output should be a single line with all the integers separated by a single space in non-decreasing order. Note: There is no space after the fourth integer.

  1. Input: The code first prompts the user to input four integer values: a, b, c, and d.

     a=int(input())
     b=int(input())
     c=int(input())
     d=int(input())
    
  2. Sorting: The code then compares pairs of adjacent variables and swaps them if they are not in ascending order. This is done using a series of if statements.

     if a > b:
         a, b = b, a
    
     if b > c:
         b, c = c, b
    
     if c > d:
         c, d = d, c
    

    This part ensures that after these comparisons and swaps, the variables a, b, c, and d are arranged in ascending order.

  3. Additional Sorting: The code repeats the same comparison and swap operations multiple times to ensure that the variables are fully sorted. This is done to ensure that the variables are sorted in ascending order even if they were initially not in the correct order.

     if a > b:
         a, b = b, a
    
     if b > c:
         b, c = c, b
    
     if a > b:
         a, b = b, a
    
  4. Output: Finally, the sorted values of a, b, c, and d are printed.

     print(a, b, c, d)
    

This code essentially sorts the input values in ascending order using a series of comparison and swap operations. It repeatedly checks and swaps adjacent values until they are all in ascending order. This ensures that after the execution of the code, a is the smallest value, d is the largest value, and b and c are in between.