.LonePy Compiler.| Design & Development || Lone A Firdous | | Course Editors | | Youssef Yasser Kusibati | Abdulrahman Mohammed A Aljohani || Feedback | Suggestions | Improvements || Email | @ | lonevlabs@gmail.com |
>EXIT
Lecture Mode
Generate Flowchart
task_alt
..PYTHON TUTORIAL:BASICS
Python Intro<>
Python is one of the most widely used pro
gramming languages nowadays. Despite being a general-purpose language, its applications span a wide range, including web development, IoT, machine learning, and artificial intelligence.
This Python tutorial is to assist the basic programmers in understanding the fundamentals to more complex ideas of the Python programming language. Upon finishing this training, you will have a great deal of proficiency with Python, which will allow you to advance and become a highly skilled software engineer.
* What is Python? *
Python is a widely used high-level, object-oriented, interpreted, general-purpose computer language. Python is a garbage-collected programming language with dynamic typing. Guido van Rossum designed it between 1985 and 1990. The GNU General Public License (GPL) is used to distribute Python source code, much like it is for Perl.
* Python Jobs *
Today, a Python Programmer with 3-5 years of expertise is asking for an annual salary of roughly $150,000, and Python is the most demanding programming language. However, this may vary based on the location of the job. It's impossible to list all of the firms that use Python, but a few big ones are:
Google-Intel-NASA-PayPal-Facebook-IBM-Amazon-Netflix-Pinterest-Uber and many more...
* Why to Learn Python? *
# Python is Open Source which means its available free of
# Python is simple and so easy to learn"
# Python is versatile and can be used to create many different things."
# Python has powerful development libraries include AI, ML etc."
#Python is much in demand and ensures high salary"
* Python Features*
# Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP."
# Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
# Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
# Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.
* My Python Online Compiler *
My Python programming tutorial provides various examples to explain different programming concepts. I have provided Online Python Compiler/Interpreter on the left side of the screen. You can Edit and Execute almost all the
examples directly from your browser without the need to set up your development environment.
Python Syntax:Print()<>
The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.
# Example 1:Print a string# Print a stringprint("Hello, World!")
# Example 2:Print Multiple Values# Print multiple valuesprint("Hello", "World")
# Example 3: Print variables# Declare a variablename = "Alice"
# Declare another variableage = 25
# Print variablesprint("Name:", name, "Age:", age)
# Example 4: Use f-string# Declare variablesname = "Bob"
# Declare another variableage = 30
# Use f-string to printprint("My name is", name, "and I am", age, "years old.")
# Example 5: Print numbers# Print an integerprint(100)
# Print a floatprint(3.14)
# Example 6: Concatenate strings# Declare string variablesgreeting = "Hello"
# Declare another string variablename = "Charlie"
# Concatenate and printprint(greeting, ",", name, "!")
# Example 7: Print escape characters# Print with new lineprint("Hello\nWorld")
# Print with tab spaceprint("Hello\tWorld")
# Example 8: Print a list# Declare a listfruits = ["apple", "banana", "cherry"]
# Print the listprint(fruits)
# Example 9: Suppress newline in print# Print without new lineprint("Hello", end=" ")
# Continue on the same lineprint("World")
# Example 10: Print a formatted float# Print a formatted float with 2 decimal placesprint("Pi is approximately:", round(3.14159, 2))
# Example 11: Print with padding# Print with paddingprint("Number:", str(7).zfill(3))
# Example 15: Print with string interpolation# String interpolation in printname = "Alice"
# Print interpolated stringprint("Hello", name, "!")
# Example 16: Print a complex number# Print a complex numberprint(3 + 5j)
# Example 17: Print boolean expressions# Print a boolean expressionprint(5 > 3)
# Example 18: Print file content# Print content of a filewith open('example.txt', 'r') as file:
print(file.read())
# Example 19: Print with a loop# Print numbers using a loopfor i in range(5):
print(i)
# Example 20: Print exception handling# Print an error message in exception handlingtry:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
# Example 21: Print list comprehension# Print list comprehension resultnumbers = [x**2 for x in range(5)]
print(numbers)
# Example 22: Print date and time# Print the current date and timeimport datetime
print(datetime.datetime.now())
# Example 23: Print memory address of a variable# Print memory address of a variablex = 10
print(hex(id(x)))
# Example 25: Print after importing a module# Import math module and print a valueimport math
print(math.pi)
# Example 26: Print bytes# Print a byte objectbyte_data = b"Hello"
print(byte_data)
# Example 27: Print list elements on separate lines# Print each element of a list on a new linefruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Example 28: Print with keyword arguments# Print using keyword argumentsprint("Hello", "World", sep="-", end="!")
# Example 29: Print a tuple# Print a tuplemy_tuple = (1, 2, 3)
print(my_tuple)
Python Syntax:Input()<>
# Example 1: Text Input# enter a text inputtext = input("Enter some text: ")
# print the entered textprint("You entered:", text)
# Example 2: Integer Input# enter an integer inputnumber = int(input("Enter an integer: "))
# print the entered numberprint("The number you entered is:", number)
# Example 3: Float Input# enter a float inputdecimal = float(input("Enter a decimal number: "))
# print the entered floatprint("The decimal number you entered is:", decimal)
# Example 4: Converting String to Integer# enter a string inputstring_number = input("Enter a number as a string: ")
# convert the string to an integerconverted_number = int(string_number)
# print the converted integerprint("Converted integer:", converted_number)
# Example 5: Arithmetic Operation# input two numbersnum1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# perform additionsum_result = num1 + num2
# print the resultprint("The sum is:", sum_result)
# Example 6: Character Input# enter a single characterchar = input("Enter a character: ")[0]
# print the entered characterprint("You entered:", char)
# Example 7: Boolean Conversion# enter a valuevalue = input("Enter any value (true/false): ")
# convert the value to a booleanboolean_value = bool(value)
# print the boolean valueprint("Boolean conversion result:", boolean_value)
# Example 8: Multiple Inputs in One Line# enter two numbers separated by a spacenum1, num2 = map(int, input("Enter two numbers separated by space: ").split())
# print the entered numbersprint("First number:", num1, "Second number:", num2)
# Example 9: Input with a Default Value# input with default value handlingname = input("Enter your name (default is 'Guest'): ") or "Guest"
# print the nameprint("Hello,", name, "!")
# Example 10: Input and Type Conversion to List# enter numbers separated by commasnumbers = list(map(int, input("Enter numbers separated by commas: ").split(',')))
# print the list of numbersprint("List of numbers:", numbers)
# Example 11: Checking Input Type# enter any inputvalue = input("Enter any value: ")
# print the type of the entered valueprint("The type of entered value is:", type(value))
# Example 12: Summing Multiple Integer Inputs# input multiple integers separated by spacenumbers = map(int, input("Enter multiple integers separated by space: ").split())
# sum the entered numberstotal = sum(numbers)
# print the total sumprint("The total sum is:", total)
# Example 13: Inputting and Concatenating Strings# enter two stringsstring1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
# concatenate the stringsconcatenated = string1 + " " + string2
# print the concatenated resultprint("Concatenated string:", concatenated)
# Example 14: Inputting and Multiplying a String# enter a string and a numbertext = input("Enter a string: ")
repeat = int(input("Enter the number of repetitions: "))
# multiply the stringresult = text * repeat
# print the repeated stringprint("Repeated string:", result)
# Example 15: Inputting and Finding Maximum Value# enter multiple integers separated by spacenumbers = list(map(int, input("Enter numbers separated by space: ").split()))
# find the maximum valuemax_value = max(numbers)
# print the maximum valueprint("The maximum value is:", max_value)
# Example 16: Inputting and Finding Minimum Value# enter multiple integers separated by spacenumbers = list(map(int, input("Enter numbers separated by space: ").split()))
# find the minimum valuemin_value = min(numbers)
# print the minimum valueprint("The minimum value is:", min_value)
# Example 17: Inputting and Calculating Average# enter multiple integers separated by spacenumbers = list(map(int, input("Enter numbers separated by space: ").split()))
# calculate the averageaverage = sum(numbers) / len(numbers)
# print the averageprint("The average is:", average)
# Example 18: Inputting a List and Sorting It# enter multiple integers separated by spacenumbers = list(map(int, input("Enter numbers separated by space: ").split()))
# sort the numberssorted_numbers = sorted(numbers)
# print the sorted listprint("Sorted numbers:", sorted_numbers)
# Example 19: Inputting and Checking for Duplicates# enter multiple integers separated by spacenumbers = list(map(int, input("Enter numbers separated by space: ").split()))
# check for duplicateshas_duplicates = len(numbers) != len(set(numbers))
# print if duplicates existprint("Duplicates exist:", has_duplicates)
# Example 20: Inputting and Removing Duplicates# enter multiple integers separated by spacenumbers = list(map(int, input("Enter numbers separated by space: ").split()))
# remove duplicatesunique_numbers = list(set(numbers))
# print the unique listprint("Unique numbers:", unique_numbers)
# Example 21: Inputting and Counting Occurrences# enter a stringtext = input("Enter a string: ")
# input character to countchar = input("Enter character to count: ")
# count occurrencescount = text.count(char)
# print the countprint("The character '", char, "' appears", count, "times.")
# Example 22: Inputting and Replacing Characters in a String# enter a stringtext = input("Enter a string: ")
# enter character to replace and the new characterold_char = input("Enter character to replace: ")
new_char = input("Enter new character: ")
# replace charactersnew_text = text.replace(old_char, new_char)
# print the new stringprint("Modified string:", new_text)
# Example 23: Inputting and Checking String Length# enter a stringtext = input("Enter a string: ")
# check the length of the stringlength = len(text)
# print the lengthprint("The length of the string is:", length)
# Example 24: Inputting and Capitalizing a String# enter a stringtext = input("Enter a string: ")
# capitalize the stringcapitalized_text = text.capitalize()
# print the capitalized stringprint("Capitalized string:", capitalized_text)
# Example 25: Inputting and Reversing a String# enter a stringtext = input("Enter a string: ")
# reverse the stringreversed_text = text[::-1]
# print the reversed stringprint("Reversed string:", reversed_text)
Python Variables<>
# Example 1: Assign Value to Variable# assigning value to a variableage = 25
# print variableprint("Age:", age)
# Example 2: Assign-Reassign Variable# assigning valuex = 10
# reassigning new valuex = 20
# print variableprint("Updated x:", x)
# Example 3: Assign a String to a Variable# assigning a stringname = "John"
# print stringprint("Name:", name)
# Example 4: Assign a Float to a Variable# assigning a float valuepi = 3.14159
# print floatprint("Value of pi:", pi)
# Example 5: Assign Boolean to a Variable# assigning boolean valueis_active = True
# print booleanprint("Is Active:", is_active)
# Example 6: Assign None to a Variable# assigning Noneresult = None
# print Noneprint("Result:", result)
# Example 7: Assign Multiple Variables in One Line# assigning multiple variablesa, b, c = 1, 2, 3
# print variablesprint("a:", a, "b:", b, "c:", c)
# Example 8: Swap Two Variables# swapping variablesx, y = 5, 10
# swapping variablesx, y = y, x
# print swapped valuesprint("x:", x, "y:", y)
# Example 9: Assign a List to a Variable# assigning a listcolors = ["red", "green", "blue"]
# print listprint("Colors:", colors)
# Example 10: Assign a Tuple to a Variable# assigning a tupledimensions = (1920, 1080)
# print tupleprint("Dimensions:", dimensions)
# Example 11: Assign a Dictionary to a Variable# assigning a dictionaryperson = {"name": "Alice", "age": 30}
# print dictionaryprint("Person:", person)
# Example 12: Assign and Print Using Concatenation# assigning variablesname = "Bob"
age = 28
# print using concatenationprint(name + " is " + str(age) + " years old")
# Example 13: Assign a Boolean Expression Result# assigning a boolean expressionis_adult = age >= 18
# print resultprint("Is Adult:", is_adult)
# Example 14: Assign a Function Return Value# defining a functiondef greet(): return "Hello"
# assigning return valuemessage = greet()
# print messageprint(message)
# Example 15: Assign a Set to a Variable# assigning a setfruits = {"apple", "banana", "cherry"}
# print setprint("Fruits:", fruits)
# Example 16: Assign and Update a List# assigning a listnumbers = [1, 2, 3]
# update listnumbers.append(4)
# print updated listprint("Updated List:", numbers)
# Example 17: Assign and Check Type of Variable# assigning a valuevalue = 3.14
# print typeprint("Type:", type(value))
# Example 18: Assign Result of a Mathematical Expression# assigning resultresult = 5 + 3 * 2
# print resultprint("Result:", result)
# Example 19: Assign and Print a Variable Using Format Method# assigning a valuetemperature = 36.6
# print using format methodprint("Temperature: {}".format(temperature))
# Example 20: Assign a Variable and Perform In-Place Addition# assigning a valuecount = 10
# in-place additioncount += 5
# print updated valueprint("Count:", count)
# Example 21: Assign a Variable and Perform Floor Division# assigning a valuea = 17
b = 3
# floor divisionresult = a // b
# print resultprint("Result:", result)
# Example 22: Assign Variable with Power of Another Variable# assigning valuesbase = 2
exp = 3
# power calculationresult = base ** exp
# print resultprint(base, "^", exp, "=", result)
Test Your Skills:Variables<>
Python Operators<>
#Arithmetic Operators:Arithmetic operators in Python are used to perform basic mathematical operations on numerical values.These operators are essential for performing arithmetic calculations in Python. Here’s a breakdown of how each operator is used:
x = a + b # Adds two numbers
x = a - b # Subtracts two numbers
x = a * b # Multiplies two numbers
x = a / b # Divides two numbers
x = a % b # Remainder of division
x = a ** b # Power of a number
x = a // b # Floor division
#Assignment Operators:Assignment operators in Python are used to assign values to variables and to perform operations while assigning the result back to the same variable. They make code concise and improve readability when performing operations on variables.Here’s a breakdown of how each operator is used:
x = a # Assigns value
x += a # Adds and assigns
x -= a # Subtracts and assigns
x *= a # Multiplies and assigns
x /= a # Divides and assigns
x //= a # Floor divides and assigns
x %= a # Modulus and assigns
x **= a # Exponent and assigns
# Comparison Operators:Comparison operators in Python are used to compare two values or expressions. They evaluate to a boolean result, either True or False, and play a crucial role in programming for decision making:Here’s a breakdown of how each operator is used:
x == a # Equals
x != a # Not equal
x > a # Greater than
x < a # Less than
x >= a # Greater or equal
x <= a # Less or equal
# Logical Operators:Logical operators in Python are used to combine or modify boolean expressions, enabling more complex decision-making in your code.Here’s a breakdown of how each operator is used:
x = a and b # Logical AND
x = a or b # Logical OR
x = not a # Logical NOT
# Bitwise Operators:Bitwise operators in Python are used to perform operations on individual bits of integer values.Bitwise operations are often used in data encoding, compression algorithms, and cryptographic functions. They enable packing multiple values into a single integer, reducing memory usage. Here’s a breakdown of how each operator is used:
x = a & b # Bitwise AND
x = a | b # Bitwise OR
x = a ^ b # Bitwise XOR
x = ~a # Bitwise NOT
x = a << b # Left shift
x = a >> b # Right shift
# Membership Operators:Membership operators in Python are used to test for the presence of a value within a sequence (like lists, tuples, sets, or strings).Membership operators help validate whether a particular value exists in a collection, making it easy to ensure that data meets certain criteria before proceeding with operations.Here’s a breakdown of how each operator is used:
x = a in b # In sequence
x = a not in b # Not in sequence
# Identity Operators:Assignment operators in Python are used to assign values to variables and to perform operations while assigning the result back to the same variable. They make code concise and improve readability when performing operations on variables.Here’s a breakdown of how each operator is used:
x = a is b # Same object
x = a is not b # Different object
1: * Arithmetic Operators *
#Addition Operators:Example 1
a = 10 # Declare Integer Variable
result = a + 5 # Add Integer
print(result) # Print result
#Addition Operators:Example 2
a = 3.5 # Declare Float Variable
b = 2.2 # Declare Float Variable
result = a + b # Add Floats
print(result) # Print result
#Addition Operators:Example 3
x = "Hello" # Declare String Variable
y = " World" # Declare String Variable
result = x + y # Concatenate Strings
print(result) # Print result
#Addition Operators:Example 4
a = [1, 2, 3] # Declare List
b = [4, 5, 6] # Declare List
result = a + b # Concatenate Lists
print(result) # Print result
#Addition Operators:Example 5
a = (7, 8) # Declare Tuple
b = (9, 10) # Declare Tuple
result = a + b # Concatenate Tuples
print(result) # Print result
#Addition Operators:Example 6
num1 = 12 # Declare Integer
num2 = 5.5 # Declare Float
result = num1 + num2 # Add Integer and Float
print(result) # Print result
#Addition Operators:Example 7
a = 2.75 # Declare Float
b = 10 # Declare Integer
result = a + b # Add Float and Integer
print(result) # Print result
#Addition Operators:Example 8
name = "John" # Declare String Variable
age = 30 # Declare Integer
result = name + " is " + str(age) # Concatenate String and Integer
print(result) # Print result
#Addition Operators:Example 9
a = True # Declare Boolean Variable
b = 1 # Declare Integer
result = a + b # Add Boolean and Integer
print(result) # Print result (Boolean as Integer 1)
#Addition Operators:Example 10
a = 0b1010 # Declare Binary Number
b = 5 # Declare Integer
result = a + b # Add Binary and Integer
print(result) # Print result (Decimal)
#Addition Operators:Example 11
num1 = 0o12 # Declare Octal Number
num2 = 5 # Declare Integer
result = num1 + num2 # Add Octal and Integer
print(result) # Print result (Decimal)
#Addition Operators:Example 12
a = 0x1F # Declare Hexadecimal Number
b = 10 # Declare Integer
result = a + b # Add Hexadecimal and Integer
print(result) # Print result (Decimal)
#Addition Operators:Example 13
list1 = [10] * 3 # Repeat List Elements
result = sum(list1) # Sum List Elements
print(result) # Print result
#Addition Operators:Example 14
total = sum(range(1, 11)) # Sum of Range (1 to 10)
print(total) # Print result
#Addition Operators:Example 15
a = {1, 2} # Declare Set
b = {3, 4} # Declare Set
result = a.union(b) # Union of Sets (Addition of Elements)
print(result) # Print result
#Subtraction Operator:Example 1
a = 15 # Declare Integer
result = a - 5 # Subtract Integer
print(result) # Print result
#Subtraction Operator:Example 2
x = 12.5 # Declare Float
y = 2.5 # Declare Float
result = x - y # Subtract Floats
print(result) # Print result
#Subtraction Operator:Example 3
a = 100 # Declare Integer
result = a - 45 # Subtract Integer
print(result) # Print result
#Subtraction Operator:Example 4
a = 7.8 # Declare Float
b = 3.2 # Declare Float
result = a - b # Subtract Floats
print(result) # Print result
#Subtraction Operator:Example 5
a = 10 # Declare Integer
result = a - 0b101 # Subtract Binary
print(result) # Print result
#Subtraction Operator:Example 6
a = 0xFF # Declare Hexadecimal
b = 5 # Declare Integer
result = a - b # Subtract Hexadecimal
print(result) # Print result
#Subtraction Operator:Example 7
a = 1000 # Declare Integer
b = 200 # Declare Integer
result = a - b # Subtract Integers
print(result) # Print result
#Subtraction Operator:Example 8
a = 3.14159 # Declare Float
b = 1.14159 # Declare Float
result = a - b # Subtract Floats
print(result) # Print result
#Subtraction Operator:Example 9
list1 = [5, 3, 2] # Declare List
result = sum(list1) - 5 # Subtract from List Sum
print(result) # Print result
#Subtraction Operator:Example 10
a = 20 # Declare Integer
b = 5.5 # Declare Float
result = a - b # Subtract Integer from Float
print(result) # Print result
#Subtraction Operator:Example 11
a = 100 # Declare Integer
result = a - 50 - 25 # Multiple Subtraction
print(result) # Print result
#Subtraction Operator:Example 12
a = 0o12 # Declare Octal
b = 3 # Declare Integer
result = a - b # Subtract Octal and Integer
print(result) # Print result
#Subtraction Operator:Example 13
x = 100 # Declare Integer
y = 50 # Declare Integer
result = x - y # Subtract Integers
print(result) # Print result
#Subtraction Operator:Example 14
a = 15.75 # Declare Float
b = 5 # Declare Integer
result = a - b # Subtract Integer from Float
print(result) # Print result
#Subtraction Operator:Example 15
a = 2**4 # Declare Exponent
b = 10 # Declare Integer
result = a - b # Subtract Exponent Result
print(result) # Print result
#Multiplication Operator:Example 1
a = 7 # Declare Integer
result = a * 5 # Multiply by Integer
print(result) # Print result
#Multiplication Operator:Example 2
x = 3.5 # Declare Float
y = 2 # Declare Integer
result = x * y # Multiply Float and Integer
print(result) # Print result
#Multiplication Operator:Example 3
a = "Hello " # Declare String
result = a * 3 # Multiply String
print(result) # Print result
#Multiplication Operator:Example 4
list1 = [1, 2] # Declare List
result = list1 * 2 # Multiply List
print(result) # Print result
#Multiplication Operator:Example 5
a = 6.75 # Declare Float
b = 4 # Declare Integer
result = a * b # Multiply Float and Integer
print(result) # Print result
#Multiplication Operator:Example 6
a = 10 # Declare Integer
b = 0b101 # Declare Binary
result = a * b # Multiply Integer and Binary
print(result) # Print result
#Multiplication Operator:Example 7
a = 0xA # Declare Hexadecimal
b = 3 # Declare Integer
result = a * b # Multiply Hexadecimal and Integer
print(result) # Print result
#Multiplication Operator:Example 8
name = "John" # Declare String
result = name * 2 # Multiply String
print(result) # Print result
#Multiplication Operator:Example 9
x = 5.5 # Declare Float
y = 4.2 # Declare Float
result = x * y # Multiply Floats
print(result) # Print result
#Multiplication Operator:Example 10
a = 5 # Declare Integer
b = 4 # Declare Integer
result = a * b # Multiply Integers
print(result) # Print result
#Multiplication Operator:Example 11
a = 0o7 # Declare Octal
b = 5 # Declare Integer
result = a * b # Multiply Octal and Integer
print(result) # Print result
#Multiplication Operator:Example 12
a = 3**2 # Declare Exponent
b = 4 # Declare Integer
result = a * b # Multiply Exponent Result
print(result) # Print result
#Multiplication Operator:Example 13
a = 8 # Declare Integer
b = -2 # Declare Negative Integer
result = a * b # Multiply by Negative Integer
print(result) # Print result
#Multiplication Operator:Example 14
a = 4.5 # Declare Float
b = 2.5 # Declare Float
result = a * b # Multiply Floats
print(result) # Print result
#Multiplication Operator:Example 15
a = True # Declare Boolean
b = 5 # Declare Integer
result = a * b # Multiply Boolean and Integer
print(result) # Print result
#Division Operator:Example 1
a = 20 # Declare Integer
result = a / 5 # Division by Integer
print(result) # Print result
#Division Operator: Example 2 x = 15.5 # Declare Float y = 2.5 # Declare Float result = x / y # Divide Floats print(result) # Print result
#Division Operator: Example 3 a = 10 # Declare Integer result = a / 4 # Division by Integer print(result) # Print result
#Division Operator: Example 4 a = 50 # Declare Integer b = 2 # Declare Integer result = a / b # Divide Integers print(result) # Print result
#Division Operator: Example 5 x = 9 # Declare Integer result = x / 3 # Division by Integer print(result) # Print result
#Division Operator: Example 6 a = 8.0 # Declare Float b = 2 # Declare Integer result = a / b # Divide Float by Integer print(result) # Print result
#Division Operator: Example 7 x = 100 # Declare Integer y = 25 # Declare Integer result = x / y # Divide Integers print(result) # Print result
#Division Operator: Example 8 a = 0x10 # Declare Hexadecimal result = a / 4 # Divide Hexadecimal print(result) # Print result
#Division Operator: Example 9 x = 7.5 # Declare Float result = x / 3 # Division by Integer print(result) # Print result
#Division Operator: Example 10 a = 25 # Declare Integer result = a / 5 # Division by Integer print(result) # Print result
#Division Operator: Example 11 a = 0o16 # Declare Octal b = 2 # Declare Integer result = a / b # Divide Octal and Integer print(result) # Print result
#Division Operator: Example 12 a = 9**2 # Declare Exponent b = 9 # Declare Integer result = a / b # Divide Exponent Result print(result) # Print result
#Division Operator: Example 13 a = 16 # Declare Integer b = -4 # Declare Negative Integer result = a / b # Divide by Negative Integer print(result) # Print result
#Division Operator: Example 14 x = 81 # Declare Integer y = 9 # Declare Integer result = x / y # Divide Integers print(result) # Print result
#Division Operator: Example 15 a = 100 # Declare Integer result = a / True # Divide by Boolean print(result) # Print result
#Remainder Operator:Example 1
a = 10 # Declare Integer
result = a % 3 # Remainder after Division
print(result) # Print result
#Remainder Operator: Example 2 x = 25 # Declare Integer y = 4 # Declare Integer result = x % y # Remainder after Division print(result) # Print result
#Remainder Operator: Example 3 a = 100 # Declare Integer result = a % 6 # Remainder after Division print(result) # Print result
#Remainder Operator: Example 4 x = 50.5 # Declare Float y = 4.2 # Declare Float result = x % y # Remainder after Division print(result) # Print result
#Remainder Operator: Example 5 a = 0b1101 # Declare Binary result = a % 5 # Remainder with Binary print(result) # Print result
#Remainder Operator: Example 6 x = 13 # Declare Integer y = 3 # Declare Integer result = x % y # Remainder after Division print(result) # Print result
#Remainder Operator: Example 7 a = 144 # Declare Integer result = a % 12 # Remainder after Division print(result) # Print result
#Remainder Operator: Example 8 a = 7.5 # Declare Float result = a % 2 # Remainder with Float print(result) # Print result
#Remainder Operator: Example 9 x = 0xA # Declare Hexadecimal result = x % 4 # Remainder with Hexadecimal print(result) # Print result
#Remainder Operator: Example 10 a = 81 # Declare Integer result = a % 10 # Remainder after Division print(result) # Print result
#Remainder Operator: Example 11 a = 9**2 # Declare Exponent b = 10 # Declare Integer result = a % b # Remainder of Exponent Result print(result) # Print result
#Remainder Operator: Example 12 a = 0o17 # Declare Octal result = a % 3 # Remainder with Octal print(result) # Print result
#Remainder Operator: Example 13 x = 19 # Declare Integer y = -5 # Declare Negative Integer result = x % y # Remainder with Negative Integer print(result) # Print result
#Remainder Operator: Example 14 x = 27 # Declare Integer y = 8 # Declare Integer result = x % y # Remainder after Division print(result) # Print result
#Remainder Operator: Example 15 a = 10 # Declare Integer result = a % True # Remainder with Boolean print(result) # Print result
#PowerOfNumber: Example 1
a = 2 # Declare Integer
result = a ** 3 # Power of 2 to the power of 3
print(result) # Print result
#PowerOfNumber: Example 2
x = 5 # Declare Integer
y = 4 # Declare Integer
result = x ** y # Power of 5 to the power of 4
print(result) # Print result
#PowerOfNumber: Example 3
a = 10 # Declare Integer
result = a ** 2 # Square of 10
print(result) # Print result
#PowerOfNumber: Example 4
x = 3.5 # Declare Float
y = 2 # Declare Integer
result = x ** y # Power of Float to Integer
print(result) # Print result
#PowerOfNumber: Example 5
base = 6 # Declare Integer
exp = 3 # Declare Exponent
result = base ** exp # Power of base 6 raised to 3
print(result) # Print result
#Floor Division: Example 1
a = 17 # Declare Integer
result = a // 3 # Floor division of 17 by 3
print(result) # Print result
#Floor Division: Example 2
x = 28 # Declare Integer
y = 5 # Declare Integer
result = x // y # Floor division of 28 by 5
print(result) # Print result
#Floor Division: Example 3
a = 10.5 # Declare Float
result = a // 2 # Floor division of Float by Integer
print(result) # Print result
#Floor Division: Example 4
x = 50 # Declare Integer
y = 8 # Declare Integer
result = x // y # Floor division of 50 by 8
print(result) # Print result
#Floor Division: Example 5
base = 100 # Declare Integer
exp = 6 # Declare Integer
result = base // exp # Floor division of 100 by 6
print(result) # Print result
2: * Assignment Operators *
# Example 1: Assigns Value
a = 10 # Declare Integer Variable
x = a # Assigns value of 'a' to 'x'
print(x) # Print result
# Example 2: Adds and Assign
a = 10 # Declare Integer Variable
x = 5 # Assign value to 'x'
x += a # Adds 'a' to 'x' and assigns
print(x) # Print result
# Example 3: Subtracts and Assign
a = 10 # Declare Integer Variable
x = 20 # Assign value to 'x'
x -= a # Subtracts 'a' from 'x' and assigns
print(x) # Print result
# Example 4: Multiplies and Assign
a = 10 # Declare Integer Variable
x = 3 # Assign value to 'x'
x *= a # Multiplies 'x' by 'a' and assigns
print(x) # Print result
# Example 5: Divides and Assign
a = 10 # Declare Integer Variable
x = 50 # Assign value to 'x'
x /= a # Divides 'x' by 'a' and assigns
print(x) # Print result
# Example 6: Floor Divides and Assign
a = 10 # Declare Integer Variable
x = 55 # Assign value to 'x'
x //= a # Floor divides 'x' by 'a' and assigns
print(x) # Print result
# Example 7: Modulus and Assign
a = 10 # Declare Integer Variable
x = 37 # Assign value to 'x'
x %= a # Modulus 'x' by 'a' and assigns
print(x) # Print result
# Example 8: Exponent and Assign
a = 2 # Declare Integer Variable
x = 3 # Assign value to 'x'
x **= a # Raises 'x' to the power of 'a' and assigns
print(x) # Print result
3: * Comparison Operators: *
# Example 1: Equals
a = 10 # Declare Integer Variable
x = 10 # Assign value to 'x'
result = (x == a) # Check if 'x' equals 'a'
print(result) # Print result (True or False)
# Example 2: Not Equal
a = 10 # Declare Integer Variable
x = 5 # Assign value to 'x'
result = (x != a) # Check if 'x' is not equal to 'a'
print(result) # Print result (True or False)
# Example 3: Greater Than
a = 10 # Declare Integer Variable
x = 15 # Assign value to 'x'
result = (x > a) # Check if 'x' is greater than 'a'
print(result) # Print result (True or False)
# Example 4: Less Than
a = 10 # Declare Integer Variable
x = 5 # Assign value to 'x'
result = (x < a) # Check if 'x' is less than 'a'
print(result) # Print result (True or False)
# Example 5: Greater or Equal
a = 10 # Declare Integer Variable
x = 10 # Assign value to 'x'
result = (x >= a) # Check if 'x' is greater than or equal to 'a'
print(result) # Print result (True or False)
# Example 6: Less or Equal
a = 10 # Declare Integer Variable
x = 10 # Assign value to 'x'
result = (x <= a) # Check if 'x' is less than or equal to 'a'
print(result) # Print result (True or False)
4: * Logical Operators: *
# Example 1: Logical AND
a = True # Declare Boolean Variable
b = False # Declare Boolean Variable
x = a and b # Logical AND: True only if both 'a' and 'b' are True
print(x) # Print result (True or False)
# Example 2: Logical OR
a = True # Declare Boolean Variable
b = False # Declare Boolean Variable
x = a or b # Logical OR: True if either 'a' or 'b' is True
print(x) # Print result (True or False)
# Example 3: Logical NOT
a = True # Declare Boolean Variable
x = not a # Logical NOT: Inverts the truth value of 'a'
print(x) # Print result (True or False)
5: * Bitwise Operators: *
# Example 1: Bitwise AND
a = 10 # Declare Integer Variable (binary: 1010)
b = 4 # Declare Integer Variable (binary: 0100)
x = a & b # Bitwise AND: Performs AND operation between 'a' and 'b'
print(x) # Print result (2 - binary: 0010)
# Example 2: Bitwise OR
a = 10 # Declare Integer Variable (binary: 1010)
b = 4 # Declare Integer Variable (binary: 0100)
x = a | b # Bitwise OR: Performs OR operation between 'a' and 'b'
print(x) # Print result (14 - binary: 1110)
# Example 3: Bitwise XOR
a = 10 # Declare Integer Variable (binary: 1010)
b = 4 # Declare Integer Variable (binary: 0100)
x = a ^ b # Bitwise XOR: Performs XOR operation between 'a' and 'b'
print(x) # Print result (14 - binary: 1110)
# Example 4: Bitwise NOT
a = 10 # Declare Integer Variable (binary: 1010)
x = ~a # Bitwise NOT: Inverts bits of 'a'
print(x) # Print result (-11)
# Example 5: Left Shift
a = 10 # Declare Integer Variable (binary: 1010)
b = 2 # Declare Shift Amount
x = a << b # Left shift: Shifts bits of 'a' to the left by 'b'
print(x) # Print result (40 - binary: 101000)
# Example 6: Right Shift
a = 10 # Declare Integer Variable (binary: 1010)
b = 2 # Declare Shift Amount
x = a >> b # Right shift: Shifts bits of 'a' to the right by 'b'
print(x) # Print result (2 - binary: 10)
6: * Membership Operators: *
# Example 1: In Sequence
a = 3 # Declare Integer Variable
b = [1, 2, 3, 4, 5] # Declare List
x = a in b # Check if 'a' is in the list 'b'
print(x) # Print result (True or False)
# Example 2: Not In Sequence
a = 6 # Declare Integer Variable
b = [1, 2, 3, 4, 5] # Declare List
x = a not in b # Check if 'a' is not in the list 'b'
print(x) # Print result (True or False)
7: * Identity Operators: *
# Example 1: Same Object
a = [1, 2, 3] # Declare List
b = a # Assign 'b' to the same object as 'a'
x = a is b # Check if 'a' and 'b' refer to the same object
print(x) # Print result (True or False)
# Example 2: Different Object
a = [1, 2, 3] # Declare List
b = [1, 2, 3] # Declare another list with the same values
x = a is not b # Check if 'a' and 'b' refer to different objects
print(x) # Print result (True or False)
Test Your Skills:Operators<>
If-elif-else<>
# Example 1: If-Else Statement with Numbers# Variable num = 10
# check if the number is greater than 5 if num > 5:
# print if true print("The number is greater than 5")
# print if false else:
# print if false print("The number is not greater than 5")
# Example 2: If-Else Statement with Numbers# Variable num = 3
# check if the number is even if num % 2 == 0:
# print if true print("The number is even")
# print if false else:
# print if false print("The number is odd")
# Example 3: If-Else Statement with Strings# Variable text = "Hello"
# check if the string is empty if text == "":
# print if true print("The string is empty")
# print if false else:
# print if false print("The string is not empty")
# Example 4: If-Else Statement with Strings# Variable name = "Alice"
# check if the name is "Alice" if name == "Alice":
# print if true print("Hello, Alice!")
# print if false else:
# print if false print("Hello, Stranger!")
# Example 5: If-Else Statement with Lists# Variable fruits = ["apple", "banana", "cherry"]
# check if "apple" is in the list if "apple" in fruits:
# print if true print("Apple is in the list")
# print if false else:
# print if false print("Apple is not in the list")
# Example 6: If-Elif-Else Statement# Variable num = 7
# check the value of num if num > 10:
# print if true print("Greater than 10")
# check if num is 10 elif num == 10:
# print if true print("Equal to 10")
# print if false else:
# print if false print("Less than 10")
# Example 7: If-Elif-Else Statement with Strings# Variable color = "blue"
# check the color if color == "red":
# print if true print("Red color")
# check if color is blue elif color == "blue":
# print if true print("Blue color")
# print if false else:
# print if false print("Other color")
# Example 8: If-Else with a Boolean# Variable is_raining = True
# check if it is raining if is_raining:
# print if true print("Take an umbrella")
# print if false else:
# print if false print("No umbrella needed")
# Example 9: If-Else with Age Check# Variable age = 18
# check if the person is an adult if age >= 18:
# print if true print("You are an adult")
# print if false else:
# print if false print("You are not an adult")
# Example 10: If-Else with Nested Condition# Variable num = 15
# check if the number is positive if num > 0:
# check if number is even if num % 2 == 0:
# print if true print("Positive and Even")
# print if false else:
# print if false print("Positive and Odd")
# print if false else:
# print if false print("Non-positive number")
# Example 11: If-Elif-Else with Grades# Variable grade = 85
# check the grade if grade >= 90:
# print if true print("A grade")
# check if grade is between 80 and 89 elif grade >= 80:
# print if true print("B grade")
# print if false else:
# print if false print("C grade")
# Example 12: If-Else with a List Check# Variable fruits = ["apple", "banana", "cherry"]
# check if "orange" is in the list if "orange" in fruits:
# print if true print("Orange is in the list")
# print if false else:
# print if false print("Orange is not in the list")
# Example 13: If-Else with a String Length# Variable message = "Hello World"
# check if the message length is greater than 10 if len(message) > 10:
# print if true print("Message is too long")
# print if false else:
# print if false print("Message is just right")
# Example 14: If-Else with Multiple Conditions# Variable temperature = 25
# check if the temperature is between 20 and 30 if 20 <= temperature <= 30:
# print if true print("The weather is warm")
# print if false else:
# print if false print("The weather is not warm")
# Example 15: If-Else with User Input# Variable user_input = int(input("Enter a number: "))
# check if the number is greater than 10 if user_input > 10:
# print if true print("The number is greater than 10")
# print if false else:
# print if false print("The number is less than or equal to 10")
# Example 16: If-Else with Boolean Expression# Variable is_adult = False
# check if the person is an adult if is_adult:
# print if true print("You are an adult")
# print if false else:
# print if false print("You are not an adult")
# Example 17: If-Else with Time Check# Variable hour = 15
# check if it is day or night if 6 <= hour < 18:
# print if true print("Good day!")
# print if false else:
# print if false print("Good evening!")
# Example 18: If-Else with Number Range# Variable number = 50
# check if number is within a certain range if 0 <= number <= 100:
# print if true print("The number is in range")
# print if false else:
# print if false print("The number is out of range")
# Example 19: If-Elif-Else with Days of the Week# Variable day = "Monday"
# check the day of the week if day == "Monday":
# print if true print("Start of the week")
# check if day is Wednesday elif day == "Wednesday":
# print if true print("Midweek")
# print if false else:
# print if false print("Another day")
# Example 20: If-Else with Tuple# Variable person = ("Alice", 25)
# check the name in the tuple if person[0] == "Alice":
# print if true print("Hello Alice!")
# print if false else:
# print if false print("Who are you?")
# Example 21: If-Elif-Else with Multiple Variables# Variable x, y = 3, 5
# check x and y values if x == 3 and y == 5:
# print if true print("x is 3 and y is 5")
# check if x is 3 and y is 6 elif x == 3 and y == 6:
# print if true print("x is 3 and y is 6")
# print if false else:
# print if false print("Other combination")
# Example 22: If-Else with Type Check# Variable value = 10.5
# check the type of value if isinstance(value, int):
# print if true print("It's an integer")
# print if false else:
# print if false print("It's not an integer")
# Example 23: If-Else with a Dictionary Check# Variable student = {"name": "John", "age": 20}
# check if the student has a name if "name" in student:
# print if true print("Student name is", student["name"])
# print if false else:
# print if false print("Student name is not available")
# Example 24: If-Else with Logical Operators# Variable age = 25
# check if age is between 18 and 30 if 18 <= age <= 30:
# print if true print("Age is in the range 18 to 30")
# print if false else:
# print if false print("Age is outside the range")
# Example 25: If-Else with Comparison Operator# Variable number = 100
# check if the number is greater than 50 if number > 50:
# print if true print("Greater than 50")
# print if false else:
# print if false print("Less than or equal to 50")
# Example 26: If-Else with a List Length# Variable numbers = [1, 2, 3]
# check if the list is empty if len(numbers) == 0:
# print if true print("The list is empty")
# print if false else:
# print if false print("The list is not empty")
# Example 27: If-Elif-Else with Range Check# Variable temperature = 15
# check temperature range if temperature < 10:
# print if true print("Cold weather")
# check if temperature is between 10 and 20 elif 10 <= temperature <= 20:
# print if true print("Mild weather")
# print if false else:
# print if false print("Hot weather")
# Example 28: If-Else with Float Check# Variable number = 3.14
# check if the number is a float if isinstance(number, float):
# print if true print("The number is a float")
# print if false else:
# print if false print("The number is not a float")
Test Your Skills:if-elif-else<>
Iteration and Loops<>
# Example 1: Simple For Loop# Variable numbers = [1, 2, 3, 4, 5]
# iterate through the list for num in numbers:
# print each number print(num)
# Example 2: For Loop with Range# Variable n = 5
# iterate from 0 to 4 for i in range(n):
# print each iteration index print(i)
# Example 3: For Loop with Step# Variable n = 10
# iterate with a step of 2 for i in range(0, n, 2):
# print each step print(i)
# Example 4: If-Else inside For Loop# Variable numbers = [1, 2, 3, 4, 5]
# iterate through the list for num in numbers:
# check if the number is even if num % 2 == 0:
# print if even print(f"{num} is even")
# print if odd else:
# print if odd print(f"{num} is odd")
# Example 5: For Loop with Nested Loops# Variable matrix = [[1, 2], [3, 4], [5, 6]]
# iterate through rows for row in matrix:
# iterate through columns for col in row:
# print each element print(col)
# Example 6: While Loop# Variable count = 0
# run until count is less than 5 while count < 5:
# print count print(count)
# increment count count += 1
# Example 7: While Loop with Break# Variable count = 0
# run until count reaches 3 while count < 5:
# check if count is 3 if count == 3:
# break out of the loop break
# print count print(count)
# increment count count += 1
# Example 8: While Loop with Continue# Variable count = 0
# run until count is less than 5 while count < 5:
# skip count 2 if count == 2:
# continue to the next iteration continue
# print count print(count)
# increment count count += 1
# Example 9: For Loop with List Comprehension# Variable numbers = [1, 2, 3, 4, 5]
# create a new list with squared numbers squares = [num**2 for num in numbers]
# print the list of squares print(squares)
# Example 10: For Loop with Dictionary Iteration# Variable data = {"a": 1, "b": 2, "c": 3}
# iterate through dictionary keys and values for key, value in data.items():
# print key and value print(f"{key}: {value}")
# Example 11: For Loop with Index# Variable names = ["Alice", "Bob", "Charlie"]
# iterate with index for index, name in enumerate(names):
# print index and name print(f"Index {index}: {name}")
# Example 12: Nested While Loop# Variable rows = 3
# variable for while loop while rows > 0:
# print the row print("Row", rows)
# decrement rows rows -= 1
# Example 13: For Loop with Else# Variable numbers = [1, 2, 3, 4, 5]
# iterate through numbers for num in numbers:
# check if number is even if num % 2 == 0:
# print if even print(f"{num} is even")
# execute when loop finishes without break else:
# print else message print(f"{num} is odd")
# Example 14: While Loop with Else# Variable count = 0
# loop until count reaches 5 while count < 5:
# print count print(count)
# increment count count += 1
# execute after the while loop ends else:
# print when while loop is finished print("Finished counting!")
# Example 15: Infinite While Loop# Variable count = 0
# infinite loop while True:
# print the count print(count)
# break after 5 iterations if count == 5:
# break the loop break
# increment count count += 1
# Example 16: For Loop with Multiple Conditions# Variable numbers = [1, 2, 3, 4, 5, 6]
# iterate through numbers for num in numbers:
# check if even and divisible by 3 if num % 2 == 0 and num % 3 == 0:
# print if true print(f"{num} is divisible by both 2 and 3")
# Example 17: For Loop with Continue# Variable numbers = [1, 2, 3, 4, 5]
# iterate through numbers for num in numbers:
# skip 3 if num == 3:
# continue with next iteration continue
# print number print(num)
# Example 18: For Loop with Reverse# Variable numbers = [1, 2, 3, 4, 5]
# iterate in reverse order for num in reversed(numbers):
# print number print(num)
# Example 19: List Comprehension with If# Variable numbers = [1, 2, 3, 4, 5, 6]
# create a new list of even numbers evens = [num for num in numbers if num % 2 == 0]
# print list of even numbers print(evens)
# Example 20: For Loop with String# Variable text = "Python"
# iterate through characters in the string for char in text:
# print each character print(char)
# Example 21: Nested For Loop with Range# Variable n = 3
# outer loop for i in range(n):
# inner loop for j in range(n):
# print coordinates print(f"({i},{j})")
# Example 22: For Loop with Tuple Unpacking# Variable pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
# unpack tuple into two variables for num, char in pairs:
# print each pair print(f"{num}: {char}")
# Example 23: While Loop with Counter# Variable counter = 0
# while loop until counter reaches 5 while counter < 5:
# print counter print(counter)
# increment counter counter += 1
# Example 24: For Loop with a Set# Variable items = {1, 2, 3, 4, 5}
# iterate through set for item in items:
# print each item print(item)
# Example 25: For Loop with Dictionary Keys# Variable data = {"name": "Alice", "age": 25, "city": "Wonderland"}
# iterate through dictionary keys for key in data:
# print each key print(key)
# Example 26: While Loop with Flag# Variable found = False
# while loop to check if flag is set while not found:
# check condition if some_condition:
# set flag found = True
# Example 27: For Loop with Sorted List# Variable numbers = [3, 1, 4, 5, 2]
# iterate through sorted list for num in sorted(numbers):
# print each number print(num)
# Example 28: For Loop with Multiple Lists# Variable list1 = [1, 2, 3]
# Variable list2 = ['a', 'b', 'c']
# iterate through both lists for num, char in zip(list1, list2):
# print number and character print(f"{num}: {char}")
# Example 29: Break Out of Nested Loop# Variable matrix = [[1, 2], [3, 4], [5, 6]]
# iterate through rows for row in matrix:
# iterate through columns for num in row:
# break when number equals 4 if num == 4:
# break both loops break
# Example 30: Loop with Try-Except# Variable numbers = [1, 'a', 2, 'b', 3]
# iterate through the list for num in numbers:
# try to square the number try:
# print square print(num ** 2)
# handle exception if not a number except TypeError:
# print error message print(f"{num} is not a number")
# Example 31: Basic While Loop# Variable counter = 1
# while loop that prints numbers from 1 to 5 while counter <= 5:
# print counter value print(counter)
# increment counter counter += 1
# Example 32: While Loop with Break# Variable counter = 1
# while loop with break condition while counter <= 5:
# check if counter is 3 to break loop if counter == 3:
# break the loop break
# print counter value print(counter)
# increment counter counter += 1
# Example 33: While Loop with Else# Variable counter = 1
# while loop that ends normally while counter <= 5:
# print counter value print(counter)
# increment counter counter += 1
# else executed after loop finishes else:
# print when loop ends print("Loop finished")
# Example 34: While Loop with Continue# Variable counter = 1
# while loop with continue condition while counter <= 5:
# skip printing when counter is 3 if counter == 3:
# increment counter and continue counter += 1
# continue loop without printing continue
# print counter value print(counter)
# increment counter counter += 1
# Example 35: Infinite While Loop# Variable counter = 1
# infinite while loop until counter exceeds 10 while True:
# print counter value print(counter)
# increment counter counter += 1
# break loop after counter exceeds 10 if counter > 10:
# break the loop break
# Example 36: While Loop with User Input# Variable user_input = ""
# while loop until 'stop' is entered while user_input != "stop":
# prompt for user input user_input = input("Enter 'stop' to stop the loop: ")
# print the input print(f"You entered: {user_input}")
# Example 37: While Loop for Summation# Variable total = 0
# prompt user for input num = int(input("Enter a number (0 to stop): "))
# while loop until 0 is entered while num != 0:
# add to total total += num
# prompt again num = int(input("Enter a number (0 to stop): "))
# print the total sum print(f"Total sum: {total}")
# Example 38: While Loop with a List# Variable my_list = [1, 2, 3, 4, 5]
# Variable index = 0
# while loop to iterate through list while index < len(my_list):
# print list element print(my_list[index])
# increment index index += 1
# Example 39: Nested While Loop# Variable row = 1
# while loop for rows while row <= 3:
# Variable col = 1
# nested while loop for columns while col <= 3:
# print product of row and col print(row * col, end=" ")
# increment column col += 1
# new line after each row print()
# increment row row += 1
# Example 40: While Loop with a Flag# Variable flag = True
# Variable counter = 1
# while loop with flag condition while flag:
# print counter value print(counter)
# increment counter counter += 1
# change flag condition if counter > 5:
# set flag to False flag = False
Test Your Skills:Iteration and Loops<>
Python Functions<>
# Example 1: Simple Function# Define a functiondef greet():
# Function Statement print("Hello, World!")
# Call a functiongreet()
# Example 2: Function with Parameters# Define a function with parametersdef greet(name):
# Function Statement print("Hello, " + name + "!")
# Call a functiongreet("Alice")
# Example 3: Function with Return Value# Define a function with a return valuedef add(a, b):
# Function Statement return a + b
# Call a functionresult = add(5, 3)
# Print resultprint(result)
# Example 4: Function with Default Argument# Define a function with default argumentdef greet(name="Guest"):
# Function Statement print("Hello, " + name + "!")
# Call a functiongreet()
# Call a function with argumentgreet("Bob")
# Example 5: Function with Variable Number of Arguments# Define a function with variable argumentsdef print_numbers(*args):
# Function Statement for num in args:
# Function Statement print(num)
# Call a functionprint_numbers(1, 2, 3, 4, 5)
# Example 6: Function with Keyword Arguments# Define a function with keyword argumentsdef display_info(name, age):
# Function Statement print("Name: " + name + ", Age: " + str(age))
# Call a function with keyword argumentsdisplay_info(name="Alice", age=30)
# Example 7: Function with Arbitrary Keyword Arguments# Define a function with arbitrary keyword argumentsdef display_details(**kwargs):
# Function Statement for key, value in kwargs.items():
# Function Statement print(key + ": " + str(value))
# Call a function with arbitrary keyword argumentsdisplay_details(name="John", age=25, city="New York")
# Example 8: Recursive Function# Define a recursive functiondef factorial(n):
# Function Statement if n == 1:
# Function Statement return 1
# Function Statement else:
# Function Statement return n * factorial(n-1)
# Call a functionprint(factorial(5))
# Example 9: Lambda Function# Define a lambda functionadd = lambda a, b: a + b
# Call the lambda functionprint(add(2, 3))
# Example 10: Function with Multiple Return Values# Define a function with multiple return valuesdef divide(a, b):
# Function Statement return a // b, a % b
# Call a function and store multiple return valuesquotient, remainder = divide(10, 3)
# Print resultprint("Quotient: " + str(quotient) + ", Remainder: " + str(remainder))
# Example 11: Function to Check Even or Odd# Define a function to check even or odddef check_even_odd(number):
# Function Statement if number % 2 == 0:
# Function Statement print(str(number) + " is even")
# Function Statement else:
# Function Statement print(str(number) + " is odd")
# Call a functioncheck_even_odd(4)
# Example 12: Function with String Argument# Define a function with string argumentdef string_length(s):
# Function Statement return len(s)
# Call a functionprint(string_length("Hello"))
# Example 13: Function to Find Maximum of Two Numbers# Define a function to find the maximumdef max_of_two(a, b):
# Function Statement if a > b:
# Function Statement return a
# Function Statement else:
# Function Statement return b
# Call a functionprint(max_of_two(4, 7))
# Example 14: Function to Check Palindrome# Define a function to check palindromedef is_palindrome(s):
# Function Statement return s == s[::-1]
# Call a functionprint(is_palindrome("racecar"))
# Example 15: Function to Count Vowels# Define a function to count vowelsdef count_vowels(s):
# Function Statement vowels = "aeiou"
# Function Statement count = 0
# Function Statement for char in s:
# Function Statement if char.lower() in vowels:
# Function Statement count += 1
# Function Statement return count
# Call a functionprint(count_vowels("hello"))
# Example 16: Function to Reverse a String# Define a function to reverse a stringdef reverse_string(s):
# Function Statement return s[::-1]
# Call a functionprint(reverse_string("hello"))
# Example 17: Function to Calculate Factorial# Define a function to calculate factorialdef factorial(n):
# Function Statement if n == 0:
# Function Statement return 1
# Function Statement else:
# Function Statement return n * factorial(n - 1)
# Call a functionprint(factorial(5))
# Example 18: Function to Count Words in a Sentence# Define a function to count wordsdef count_words(sentence):
# Function Statement return len(sentence.split())
# Call a functionprint(count_words("Hello world, this is Python"))
# Example 19: Function to Check Prime Number# Define a function to check prime numberdef is_prime(n):
# Function Statement if n <= 1:
# Function Statement return False
# Function Statement for i in range(2, int(n ** 0.5) + 1):
# Function Statement if n % i == 0:
# Function Statement return False
# Function Statement return True
# Call a functionprint(is_prime(11))
# Example 20: Function to Convert Celsius to Fahrenheit# Define a function to convert Celsius to Fahrenheitdef celsius_to_fahrenheit(celsius):
# Function Statement return (celsius * 9/5) + 32
# Call a functionprint(celsius_to_fahrenheit(0))
# Example 21: Function to Sum List Elements# Define a function to sum elements in a listdef sum_list(lst):
# Function Statement return sum(lst)
# Call a functionprint(sum_list([1, 2, 3, 4, 5]))
# Example 22: Function to Sort List# Define a function to sort a listdef sort_list(lst):
# Function Statement return sorted(lst)
# Call a functionprint(sort_list([5, 2, 8, 1, 4]))
# Example 23: Function to Find GCD of Two Numbers# Define a function to find GCDdef gcd(a, b):
# Function Statement while b:
# Function Statement a, b = b, a % b
# Function Statement return a
# Call a functionprint(gcd(56, 98))
# Example 24: Function to Find LCM of Two Numbers# Define a function to find LCMdef lcm(a, b):
# Function Statement return abs(a*b) // gcd(a, b)
# Call a functionprint(lcm(4, 5))
# Example 25: Function to Convert Fahrenheit to Celsius# Define a function to convert Fahrenheit to Celsiusdef fahrenheit_to_celsius(fahrenheit):
# Function Statement return (fahrenheit - 32) * 5/9
# Call a functionprint(fahrenheit_to_celsius(32))
# Example 26: Function to Find Square Root# Define a function to find square rootimport math
# Function Statement def square_root(n):
# Function Statement return math.sqrt(n)
# Call a functionprint(square_root(16))
# Example 27: Function to Return Unique Elements from List# Define a function to get unique elementsdef unique_elements(lst):
# Function Statement return list(set(lst))
# Call a functionprint(unique_elements([1, 2, 2, 3, 4, 4]))
# Example 28: Function to Reverse List# Define a function to reverse a listdef reverse_list(lst):
# Function Statement return lst[::-1]
# Call a functionprint(reverse_list([1, 2, 3]))
# Example 29: Function to Count Occurrences of an Item in List# Define a function to count occurrencesdef count_occurrences(lst, item):
# Function Statement return lst.count(item)
# Call a functionprint(count_occurrences([1, 2, 2, 3], 2))
# Example 30: Function to Find Intersection of Two Lists# Define a function to find intersectiondef intersection(lst1, lst2):
# Function Statement return list(set(lst1) & set(lst2))
# Call a functionprint(intersection([1, 2, 3], [2, 3, 4]))
Test Your Skills:Python Functions<>
Python Lists<>
# Example 1: Creating a List# create a simple listmy_list = [1, 2, 3, 4, 5]
# print the listprint(my_list)
# Example 2: Accessing List Elements# create a listmy_list = ['apple', 'banana', 'cherry']
# access the second elementprint(my_list[1])
# Example 3: Adding an Element to a List# create a listmy_list = [1, 2, 3]
# add an element to the listmy_list.append(4)
# print the updated listprint(my_list)
# Example 4: Inserting an Element at a Specific Position# create a listmy_list = [1, 2, 4, 5]
# insert an element at the second positionmy_list.insert(1, 3)
# print the updated listprint(my_list)
# Example 5: Removing an Element from a List# create a listmy_list = [1, 2, 3, 4]
# remove the element '3'my_list.remove(3)
# print the updated listprint(my_list)
# Example 6: Popping an Element from a List# create a listmy_list = [1, 2, 3, 4]
# pop the last elementpopped_item = my_list.pop()
# print the popped item and the updated listprint(popped_item, my_list)
# Example 7: Slicing a List# create a listmy_list = [1, 2, 3, 4, 5]
# slice the first three elementsprint(my_list[:3])
# Example 8: Length of a List# create a listmy_list = [10, 20, 30, 40]
# print the length of the listprint(len(my_list))
# Example 9: List Concatenation# create two listslist1 = [1, 2, 3]
# concatenate the listslist2 = list1 + [4, 5, 6]
# print the concatenated listprint(list2)
# Example 10: List Repetition# create a listmy_list = [1, 2]
# repeat the list 3 timesprint(my_list * 3)
# Example 11: List Comprehension# create a list with comprehensionmy_list = [x**2 for x in range(1, 6)]
# print the listprint(my_list)
# Example 12: Checking if an Element Exists in a List# create a listmy_list = [1, 2, 3, 4, 5]
# check if '3' exists in the listprint(3 in my_list)
# Example 13: Iterating Through a List# create a listmy_list = ['apple', 'banana', 'cherry']
# iterate through the listfor item in my_list:
# print each item print(item)
# Example 14: Nested Lists# create a nested listmy_list = [[1, 2], [3, 4], [5, 6]]
# access the first element of the second listprint(my_list[1][0])
# Example 15: List of Lists and Iteration# create a list of listsmy_list = [[1, 2], [3, 4], [5, 6]]
# iterate through the list of listsfor sublist in my_list:
# iterate through each sublist for item in sublist:
# print each item print(item)
# Example 16: Sorting a List# create a listmy_list = [3, 1, 4, 5, 2]
# sort the listmy_list.sort()
# print the sorted listprint(my_list)
# Example 17: Reversing a List# create a listmy_list = [1, 2, 3, 4, 5]
# reverse the listmy_list.reverse()
# print the reversed listprint(my_list)
# Example 18: Removing an Element by Index# create a listmy_list = [1, 2, 3, 4, 5]
# remove the element at index 2my_list.pop(2)
# print the updated listprint(my_list)
# Example 19: List with Mixed Data Types# create a list with mixed data typesmy_list = [1, 'apple', 3.14, True]
# print the listprint(my_list)
# Example 20: Concatenating Two Lists# create two listslist1 = [1, 2, 3]
# concatenate the two listslist2 = list1 + [4, 5, 6]
# print the concatenated listprint(list2)
# Example 21: Checking List Length# create a listmy_list = [1, 2, 3, 4]
# check the length of the listprint(len(my_list))
# Example 22: List with Nested Loops# create a listmy_list = [[1, 2], [3, 4], [5, 6]]
# iterate through the listfor sublist in my_list:
# iterate through each sublist for item in sublist:
# print each item print(item)
# Example 23: List Comprehension with Condition# create a list with even numbersmy_list = [x for x in range(10) if x % 2 == 0]
# print the listprint(my_list)
# Example 24: List with Duplicate Elements# create a list with duplicatesmy_list = [1, 2, 2, 3, 4, 4]
# print the list with duplicatesprint(my_list)
# Example 25: List with Range Function# create a list using range functionmy_list = list(range(1, 6))
# print the listprint(my_list)
# Example 26: Find Maximum Value in a List# create a listmy_list = [1, 3, 7, 2, 5]
# find the maximum valueprint(max(my_list))
# Example 27: List Slicing with Negative Indices# create a listmy_list = [1, 2, 3, 4, 5]
# slice the last three elementsprint(my_list[-3:])
# Example 28: List of Dictionaries# create a list of dictionariesmy_list = [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Charlie'}]
# print the listprint(my_list)
# Example 29: List with Different Data Types# create a list with different data typesmy_list = [1, 'apple', 3.14, [1, 2, 3], True]
# print the listprint(my_list)
# Example 30: List Unpacking# create a listmy_list = [1, 2, 3]
# unpack the lista, b, c = my_list
# print the unpacked elementsprint(a, b, c)
Test Your Skills:Python Lists<>
Python Dictionary<>
# Example 1: Creating a Dictionary# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# print the dictionaryprint(my_dict)
# Example 2: Accessing Dictionary Values# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# access the value of 'name'print(my_dict['name'])
# Example 3: Adding a Key-Value Pair to a Dictionary# create a dictionarymy_dict = {'name': 'Alice'}
# add a new key-value pairmy_dict['age'] = 25
# print the updated dictionaryprint(my_dict)
# Example 4: Removing a Key-Value Pair from a Dictionary# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# remove the key 'age'my_dict.pop('age')
# print the updated dictionaryprint(my_dict)
# Example 5: Using the get() Method# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# get the value of 'age'print(my_dict.get('age'))
# Example 6: Checking if a Key Exists# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# check if 'name' existsprint('name' in my_dict)
# Example 7: Iterating Through a Dictionary# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# iterate through the dictionaryfor key, value in my_dict.items():
# print each key and value print(key, value)
# Example 8: Merging Two Dictionaries# create two dictionariesdict1 = {'name': 'Alice'}
# merge with another dictionarydict2 = {'age': 25}
# update dict1 with dict2dict1.update(dict2)
# print the merged dictionaryprint(dict1)
# Example 9: Dictionary with Multiple Data Types# create a dictionary with different data typesmy_dict = {'name': 'Alice', 'age': 25, 'is_student': True}
# print the dictionaryprint(my_dict)
# Example 10: Dictionary with Nested Dictionaries# create a nested dictionarymy_dict = {'person1': {'name': 'Alice', 'age': 25}, 'person2': {'name': 'Bob', 'age': 30}}
# print the nested dictionaryprint(my_dict)
# Example 11: Dictionary with List as Values# create a dictionary with lists as valuesmy_dict = {'fruits': ['apple', 'banana'], 'vegetables': ['carrot', 'spinach']}
# print the dictionaryprint(my_dict)
# Example 12: Using setdefault() Method# create a dictionarymy_dict = {'name': 'Alice'}
# use setdefault to add a key-value pair if key does not existmy_dict.setdefault('age', 25)
# print the updated dictionaryprint(my_dict)
# Example 13: Copying a Dictionary# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# make a shallow copy of the dictionarynew_dict = my_dict.copy()
# print the copied dictionaryprint(new_dict)
# Example 14: Dictionary with Tuple as Key# create a dictionary with tuple keysmy_dict = {('name', 'age'): 'Alice'}
# print the dictionaryprint(my_dict)
# Example 15: Dictionary Comprehension# create a dictionary using comprehensionmy_dict = {x: x**2 for x in range(5)}
# print the dictionaryprint(my_dict)
# Example 16: Dictionary with Boolean Values# create a dictionary with boolean valuesmy_dict = {'is_active': True, 'is_verified': False}
# print the dictionaryprint(my_dict)
# Example 17: Dictionary with Mixed Key Types# create a dictionary with mixed key typesmy_dict = {1: 'one', 'two': 2, (3, 4): 'three_four'}
# print the dictionaryprint(my_dict)
# Example 18: Using popitem() Method# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# pop a key-value pairkey_value = my_dict.popitem()
# print the popped item and the updated dictionaryprint(key_value, my_dict)
# Example 19: Getting All Keys of a Dictionary# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# get all the keysprint(my_dict.keys())
# Example 20: Getting All Values of a Dictionary# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# get all the valuesprint(my_dict.values())
# Example 21: Using the fromkeys() Method# create a dictionary with fromkeyskeys = ['name', 'age']
# assign a default valuemy_dict = dict.fromkeys(keys, 'Unknown')
# print the dictionaryprint(my_dict)
# Example 22: Dictionary with None as Value# create a dictionary with None as valuemy_dict = {'name': None, 'age': 25}
# print the dictionaryprint(my_dict)
# Example 23: Nested Dictionary Update# create a nested dictionarymy_dict = {'person1': {'name': 'Alice', 'age': 25}}
# update a nested key-value pairmy_dict['person1']['age'] = 26
# print the updated dictionaryprint(my_dict)
# Example 24: Dictionary with Set as Value# create a dictionary with sets as valuesmy_dict = {'fruits': {'apple', 'banana'}, 'vegetables': {'carrot', 'spinach'}}
# print the dictionaryprint(my_dict)
# Example 25: Dictionary with Conditional Update# create a dictionarymy_dict = {'name': 'Alice', 'age': 25}
# update 'age' conditionallyif my_dict.get('age') < 30: my_dict['status'] = 'young'
# print the updated dictionaryprint(my_dict)
# Example 26: Dictionary with List as a Key# create a dictionary with list as key (not allowed)my_dict = {['name', 'age']: 'Alice'}
# print the dictionary (will cause an error)print(my_dict)
# Example 27: Dictionary with Integer as Key# create a dictionary with integer keysmy_dict = {1: 'one', 2: 'two'}
# print the dictionaryprint(my_dict)
# Example 28: Dictionary Merge Using `|` Operator (Python 3.9+)# create two dictionariesdict1 = {'name': 'Alice'}
# merge using `|` operatordict2 = {'age': 25}
# merged dictionarymerged_dict = dict1 | dict2
# print the merged dictionaryprint(merged_dict)
# Example 29: Dictionary with Function as Value# create a dictionary with functions as valuesmy_dict = {'greet': lambda name: f"Hello {name}"}
# call the function stored in the dictionaryprint(my_dict['greet']('Alice'))
# Example 30: Dictionary with Boolean Operations# create a dictionary with boolean operationsmy_dict = {'is_raining': False, 'is_sunny': True}
# check if both conditions are trueprint(my_dict['is_raining'] and my_dict['is_sunny'])
Test Your Skills:Python Dictionaries<>
Python Sets<>
# Example 1: Creating a Set# create a setmy_set = {1, 2, 3, 4}
# print the setprint(my_set)
# Example 2: Adding an Element to a Set# create a setmy_set = {1, 2, 3}
# add an element to the setmy_set.add(4)
# print the updated setprint(my_set)
# Example 3: Removing an Element from a Set# create a setmy_set = {1, 2, 3, 4}
# remove an element from the setmy_set.remove(3)
# print the updated setprint(my_set)
# Example 4: Using discard() to Remove an Element# create a setmy_set = {1, 2, 3, 4}
# discard an elementmy_set.discard(2)
# print the updated setprint(my_set)
# Example 5: Clearing a Set# create a setmy_set = {1, 2, 3}
# clear all elements from the setmy_set.clear()
# print the empty setprint(my_set)
# Example 6: Set Union# create two setsset1 = {1, 2, 3}
# union of two setsset2 = {3, 4, 5}
# combine both setsunion_set = set1 | set2
# print the unionprint(union_set)
# Example 7: Set Intersection# create two setsset1 = {1, 2, 3}
# intersection of two setsset2 = {3, 4, 5}
# get common elementsintersection_set = set1 & set2
# print the intersectionprint(intersection_set)
# Example 8: Set Difference# create two setsset1 = {1, 2, 3}
# difference between two setsset2 = {3, 4, 5}
# elements in set1 but not in set2difference_set = set1 - set2
# print the differenceprint(difference_set)
# Example 9: Set Symmetric Difference# create two setsset1 = {1, 2, 3}
# symmetric difference between two setsset2 = {3, 4, 5}
# elements in set1 or set2, but not in bothsymmetric_difference_set = set1 ^ set2
# print the symmetric differenceprint(symmetric_difference_set)
# Example 10: Checking if a Set is Subset of Another# create two setsset1 = {1, 2}
# check if set1 is a subset of set2set2 = {1, 2, 3, 4}
# print if set1 is a subset of set2print(set1.issubset(set2))
# Example 11: Checking if a Set is Superset of Another# create two setsset1 = {1, 2, 3, 4}
# check if set1 is a superset of set2set2 = {1, 2}
# print if set1 is a superset of set2print(set1.issuperset(set2))
# Example 12: Checking if a Set is Disjoint with Another# create two setsset1 = {1, 2, 3}
# check if set1 and set2 have no common elementsset2 = {4, 5, 6}
# print if sets are disjointprint(set1.isdisjoint(set2))
# Example 13: Set Length# create a setmy_set = {1, 2, 3, 4}
# get the length of the setprint(len(my_set))
# Example 14: Set Copy# create a setmy_set = {1, 2, 3, 4}
# copy the setnew_set = my_set.copy()
# print the copied setprint(new_set)
# Example 15: Frozen Set# create a frozen set (immutable set)frozen_set = frozenset([1, 2, 3])
# print the frozen setprint(frozen_set)
# Example 16: Set with Multiple Data Types# create a set with mixed data typesmy_set = {1, 'apple', 3.14}
# print the setprint(my_set)
# Example 17: Set Comprehension# create a set using comprehensionmy_set = {x**2 for x in range(5)}
# print the setprint(my_set)
# Example 18: Checking for an Element in a Set# create a setmy_set = {1, 2, 3, 4}
# check if 3 is in the setprint(3 in my_set)
# Example 19: Set Intersection with Another Set# create two setsset1 = {1, 2, 3}
# find common elements between two setsset2 = {3, 4, 5}
# intersection of two setsprint(set1.intersection(set2))
# Example 20: Using Set Operations with Multiple Sets# create three setsset1 = {1, 2, 3}
# perform union on three setsset2 = {3, 4, 5}
# union of three setsset3 = {5, 6, 7}
# result of unionprint(set1 | set2 | set3)
Test Your Skills:Python-Sets<>
Python Classes & Objects<>
# Example 1: Creating a Simple Class# Define a classclass Person:
# Define a constructor def __init__(self, name, age):
# Initialize instance variables self.name = name
# Initialize instance variables self.age = age
# Create an object of the classperson1 = Person("John", 25)
# Print object propertiesprint(person1.name, person1.age)
# Example 2: Creating and Accessing Methods in a Class# Define a classclass Car:
# Define a constructor def __init__(self, make, model):
# Initialize instance variables self.make = make
# Initialize instance variables self.model = model
# Define a method def display_info(self):
# Print car information print(f"{self.make} {self.model}")
# Create an object of the classcar1 = Car("Toyota", "Corolla")
# Call method on the objectcar1.display_info()
# Example 3: Modifying Instance Variables# Define a classclass Student:
# Define a constructor def __init__(self, name, grade):
# Initialize instance variables self.name = name
# Initialize instance variables self.grade = grade
# Define a method to change grade def update_grade(self, new_grade):
# Modify the grade self.grade = new_grade
# Create an object of the classstudent1 = Student("Alice", "B")
# Print original gradeprint(student1.grade)
# Update gradestudent1.update_grade("A")
# Print updated gradeprint(student1.grade)
# Example 4: Inheritance in Python# Define a base classclass Animal:
# Define a constructor def __init__(self, name):
# Initialize instance variable self.name = name
# Define a method def speak(self):
# Print sound print(f"{self.name} makes a sound")
# Define a derived classclass Dog(Animal):
# Override method def speak(self):
# Print sound print(f"{self.name} barks")
# Create an object of the derived classdog1 = Dog("Rex")
# Call overridden methoddog1.speak()
# Example 5: Multiple Inheritance# Define first base classclass Father:
# Define a method def speak(self):
# Print speech print("I am the father")
# Define second base classclass Mother:
# Define a method def walk(self):
# Print action print("I am the mother")
# Define derived classclass Child(Father, Mother):
# Define a method def play(self):
# Print action print("I am the child")
# Create an object of the derived classchild1 = Child()
# Call methods from base classeschild1.speak()
# Call method from second base classchild1.walk()
# Call method from derived classchild1.play()
# Example 6: Encapsulation in Python# Define a classclass BankAccount:
# Define a constructor def __init__(self, balance):
# Initialize instance variable self.__balance = balance
# Define a method to access balance def get_balance(self):
# Return the balance return self.__balance
# Define a method to deposit money def deposit(self, amount):
# Increase the balance self.__balance += amount
# Create an object of the classaccount = BankAccount(1000)
# Call methods on the objectprint(account.get_balance())
# Deposit money into accountaccount.deposit(500)
# Print updated balanceprint(account.get_balance())
# Example 7: Accessing Class Variables# Define a classclass Car:
# Define a constructor def __init__(self, brand, year):
# Initialize class variables self.brand = brand
# Initialize class variables self.year = year
# Create an object of the classcar1 = Car("Ford", 2020)
# Access class variablesprint(car1.brand, car1.year)
# Example 8: Creating a Class with a Method# Define a classclass Dog:
# Define a constructor def __init__(self, name, breed):
# Initialize instance variables self.name = name
# Initialize instance variables self.breed = breed
# Define a method def bark(self):
# Print a message print(f"{self.name} says woof!")
# Create an object of the classdog1 = Dog("Buddy", "Golden Retriever")
# Call the methoddog1.bark()
# Example 9: Updating Object Attributes# Define a classclass Person:
# Define a constructor def __init__(self, name, age):
# Initialize instance variables self.name = name
# Initialize instance variables self.age = age
# Define a method to update age def update_age(self, new_age):
# Update the age attribute self.age = new_age
# Create an object of the classperson1 = Person("John", 30)
# Update object attributeperson1.update_age(31)
# Print updated attributeprint(person1.age)
# Example 10: Using a Class Variable# Define a classclass Counter:
# Define a class variable count = 0
# Define a method def increment(cls):
# Increment the class variable cls.count += 1
# Create an object of the classcounter1 = Counter()
# Increment the countcounter1.increment()
# Print class variableprint(Counter.count)
# Example 11: Simple Inheritance Example# Define a parent classclass Animal:
# Define a method def speak(self):
# Print a message print("Animal makes a sound")
# Define a child classclass Dog(Animal):
# Override parent method def speak(self):
# Print a dog-specific message print("Dog barks")
# Create an object of the child classdog = Dog()
# Call overridden methoddog.speak()
# Example 12: Using Super in Inheritance# Define a parent classclass Animal:
# Define a constructor def __init__(self, name):
# Initialize instance variable self.name = name
# Define a method def speak(self):
# Print a message print(f"{self.name} makes a sound")
# Define a child classclass Dog(Animal):
# Override the constructor def __init__(self, name, breed):
# Initialize parent constructor super().__init__(name)
# Initialize child instance variable self.breed = breed
# Create an object of the child classdog = Dog("Rex", "Bulldog")
# Call parent methoddog.speak()
# Example 13: Method Overriding in Inheritance# Define a parent classclass Animal:
# Define a method def make_sound(self):
# Print message print("Animal sound")
# Define a child classclass Dog(Animal):
# Override method def make_sound(self):
# Print dog sound print("Bark")
# Create an object of the child classdog = Dog()
# Call overridden methoddog.make_sound()
# Example 14: Class with a Class Method# Define a classclass Vehicle:
# Define a class method @classmethod
# Define a method def info(cls):
# Print vehicle info print("This is a vehicle")
# Call class methodVehicle.info()
# Example 15: Class with a Static Method# Define a classclass MathOperations:
# Define a static method @staticmethod
# Define a method def add(x, y):
# Add two numbers return x + y
# Call static methodprint(MathOperations.add(5, 3))
# Example 16: Creating an Object of a Subclass# Define a parent classclass Animal:
# Define a method def make_sound(self):
# Print message print("Animal sound")
# Define a subclassclass Dog(Animal):
# Override method def make_sound(self):
# Print dog sound print("Woof")
# Create an object of the subclassdog = Dog()
# Call method from subclassdog.make_sound()
Test Your Skills:Python-Classes and Objects<>
Python Math Module<>
# Example 1: Using math.sqrt to Find the Square Root# Import math moduleimport math
# Find the square root of a numberprint(math.sqrt(16))
# Example 2: Using math.pow to Calculate Powers# Import math moduleimport math
# Calculate 2 raised to the power of 3print(math.pow(2, 3))
# Example 3: Using math.pi to Get the Value of Pi# Import math moduleimport math
# Print the value of Piprint(math.pi)
# Example 4: Using math.e for Euler's Number# Import math moduleimport math
# Print the value of Euler's number (e)print(math.e)
# Example 5: Using math.factorial to Find Factorial of a Number# Import math moduleimport math
# Find the factorial of 5print(math.factorial(5))
# Example 6: Using math.sin to Calculate the Sine of an Angle# Import math moduleimport math
# Calculate the sine of a 45-degree angle (converted to radians)print(math.sin(math.radians(45)))
# Example 7: Using math.cos to Calculate the Cosine of an Angle# Import math moduleimport math
# Calculate the cosine of a 45-degree angle (converted to radians)print(math.cos(math.radians(45)))
# Example 8: Using math.tan to Calculate the Tangent of an Angle# Import math moduleimport math
# Calculate the tangent of a 45-degree angle (converted to radians)print(math.tan(math.radians(45)))
# Example 9: Using math.ceil to Round Up to the Nearest Integer# Import math moduleimport math
# Round 4.2 up to the nearest integerprint(math.ceil(4.2))
# Example 10: Using math.floor to Round Down to the Nearest Integer# Import math moduleimport math
# Round 4.7 down to the nearest integerprint(math.floor(4.7))
Python Turtles<>
# Example 1: Drawing a Square# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(4):
# Move Forward t.forward(100)
# Move Left t.left(90)
# Example 2: Drawing a Triangle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(3):
# Move Forward t.forward(100)
# Move Left t.left(120)
# Example 3: Drawing a Circle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# Draw a circlet.circle(100)
# Example 4: Drawing a Rectangle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(2):
# Move Forward t.forward(150)
# Move Left t.left(90)
# Move Forward t.forward(100)
# Move Left t.left(90)
# Example 5: Drawing an Equilateral Triangle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(3):
# Move Forward t.forward(100)
# Move Left t.left(120)
# Example 6: Drawing a Star# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(3)
# for loopfor _ in range(5):
# Move Forward t.forward(100)
# Move Right t.right(144)
# Example 7: Animated Square# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(3)
# for loopfor i in range(4):
# Move Forward t.forward(100 + i*10)
# Move Left t.left(90)
# Example 8: Animated Triangle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(3)
# for loopfor i in range(3):
# Move Forward t.forward(100 + i*20)
# Move Left t.left(120)
# Example 9: Animated Circle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(3)
# for loopfor i in range(10):
# Draw Circle t.circle(50 + i*5)
# Example 10: Drawing a Hexagon# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(6):
# Move Forward t.forward(100)
# Move Left t.left(60)
# Example 11: Drawing an Octagon# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(8):
# Move Forward t.forward(100)
# Move Left t.left(45)
# Example 12: Drawing a Polygon with 10 sides# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# for loopfor _ in range(10):
# Move Forward t.forward(50)
# Move Left t.left(36)
# Example 13: Filling Shapes with Color# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(1)
# Begin filling colort.begin_fill()
# for loopfor _ in range(4):
# Move Forward t.forward(100)
# Move Left t.left(90)
# End filling colort.end_fill()
# Example 14: Animated Colored Circle# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(3)
# for loopfor i in range(36):
# Draw Circle t.circle(50 + i*5)
# Change Color t.pencolor(i/36, i/36, 1-i/36)
# Turn Turtle t.left(10)
# Example 15: Animated Square with Color Change# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(3)
# for loopfor i in range(4):
# Move Forward t.forward(100 + i*10)
# Change Color t.pencolor(i/4, 0, 1-i/4)
# Move Left t.left(90)
# Example 16: Drawing a Spiral# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(10)
# for loopfor i in range(50):
# Move Forward t.forward(i*10)
# Move Left t.left(90)
# Example 17: Drawing a Spirograph# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(10)
# for loopfor _ in range(36):
# Draw Circle t.circle(100)
# Turn Turtle t.left(10)
# Example 18: Drawing a Flower Pattern# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(10)
# for loopfor _ in range(36):
# Draw Circle t.circle(100)
# Turn Turtle t.left(10)
# Example 19: Draw a Spiral Square# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(10)
# for loopfor i in range(50):
# Move Forward t.forward(i*10)
# Move Left t.left(90)
# Example 20: Drawing a Spirograph# Import turtle moduleimport turtle
# Create turtle objectt = turtle.Turtle()
# Set turtle speedt.speed(10)
# for loopfor _ in range(36):
# Draw Circle t.circle(100)
# Turn Turtle t.left(10)
| Course Editors | Youssef Yasser Kusibati | Abdulrahman Mohammed A Aljohani|
OOP<>
Your download's being scanned. We'll let you know if there's an issue.