# Chapter 1,2: Basics
example 1.
# a=5
# b=3
# c=a+b
# print(c)
example 2.
# x = “COE”
# print(x)
# x=99
# print(x)
example 3.
# x, y, z = “COE”, “PMKVY”, “NGF”
# print(x,y,z)
# print(x+y+z)
# print(x)
# print(y)
# print(z)
# x=5
# print(x)
# x = y = z = “Brown”
# print(x)
example 4.
t=”my”
u=’name is’
v=”___” #your name
print(t+u+v)
subject= “hindi”
mobileNo = “xyz”
Variables
myvariablename0=0
myVariableName1=1
MyVariableName2=2
my_variable_name3=”hello”
example 5.
a=15
b=9
c= a-b
example 6.
costOfToy=15
discount=9
total=costOfToy-discount
print(total)
print(type(total))
# Chapter 3: Data Types
age = 25
is_student = True
average_grade = 89.5
name = “Alice”
print(age, is_student, average_grade, name)
# Chapter 4: Numbers
x = 10
y = 3
sum_result = x + y
diff_result = x – y
prod_result = x * y
div_result = x / y
print(sum_result, diff_result, prod_result, div_result)
# Chapter 5: Strings
course_name = “Python Programming”
instructor = “John Doe”
full_message = “Welcome to the ” + course_name + ” course, taught by ” + instructor + “.”
print(full_message)
# Chapter 6: Lists, Tuples, and Dictionary
fruits = [“apple”, “banana”, “cherry”]
point = (3, 7)
person = {
“name”: “John”,
“age”: 30,
“is_student”: False
}
print(fruits)
print(point)
print(person)
# Chapter 7: Lists, Tuples, and Dictionary (Continued)
fruits.append(“orange”)
point = point + (5, 2)
person[“occupation”] = “Engineer”
print(fruits)
print(point)
print(person)
# Chapter 8: Exercise – Temperature Conversion
celsius_temperature = 25
fahrenheit_temperature = (celsius_temperature * 9/5) + 32
print(“Celsius:”, celsius_temperature)
print(“Fahrenheit:”, fahrenheit_temperature)
# Operators in python
# Chapter 9: Arithmetic Operators
a = 9
b = 2
addition = a + b
subtraction = a – b
multiplication = a * b
division = a / b
modulus = a % b
exponentiation = a ** b
print(addition, subtraction, multiplication, division, modulus, exponentiation)
# Chapter 10: Relational/Comparison Operators
x = 5
y = 8
greater_than = x > y
less_than = x < y
equal_to = x == y
not_equal_to = x != y
print(greater_than, less_than, equal_to, not_equal_to)
# Chapter 11: Logical Operators
good = True
best = False
logical_and = good and best
logical_or = good or best
logical_not_good = not good
logical_not_best = not best
print(logical_and, logical_or, logical_not_good, logical_not_best)
# Chapter 12: Assignment Operators
x = 10
x += 5
# x -= 3
# x *= 2
# x /= 4
print(x)
# # Chapter 13: Bitwise Operators
# num1 = 10
# num2 = 7
# bitwise_and = num1 & num2
# bitwise_or = num1 | num2
# bitwise_xor = num1 ^ num2
# bitwise_left_shift = num1 << 2
# bitwise_right_shift = num1 >> 1
# print(bitwise_and, bitwise_or, bitwise_xor, bitwise_left_shift, bitwise_right_shift)
# Chapter 14: Identity Operators
x = [1, 2, 3]
y = [1, 2, 3]
z = x
is_x_y = x is y
is_x_z = x is z
is_x_not_y = x is not y
# print(is_x_y, is_x_z, is_x_not_y)
# Chapter 15: Membership Operators
fruits = [“apple”, “banana”, “cherry”]
is_apple_present = “apple” in fruits
is_mango_absent = “mango” not in fruits
print(is_apple_present, is_mango_absent)
# Chapter 16: Operator Precedence
result = 5 + 3 * 2 – 6 / 3
# The result is calculated as 5 + (3 * 2) – (6 / 3)
print(result)
# Conditional Statement
# 1. If Statement
age = 18
if age >= 18:
print(“You are an adult.”)
# 2. If-Else Statement
age = 15
if age >= 18:
print(“You are an adult.”)
else:
print(“You are a minor.”)
# 3. Elif Statement (Multiple Conditions):
score = 85
if score >= 90:
grade = “A”
elif score >= 80:
grade = “B”
elif score >= 70:
grade = “C”
else:
grade = “D”
print(“Your grade is:”, grade)
# 4. Nested If-Else Statement
is_raining = True
has_umbrella = False
if is_raining:
print(“It’s raining.”)
if has_umbrella:
print(“You can go outside with an umbrella.”)
else:
print(“Stay indoors.”)
else:
print(“It’s not raining, enjoy the weather!”)
# String Methods:
# Single Quotes: Create a string using single quotes.
my_string = ‘Hello, World!’
# Double Quotes: Create a string using double quotes.
my_string = “Hello, World!”
# Triple Quotes: Create a multi-line string using triple quotes.
multi_line_string = ”’
This is a
multi-line
string.
”’
#—————– Accessing Characters
# Indexing: Access characters by index (0-based).
my_string = “Hello, World!”
char = my_string[0]
print(char) # Gets the first character ‘H’
# Slicing: Get a substring using slicing.
my_string = “Hello, World!”
sub_string = my_string[7:12]
print(sub_string) # Gets ‘World’
# Negative Indexing: Access characters from the end.
my_string = “Hello, World!”
last_char = my_string[-1]
print(last_char) # Gets the last character ‘!’
#————- String Methods
# len(): Get the length of a string.
my_string = “Hello, World!”
length = len(my_string) # Returns 13
# str.upper() and str.lower(): Convert a string to uppercase or lowercase.
my_string = “Hello, World!”
upper_case = my_string.upper() # Converts to uppercase
lower_case = my_string.lower() # Converts to lowercase
# str.strip(): Remove leading and trailing whitespace.
my_string = “Hello, World!”
stripped = my_string.strip() # Removes leading/trailing spaces
# str.replace(): Replace occurrences of a substring.
my_string = “Hello, World!”
new_string = my_string.replace(‘Hello’, ‘Hi’) # Replaces ‘Hello’ with ‘Hi’
# str.split(): Split a string into a list of substrings.
my_string = “Hello, World!”
words = my_string.split(‘,’) # Splits on commas
# str.join(): Join a list of strings into one string.
my_string = “Hello, World!”
joined_string = ‘-‘.join([‘Hello’, ‘World’]) # Joins with a hyphen
# or
my_string = [“Hello”, “World”]
joined_string = “-“.join(my_string) # Joins with a hyphen
# str.find() and str.index(): Find the index of a substring.
my_string = “Hello, World!”
index = my_string.find(‘World’) # Returns index of ‘World’ (7)
# ——————- String Formatting
# f-Strings: Use f-strings for string interpolation.
name = ‘Alice’
greeting = f‘Hello, {name}!’ # Creates ‘Hello, Alice!’
# str.format(): Format strings with placeholders.
name = ‘Akash’
formatted = ‘Hello, {}!’.format(name) # Same result as f-string
eg.2
name = ‘Akash’
age=26
multiple_placeholders=”My name is {}, I’m {}”.format(name, age) #Output: My name is Akash, I’m 26
# String Concatenation: Combine strings with the + operator.
name = ‘Ajay’
combined = ‘Hello, ‘ + ‘World!’ # Creates ‘Hello, World!’
combinedWithVar = ‘Hello, ‘ + name # Creates ‘Hello, ‘Ajay
# String Interpolation using % (Older Python Versions):
In older Python versions, you can use the % operator for string interpolation:
name = “Ajay”
age = 30
message = “My name is %r and I am %d years old.” % (name, age)
print(message)
#Output: My name is ‘Ajay’ and I am 30 years old.
In string formatting, the placeholders like %s, %d, %r, and %f are known as format specifiers, and they are used to define how values should be formatted and inserted into a string.
%s: This is used for string formatting. It is used to insert a string into the formatted string.
%d: This is used for integer formatting. It is used to insert an integer into the formatted string. The %d specifier is typically used for whole numbers.
%r: This is used for representing any Python object as a string. It is known as the “repr” specifier. It inserts the string representation of an object into the formatted string. It’s often used for debugging and displaying a more detailed representation of an object.
%f: This is used for floating-point (decimal) formatting. It is used to insert a floating-point number into the formatted string. It allows you to control the precision and formatting of floating-point numbers, including the number of decimal places.
# ————Escape Sequences
# Escape Sequences: Use escape characters for special characters.
# Newline (\n): Used to insert a newline character into the string.
Newline=”hello how are you \n sanjay”
print(Newline) # Output: This is a newline: \n is treated as a newline character.
escaped_string = ‘This is a newline: \\n’
print(escaped_string) # Output: This is a line: \n
# In this example, the double backslash \\ is used to escape the backslash itself.
# Tab (\t): Used to insert a tab character into the string.
tabbed_string = ‘This is a tab: \\t’
print(tabbed_string) # Output: This is a tab: \t
# Single Quote (\’): Used to include a single quote character within a single-quoted string.
single_quote_string = ‘He said, \’Hello!\”
print(single_quote_string) # Output: He said, ‘Hello!’
# In this example, the single quote within the single-quoted string is escaped using \’.
# Double Quote (\”): Used to include a double quote character within a double-quoted string.
double_quote_string = “She said, \”Hi!\””
print(double_quote_string) # Output: She said, “Hi!”
# Similarly, you can use \” to include a double quote within a double-quoted string.
# Backslash (\\): Used to include a literal backslash character within the string.
backslash_string = ‘This is a backslash: \\\\’
print(backslash_string) # Output: This is a backslash: \\
# To include a backslash itself in the string, you need to escape it with another backslash, resulting in \\\\.
#————— String Checks
# str.startswith() and str.endswith(): Check if a string starts or ends with a substring.
my_string = “Hello, World!”
starts_with = my_string.startswith(‘Hello’) # True
ends_with = my_string.endswith(‘!’) # True
# str.isalnum(), str.isalpha(), str.isdigit(): Check if the string contains alphanumeric characters, alphabetic characters, or digits, respectively.
my_string = “Hello, World!”
is_alnum = my_string.isalnum() # False (contains spaces and punctuation)
is_alpha = my_string.isalpha() # False (contains spaces and punctuation)
is_digit = my_string.isdigit() # False (contains letters and punctuation)
# str.islower() and str.isupper(): Check if the string is in lowercase or uppercase.
my_string = “Hello, World!”
is_lower = my_string.islower() # False (contains uppercase)
is_upper = my_string.isupper() # False (contains lowercase)