Basic of Python

The syntax of Python is straightforward and resembles that of English. Python's syntax differs from various other programming languages in that it enables programmers to construct applications with fewer lines of code. Python operates on an interpreter system, allowing for the immediate execution of written code. As a result, prototyping can proceed quickly.

Some basics of python

  • Print() Function
  • Escape Sequence
    • Types of Escape sequence
  • Comments
  • Variable
  • Rule for assigning variable
  • String Concatenation
  • User Input
  • Int() Function
  • Two or more input in one line
  • String Formatting
  • String Indexing
  • String Slicing
  • Step Argument
  • String methods
    • len() Function
    • lower() Method
    • Upper() Method
    • Tilt() Method
    • Count() Method
  • Solving problem with Space
    • lstrip Method
    • rstrip Method
    • strip Method
  • Find and Replace Method
  • String as Immutable

Print() Function

Any number of parameters can be sent to the print() function in Python, which puts them out on a single line of text.

print("Hello Anisha")
print('Hello Anisha')
Hello Anisha
Hello Anisha
print("Hello "Anisha"")
print('Hello 'Anisha'') 
  File "C:\Users\default.LAPTOP-1LOPBDH8\AppData\Local\Temp\ipykernel_3076\3133193719.py", line 2
    print("Hello "Anisha"")
                       ^
SyntaxError: invalid syntax
print("hello 'Anisha'")
print('Hello "Anisha"')
hello 'Anisha'
Hello "Anisha"

Escape Sequence

Use an escape character to terminate characters that aren't allowed in a string. A backslash (/) is an escape character, and the character you want to insert comes after it.

print("Hello \"Anisha\"")
Hello "Anisha"
  • Types of Escape sequence
    \' Single Quote
    \\ Backslash
    \n New Line
    \r Carriage Return

    \t Tab
    \b Backspace

    \f Form Feed

Comments

Python code can be explained using comments.Comments are sued to make code more readable.

# Single line comments are done using '#' symbol
# example
# This is single line comment
# Multiple  line comments are done using ' """ ' ' """" ' symbol
# example

"""
This is a comment
written in
more than just one line
"""
print("Hello Anisha") 
Hello Anisha

Variable

Variable are container to store the value. It is declared as soon as value is assiged to it.

a = 7
A = "Anisha"

print(a)
print(A)
7
Anisha
x = 7
y = "Anisha"
print(type(x))
print(type(y))
<class 'int'>
<class 'str'>
x = "Anisha"
print(x)
# is the same as
x = 'Anisha'
print(x)
Anisha
Anisha

Rule for assigning variable

Some of the rules for assigning variable are as follows:

  1. A variable name must start with a letter or the underscore character
  2. A variable name cannot start with a number
  3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  4. Variable names are case-sensitive (age, Age and AGE are three different variables)
myvar = "Anisha"
my_var = "Anisha"
_my_var = "Anisha"
myVar = "Anisha"
MYVAR = "Anisha"
myvar2 = "Anisha"

#Illegal variable names:
2myvar = "Anisha"
my-var = "Anisha"
my var = "Anisha"
  File "C:\Users\default.LAPTOP-1LOPBDH8\AppData\Local\Temp\ipykernel_3076\572073197.py", line 10
    2myvar = "Anisha"
         ^
SyntaxError: invalid syntax

String Concatenation

String concatenation means add strings together. We use the + character to add a variable to another variables.

first=("Anisha")
second=("Dhakal")
third=first + second
print(third)
AnishaDhakal
a = "Anisha"
b = "Dhakal"
c = a + " " + b
print(c)
Anisha Dhakal
x = 5
y = "John"
print(x + y)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_3076\3024526177.py in <module>
      2 x = 5
      3 y = "John"
----> 4 print(x + y)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
a= " Anisha"
b= 7
print(a * b)
 Anisha Anisha Anisha Anisha Anisha Anisha Anisha

User Input

It is the process to ask input from user and execute it.

username = input("Enter username:")
print("Username is: " + username)
Enter username:Anisha
Username is: Anisha

Int() Function

Int functionis used to change the user input into int data type.

first=int(input("enter first number"))
second=int(input("enter second number"))
third= first+ second
enter first number7
enter second number2

Two or more input in one line

This is way to enter input in many variable at same line.

name,age="Anisha","20" # the input should be in order of variable name 
print("hello" + name+"your age is "+"age")
helloAnishayour age is age
name,age=input("enter your name and age ").split(",")
# .split(","): it is used to give comma
# .split(" "): it is used to add space
enter your name and ageanisha , Dhakal

String Formatting

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}.

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)

print(txt1)
print(txt2)
print(txt3)
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36

String Indexing

The index() method finds the first occurrence of the specified value. It raises an exception if the value is not found.

name = "Hello, my name is ANISHA."

x = name.index("l")

print(x)
2

String Slicing

We can return a range of characters by using the slice syntax. It specifes the start index and the end index, separated by a colon, to return a part of the string.

pencil = "era ser"
print(pencil[2:4])
a 

Step Argument

It is process as String Slicing but here we even mention the step at last of [ ]

name="Anisha"
print(name[1:4:2])
ns

String Methods

All string methods returns new values. They do not change the original string.

  • len() function It is used to count the length of string.
name= " Anisha dhakal"
print(len(name))
14
  • lower() Method It is used to change the given strng in lowercase.
    We use . in method
name= " Anisha dhakal"
print(name.lower())
 anisha dhakal
  • upper() Method It is used to change the given strng in uppercase.
name= " Anisha dhakal"
print(name.upper())
 ANISHA DHAKAL
  • title() Method It is used to change first letter of string in capital case.
name= " anisha dhakal"
print(name.title())
 Anisha Dhakal
  • count() Method It is used to count string as well as character repetation time.
name= " anisha dhakal"
print(name.count("a"))
4

Solving problem with Space

Some methods are used to resize the space given in the string. It can be solved by using lstrip method,rstrip method and strip method.

  • lstrip method It prints all string towards left side, recuding space in left.
name=("      Anisha        ")
print(name.lstrip())
Anisha        
  • rstrip method It prints all string towards right side, recuding space in right.
name=("      Anisha        ")
print(name.rstrip())
      Anisha
  • strip method It prints all string removing space in left and right side.
name=("      Anisha        ")
print(name.strip())
Anisha

Find and Replace Method

The find() method finds the first occurrence of the specified value.
The Python programming language's built-in replace() method creates a replica of the string by replacing every instance of one substring with a different substring.

txt = "Hello, welcome to my world."

x = txt.find("welcome")

print(x)
7
txt = "I like mangos"

x = txt.replace("mangos", "apples")

print(x)
I like apples

String as Immutable

These means new output doesn't come in case of string, replace method should be added to new variable name first.

string="anisha"
string.replace('a','A')
print(string)
anisha
string="anisha"
string.replace('a','A')
print(string.replace('a','A',))
anisha