- Python Program to Print Hello world!
- Python Program to Add Two Numbers
- Python Program to Find the Square Root
- Python Program to Calculate the Area of a Triangle
- Python Program to Solve Quadratic Equation
- Python Program to Swap Two Variables
- Python Program to Generate a Random Number
- Python Program to Convert Kilometers to Miles
- Python Program to Convert Celsius To Fahrenheit
- Python Program to Check if a Number is Positive, Negative or 0
- Python Program to Check if a Number is Odd or Even
- Python Program to Check Leap Year
- Python Program to Find the Largest Among Three Numbers
- Python Program to Check Prime Number
- Python Program to Print all Prime Numbers in an Interval
- Python Program to Find the Factorial of a Number
- Python Program to Display the multiplication Table
- Python Program to Print the Fibonacci sequence
- Python Program to Check Armstrong Number
- Python Program to Find Armstrong Number in an Interval
- Python Program to Find the Sum of Natural Numbers
- Python Program to Display Powers of 2 Using Anonymous Function
- Python Program to Find Numbers Divisible by Another Number
- Python Program to Convert Decimal to Binary, Octal and Hexadecimal
- Python Program to Find ASCII Value of Character
- Python Program to Find HCF or GCD
- Python Program to Find LCM
- Python Program to Find the Factors of a Number
- Python Program to Make a Simple Calculator
- Python Program to Shuffle Deck of Cards
- Python Program to Display Calendar
- Python Program to Display Fibonacci Sequence Using Recursion
- Python Program to Find Sum of Natural Numbers Using Recursion
- Python Program to Find Factorial of Number Using Recursion
- Python Program to Convert Decimal to Binary Using Recursion
- Python Program to Add Two Matrices
- Python Program to Transpose a Matrix
- Python Program to Multiply Two Matrices
- Python Program to Check Whether a String is Palindrome or Not
- Python Program to Remove Punctuations From a String
- Python Program to Sort Words in Alphabetic Order
- Python Program to Illustrate Different Set Operations
- Python Program to Count the Number of Each Vowel
- Python Program to Merge Mails
- Python Program to Find the Size (Resolution) of a Image
- Python Program to Find Hash of File
- Python Program to Create Pyramid Patterns
- Python Program to Merge Two Dictionaries
- Python Program to Safely Create a Nested Directory
- Python Program to Access Index of a List Using for Loop
- Python Program to Flatten a Nested List
- Python Program to Slice Lists
- Python Program to Iterate Over Dictionaries Using for Loop
- Python Program to Sort a Dictionary by Value
- Python Program to Check If a List is Empty
- Python Program to Catch Multiple Exceptions in One Line
- Python Program to Copy a File
- Python Program to Concatenate Two Lists
- Python Program to Check if a Key is Already Present in a Dictionary
- Python Program to Split a List Into Evenly Sized Chunks
- Python Program to Parse a String to a Float or Int
- Python Program to Print Colored Text to the Terminal
- Python Program to Convert String to Datetime
- Python Program to Get the Last Element of the List
- Python Program to Get a Substring of a String
- Python Program to Print Output Without a Newline
- Python Program Read a File Line by Line Into a List
- Python Program to Randomly Select an Element From the List
- Python Program to Check If a String Is a Number (Float)
- Python Program to Count the Occurrence of an Item in a List
- Python Program to Append to a File
- Python Program to Delete an Element From a Dictionary
- Python Program to Create a Long Multiline String
- Python Program to Extract Extension From the File Name
- Python Program to Measure the Elapsed Time in Python
- Python Program to Get the Class Name of an Instance
- Python Program to Convert Two Lists Into a Dictionary
- Python Program to Differentiate Between type() and isinstance()
- Python Program to Trim Whitespace From a String
- Python Program to Get the File Name From the File Path
- Python Program to Represent enum
- Python Program to Return Multiple Values From a Function
- Python Program to Get Line Count of a File
- Python Program to Find All File with .txt Extension Present Inside a Directory
- Python Program to Get File Creation and Modification Date
- Python Program to Get the Full Path of the Current Working Directory
- Python Program to Iterate Through Two Lists in Parallel
- Python Program to Check the File Size
- Python Program to Reverse a Number
- Python Program to Compute the Power of a Number
- Python Program to Count the Number of Digits Present In a Number
- Python Program to Check If Two Strings are Anagram
- Python Program to Capitalize the First Character of a String
- Python Program to Compute all the Permutation of the String
- Python Program to Create a Countdown Timer
- Python Program to Count the Number of Occurrence of a Character in String
- Python Program to Remove Duplicate Element From a List
- Python Program to Convert Bytes to a String
Sunday 9 July 2023
Wednesday 28 June 2023
Eid-ul-Adha Mubarak wish using Python
Python Coding June 28, 2023 Python No comments
Saturday 24 June 2023
Python libraries commonly used in oceanographic research
Python Coding June 24, 2023 Python No comments
Python libraries commonly used in oceanographic research:
NumPy and SciPy: These libraries provide powerful numerical and scientific computing capabilities, including array manipulation, linear algebra, optimization, and signal processing.
Pandas: Pandas is a library used for data manipulation and analysis. It provides data structures and functions for efficient handling and processing of structured data, such as time series or oceanographic datasets.
Matplotlib and Seaborn: These libraries are used for data visualization in Python. Matplotlib provides a wide range of plotting functions, while Seaborn offers a high-level interface for creating attractive statistical graphics.
Cartopy: Cartopy is a library for geospatial data processing and mapping. It allows you to create maps, plot geographical data, and perform geospatial transformations.
Xarray and NetCDF4: These libraries are commonly used for handling and analyzing multidimensional gridded data, such as ocean model outputs or satellite observations. They provide efficient I/O operations, metadata handling, and mathematical operations on multidimensional arrays.
Ocean Data View (ODV): ODV is a popular software tool for oceanographic data visualization and analysis. While not a Python library, it can be integrated with Python using the PyODV package, allowing you to import, analyze, and plot ODV data files.
Thursday 22 June 2023
Free Python Notes for Interview
Python Coding June 22, 2023 Python No comments
Wednesday 21 June 2023
10 Python terms that beginners tend to confuse
Python Coding June 21, 2023 Python No comments
Variable vs. Value: Beginners often confuse variables and values in Python. A variable is a name used to store a value, while a value is the actual data stored in the variable. For example, in the statement x = 5, x is the variable, and 5 is the value assigned to it.
List vs. Tuple: Beginners may struggle with understanding the differences between lists and tuples in Python. A list is a mutable sequence of elements enclosed in square brackets ([]), while a tuple is an immutable sequence enclosed in parentheses (()). This means that you can modify a list by adding, removing, or changing elements, but you cannot do the same with a tuple once it is created.
Function vs. Method: Beginners sometimes confuse functions and methods. A function is a block of reusable code that performs a specific task, while a method is a function that belongs to an object and is called using the dot notation (object.method()). Functions can be called independently, whereas methods are invoked on specific objects.
Syntax Error vs. Runtime Error: Beginners often mix up syntax errors and runtime errors. A syntax error occurs when the code violates the language's grammar rules and prevents it from being compiled or interpreted correctly. On the other hand, a runtime error occurs when the code is syntactically correct, but an error is encountered while the program is running.
Index vs. Slice: Understanding the difference between indexing and slicing can be confusing for beginners. Indexing refers to accessing a specific element in a sequence, such as a string or a list, by specifying its position using square brackets ([]). Slicing, on the other hand, allows you to extract a portion of a sequence by specifying a range of indices using the colon (:) notation.
Mutable vs. Immutable: Beginners may struggle with grasping the concept of mutable and immutable objects in Python. Mutable objects can be modified after they are created, while immutable objects cannot. For example, lists are mutable, so you can change their elements, whereas strings are immutable, so you cannot modify their characters once they are created.
Importing Modules vs. Installing Packages: Beginners sometimes confuse importing modules and installing packages. Importing a module allows you to use its predefined functions, classes, or variables in your code by using the import statement. On the other hand, installing a package refers to downloading and setting up additional libraries or modules that are not included in the Python standard library, usually using package managers like pip.
Syntax vs. Semantics: Beginners may have difficulty understanding the distinction between syntax and semantics. Syntax refers to the rules and structure of a programming language, including the correct placement of punctuation, keywords, and symbols. Semantics, on the other hand, relates to the meaning and interpretation of the code. Syntax errors occur when the code violates the language's syntax rules, while semantic errors occur when the code produces unexpected or incorrect results due to logical or conceptual mistakes.
Class vs. Object: Beginners often struggle with the concepts of classes and objects in object-oriented programming. A class is a blueprint or template that defines the structure and behavior of objects, while an object is an instance of a class. In simpler terms, a class can be thought of as a blueprint for creating multiple objects with similar characteristics and behaviors.
Global vs. Local Variables: Understanding the scope of variables can be confusing for beginners. Global variables are defined outside of any function or class and can be accessed from any part of the program. Local variables, on the other hand, are defined within a function or a block of code and can only be accessed within that specific function or block. Beginners may encounter issues when they unintentionally create variables with the same name in different scopes, leading to unexpected behavior or errors.
Sunday 18 June 2023
Data Analytics Course Handwritten Notes
Author June 18, 2023 Pandas, Python No comments
Friday 26 May 2023
Python Interview Questions | Fresher| Senior Developer | Technical Lead
Python Coding May 26, 2023 Python No comments
Python interview questions that are commonly asked to freshers:
- What is Python? Mention some key features of Python.
- What are the differences between Python 2 and Python 3?
- How do you install third-party packages in Python?
- Explain the concept of Python virtual environments.
- What are the different data types available in Python?
- Explain the difference between a list and a tuple in Python.
- How do you handle exceptions in Python? Provide an example.
- What is the purpose of the __init__ method in a Python class?
- How do you open and read a file in Python?
- What is the difference between append() and extend() methods in Python lists?
- Explain the concept of a generator in Python. How is it different from a regular function?
- What is the difference between shallow copy and deep copy in Python?
- How do you define a lambda function in Python? Provide an example.
- Explain the concept of decorators in Python. Provide an example.
- What is the difference between __str__ and __repr__ methods in Python?
- How can you remove duplicate elements from a list in Python?
- Explain the difference between a module and a package in Python.
- How do you perform unit testing in Python?
- Explain the concept of list comprehensions in Python. Provide an example.
- How do you handle file handling errors in Python?
- What is a decorator in Python? How do you use decorators?
- Explain the Global Interpreter Lock (GIL) in Python. How does it impact multi-threading?
- What are the different ways to achieve concurrency in Python?
- Explain the concept of metaclasses in Python. Provide an example.
- How do you handle memory management in Python?
- What are some common design patterns used in Python?
- Explain the concept of context managers in Python. Provide an example.
- What are some differences between a function and a method in Python?
- How do you handle large datasets in Python? Are there any libraries that can help?
- Explain the concept of closures in Python. Provide an example.
- How do you optimize the performance of a Python application?
- What is the purpose of the __slots__ attribute in a Python class?
- Explain the difference between shallow copy and deep copy in Python. When would you use each?
- How do you handle circular imports in Python?
- What are some best practices for writing clean and maintainable Python code?
- Explain the concept of generators and iterators in Python. Provide an example.
- What are some differences between the is and == operators in Python?
- How do you work with databases in Python? Are there any ORM libraries you are familiar with?
- Explain the concept of method resolution order (MRO) in Python.
- How do you handle and raise custom exceptions in Python?
Python interview questions that are commonly asked to technical leads:
As a technical lead, how do you ensure code quality and enforce coding standards in a Python project?
- Explain the concept of Python decorators. How can they be used to enhance code functionality or provide cross-cutting concerns?
- What strategies or methodologies do you follow for effective project planning and task estimation?
- How do you handle technical debt and code refactoring in a Python project?
- Describe your experience with optimizing Python code for performance. What techniques or tools have you used?
- How do you approach architectural design and system scalability in a Python application?
- Explain your experience with integrating Python applications with external systems or APIs.
- How do you ensure the security of a Python application, including handling sensitive data and preventing common vulnerabilities?
- Describe your experience with handling and resolving production issues in Python applications.
- How do you lead a development team and promote collaboration and knowledge sharing?
- Describe a situation where you faced a technical challenge or roadblock in a Python project and how you resolved it.
- Explain your experience with working in Agile or other software development methodologies.
- How do you ensure effective communication and collaboration between technical and non-technical stakeholders in a project?
- What tools or techniques do you use for automated testing and continuous integration in Python projects?
- Describe your experience with cloud platforms and deploying Python applications in a cloud environment.
- How do you ensure the maintainability and extensibility of a Python codebase as it evolves over time?
- Explain your approach to code reviews and how you provide constructive feedback to team members.
- Describe a situation where you had to make a technology or architectural decision for a Python project and the factors you considered.
- How do you mentor and guide junior developers to enhance their skills and contribute effectively to a Python project?
- What are some best practices for managing technical documentation and knowledge sharing in a Python project?
- What is a decorator in Python? How do you use decorators?
- Explain the Global Interpreter Lock (GIL) in Python. How does it impact multi-threading?
- What are the different ways to achieve concurrency in Python?
- Explain the concept of metaclasses in Python. Provide an example.
- How do you handle memory management in Python?
- What are some common design patterns used in Python?
- Explain the concept of context managers in Python. Provide an example.
- What are some differences between a function and a method in Python?
- How do you handle large datasets in Python? Are there any libraries that can help?
- Explain the concept of closures in Python. Provide an example.
- How do you optimize the performance of a Python application?
- What is the purpose of the __slots__ attribute in a Python class?
- Explain the difference between shallow copy and deep copy in Python. When would you use each?
- How do you handle circular imports in Python?
- What are some best practices for writing clean and maintainable Python code?
- Explain the concept of generators and iterators in Python. Provide an example.
- What are some differences between the is and == operators in Python?
- How do you work with databases in Python? Are there any ORM libraries you are familiar with?
- Explain the concept of method resolution order (MRO) in Python.
- How do you handle and raise custom exceptions in Python?
Python interview questions that are commonly asked to technical leads:
As a technical lead, how do you ensure code quality and enforce coding standards in a Python project?
- Explain the concept of Python decorators. How can they be used to enhance code functionality or provide cross-cutting concerns?
- What strategies or methodologies do you follow for effective project planning and task estimation?
- How do you handle technical debt and code refactoring in a Python project?
- Describe your experience with optimizing Python code for performance. What techniques or tools have you used?
- How do you approach architectural design and system scalability in a Python application?
- Explain your experience with integrating Python applications with external systems or APIs.
- How do you ensure the security of a Python application, including handling sensitive data and preventing common vulnerabilities?
- Describe your experience with handling and resolving production issues in Python applications.
- How do you lead a development team and promote collaboration and knowledge sharing?
- Describe a situation where you faced a technical challenge or roadblock in a Python project and how you resolved it.
- Explain your experience with working in Agile or other software development methodologies.
- How do you ensure effective communication and collaboration between technical and non-technical stakeholders in a project?
- What tools or techniques do you use for automated testing and continuous integration in Python projects?
- Describe your experience with cloud platforms and deploying Python applications in a cloud environment.
- How do you ensure the maintainability and extensibility of a Python codebase as it evolves over time?
- Explain your approach to code reviews and how you provide constructive feedback to team members.
- Describe a situation where you had to make a technology or architectural decision for a Python project and the factors you considered.
- How do you mentor and guide junior developers to enhance their skills and contribute effectively to a Python project?
- What are some best practices for managing technical documentation and knowledge sharing in a Python project?
As a technical lead, how do you ensure code quality and enforce coding standards in a Python project?
- Explain the concept of Python decorators. How can they be used to enhance code functionality or provide cross-cutting concerns?
- What strategies or methodologies do you follow for effective project planning and task estimation?
- How do you handle technical debt and code refactoring in a Python project?
- Describe your experience with optimizing Python code for performance. What techniques or tools have you used?
- How do you approach architectural design and system scalability in a Python application?
- Explain your experience with integrating Python applications with external systems or APIs.
- How do you ensure the security of a Python application, including handling sensitive data and preventing common vulnerabilities?
- Describe your experience with handling and resolving production issues in Python applications.
- How do you lead a development team and promote collaboration and knowledge sharing?
- Describe a situation where you faced a technical challenge or roadblock in a Python project and how you resolved it.
- Explain your experience with working in Agile or other software development methodologies.
- How do you ensure effective communication and collaboration between technical and non-technical stakeholders in a project?
- What tools or techniques do you use for automated testing and continuous integration in Python projects?
- Describe your experience with cloud platforms and deploying Python applications in a cloud environment.
- How do you ensure the maintainability and extensibility of a Python codebase as it evolves over time?
- Explain your approach to code reviews and how you provide constructive feedback to team members.
- Describe a situation where you had to make a technology or architectural decision for a Python project and the factors you considered.
- How do you mentor and guide junior developers to enhance their skills and contribute effectively to a Python project?
- What are some best practices for managing technical documentation and knowledge sharing in a Python project?
Saturday 20 May 2023
Future of Python Programming
Python Coding May 20, 2023 Python No comments
The future of Python programming looks bright and promising. Python has been steadily growing in popularity over the years and has become one of the most widely used programming languages across various domains. Here are some key aspects that shape the future of Python programming:
Continued Growth: Python's popularity is expected to continue growing as more developers and organizations recognize its simplicity, readability, and versatility. It has a vast ecosystem of libraries and frameworks that make it suitable for a wide range of applications.
Data Science and Machine Learning: Python has become the go-to language for data science and machine learning. Popular libraries like NumPy, Pandas, and scikit-learn have established Python as a powerful tool for data analysis, modeling, and machine learning. With the growing demand for data-driven insights and AI solutions, Python's role in these fields is expected to expand further.
Web Development: Python's web development frameworks, such as Django and Flask, have gained significant traction in recent years. Python's simplicity and ease of use make it an attractive choice for web development projects. As web applications continue to evolve and grow in complexity, Python is likely to remain a preferred language for web development.
Artificial Intelligence and Automation: Python is heavily used in artificial intelligence (AI) and automation. Libraries like TensorFlow and PyTorch are widely adopted for building and deploying AI models. Python's flexibility and ease of integration with other technologies make it well-suited for AI-related tasks.
DevOps and Infrastructure: Python's role in DevOps and infrastructure automation is also expected to increase. Tools like Ansible, Fabric, and SaltStack leverage Python for automation and configuration management. Python's scripting capabilities and extensive library support make it a valuable language in the DevOps domain.
Education and Beginner-Friendly Nature: Python's simplicity and readability make it an excellent choice for teaching programming to beginners. Many educational institutions and coding bootcamps have adopted Python as their primary teaching language. This trend is likely to continue, fostering a growing community of Python developers.
Performance Improvements: Python's performance has been a topic of discussion, particularly in high-performance computing and real-time applications. Efforts like PyPy, Numba, and Cython have been made to optimize Python's execution speed. As these optimizations progress, Python's performance is expected to improve further.
Community and Ecosystem: Python has a vibrant and active community, contributing to its growth and development. The Python Package Index (PyPI) hosts an extensive collection of open-source libraries, enabling developers to easily leverage existing code and accelerate their development process. The community's continuous contributions and collaborations are likely to drive Python's progress.
Overall, Python's future seems promising, driven by its versatility, simplicity, and strong ecosystem. It will continue to be a popular choice for a wide range of applications, from web development and data science to AI and automation. As technology advances and new trends emerge, Python is expected to adapt and remain a relevant and influential language in the programming landscape.
Wednesday 17 May 2023
What is the output of the following snippet, and why?
Python Coding May 17, 2023 Python, Python Coding Challenge No comments
What is the output of the following snippet, and why?
Code:
x,x,y = 0,3,6
print(x,y)
Solution:
Saturday 13 May 2023
Friday 12 May 2023
100 Days Python Loop Challenge
Python Coding May 12, 2023 Python No comments
100 Days Python Loop Challenge
The 100 Days of Code Python Loop Challenge is a coding challenge designed to help you improve your coding skills by coding every day for 100 days. The challenge focuses on loops in Python, which are a fundamental building block of many programs.
The challenge involves writing code every day for 100 days, with each day building on the previous day's work. The challenge provides you with a set of tasks to complete each day, with the aim of helping you to gradually build up your skills and knowledge of loops in Python.
The challenge is designed to be flexible, so you can start it at any time and work at your own pace. You can also choose to work on the challenge for more or less than 100 days, depending on your schedule and availability.
To participate in the challenge, you can join the 100 Days of Code community, which provides support and resources for participants. You can also use the #100DaysOfCode hashtag on social media to connect with other participants and share your progress.
If you are interested in improving your coding skills and learning more about loops in Python, the 100 Days of Code Python Loop Challenge is a great way to get started.
Thursday 11 May 2023
Monday 8 May 2023
Difference between class and function in Python
Python Coding May 08, 2023 Python No comments
In Python, classes and functions are two fundamental programming constructs, each with its own unique purpose and characteristics.
Functions are blocks of code that take input, perform operations on that input, and then return an output. Functions can be defined and called within a program, making it possible to reuse code and simplify the development process. Functions are also useful for encapsulating logic and making code more modular, as well as improving code readability.
Classes, on the other hand, are a way to define new types of objects in Python. They provide a blueprint for creating objects that have a specific set of attributes and methods. In other words, classes define the structure and behavior of objects, and allow you to create multiple instances of those objects.
Here are some key differences between classes and functions in Python:
- Syntax: Functions are defined using the def keyword, followed by the function name and any arguments. Classes are defined using the class keyword, followed by the class name and any properties or methods.
- Purpose: Functions are primarily used to perform a specific operation and return a result. Classes, on the other hand, are used to define new types of objects with their own attributes and methods.
- Scope: Functions are typically defined at the module level, and can be called from anywhere in the module. Classes, however, are often defined within a module or within another class, and can only be accessed within that scope.
- Instances: Functions are not instantiated - they are simply called and executed as needed. Classes, on the other hand, can be instantiated to create new objects with their own properties and methods.
- Inheritance: Classes can be inherited from other classes to create new classes that inherit the properties and methods of their parent classes. Functions do not have this capability.
Overall, both classes and functions are important programming constructs in Python, but they serve different purposes and are used in different ways. Understanding the differences between classes and functions is key to writing effective Python code.
Sunday 7 May 2023
Friday 5 May 2023
Sunday 30 April 2023
What does the “yield” keyword do in python?
Python Coding April 30, 2023 Python No comments
In Python, the yield keyword is used to create a generator function. When a function includes a yield statement, it becomes a generator function, which returns an iterator object that can be iterated over with a loop.
The yield statement suspends the function's execution and sends a value back to the caller, but unlike return, the function state is saved, and the function can be resumed later from where it left off.
Here's an example to demonstrate the use of yield:
def countdown(num):
while num > 0:
yield num
num -= 1
Saturday 29 April 2023
Generator Vs List in Python
Python Coding April 29, 2023 Python No comments
In Python, there are two main ways to create sequences of values: using a generator or a list. While both have their uses, they have different performance characteristics and memory usage, so it's important to choose the right one for your specific use case.
A generator is a type of iterable, like a list or a tuple, but unlike a list, a generator does not store all the values in memory at once. Instead, it generates the values on-the-fly as they are requested, using a special type of function called a generator function. Generator functions use the yield keyword to return a value, but unlike a regular function that returns a value and then exits, a generator function can be resumed from where it left off, so it can continue generating values until it is done. Because generators don't store all their values in memory, they can be more memory-efficient than lists for large data sets, and can be faster for certain operations.
Here's an example of a simple generator function that generates a sequence of numbers:
def generate_numbers(n):
for i in range(n):
yield i
To use this generator, you would typically use it in a loop or with a function like next() to generate values one at a time:
numbers = generate_numbers(5)
print(next(numbers)) # Output: 0
print(next(numbers)) # Output: 1
print(next(numbers)) # Output: 2
print(next(numbers)) # Output: 3
print(next(numbers)) # Output: 4
A list, on the other hand, is a type of sequence that stores all its values in memory at once. Lists can be created using square brackets [] or the list() function. Lists are very versatile and can be modified, sliced, and indexed in various ways. However, because they store all their values in memory at once, they can be memory-intensive for large data sets.
Here's an example of creating a list of numbers:
numbers = [0, 1, 2, 3, 4]
To iterate over a list, you can use a for loop or various other functions and methods:
for number in numbers:
print(number)
Both generators and lists have their advantages and disadvantages, so choosing the right one depends on the specific use case. If you have a large data set or you only need to generate values one at a time, a generator might be more memory-efficient and faster. If you need to modify the sequence, access its values multiple times, or if the data set is small enough to fit in memory, a list might be more appropriate.
7 Cool Ways To Use F-Strings In Python
Python Coding April 29, 2023 Python No comments
1. Align strings with f-strings:
You can use f-strings to align strings to the left, right, or center of a field. Here's an example:
name = "Alice"
age = 30
print(f"|{name:<10}|{age:^5}|") # Output: |Alice | 30 |
In this example, the < character aligns the name variable to the left of a 10-character field, and the ^ character centers the age variable in a 5-character field.
2. Use f-strings with dictionary variables:
You can use f-strings with dictionary variables to create dynamic strings. Here's an example:
person = {"name": "Alice", "age": 30}
print(f"My name is {person['name']} and I'm {person['age']} years old.") # Output: My name is Alice and I'm 30 years old.
In this example, the person variable is a dictionary with keys "name" and "age". The f-string uses the values of these keys to create a dynamic string.
3. Use f-strings to format binary and hexadecimal numbers:
You can use f-strings to format binary and hexadecimal numbers. Here's an example:
x = 42
print(f"x = {x:b}") # Output: x = 101010
print(f"x = {x:x}") # Output: x = 2a
In this example, the :b format specifier formats the x variable as a binary number, and the :x format specifier formats the x variable as a hexadecimal number.
4. Use f-strings to format dates and times:
You can use f-strings to format dates and times. Here's an example:
import datetime
now = datetime.datetime.now()
print(f"Today is {now:%B %d, %Y}") # Output: Today is April 29, 2023
In this example, the %B %d, %Y format specifier formats the now variable as a string in the format Month Day, Year.
5. Use f-strings to format currency values:
You can use f-strings to format currency values. Here's an example:
salary = 50000
print(f"My salary is ${salary:,}") # Output: My salary is $50,000
In this example, the , character formats the salary variable as a string with comma separators.
6. Use f-strings with formatted strings:
You can use f-strings with formatted strings to create complex strings. Here's an example:
name = "Alice"
age = 30
message = f"My name is {name} and I'm {age} years old."
print(f"Message length: {len(message):<10}, Message: '{message:^20}'")
# Output: Message length: 32 , Message: 'My name is Alice and I'm 30 years old.'
In this example, the f-string uses another f-string to create a complex string that includes the length of the message variable and the message itself.
7.Use f-strings to format scientific notation:
You can use f-strings to format numbers in scientific notation. Here's an example:
x = 1234567890.123456789
print(f"x = {x:e}") # Output: x = 1.234568e+09
Return VS Yield in Python
Python Coding April 29, 2023 Python No comments
In Python, return and yield are two ways to send a value back from a function or generator to its caller, but they work in different ways.
return is a statement that immediately terminates the execution of a function and returns a value to the caller. When the function is called again, it starts executing from the beginning.
Here's an example:
def square(x):
return x * x
result = square(5)
print(result) # Output: 25
Python Quiz | Day 78 | What is the output of following Python code ?
Python Coding April 29, 2023 Python No comments
Python Quiz | Day 78 | What is the output of following Python code ?
— Python Coding (@clcoding) April 29, 2023
Complete Playlist : https://t.co/ExeeauixjT pic.twitter.com/YAgKqi0M1a
Sunday 23 April 2023
Python Quiz | Day 76 | What is the output of following Python code ?
Python Coding April 23, 2023 Python No comments
Solutions :
Python Quiz | Day 76 | What is the output of following Python code ?
— Python Coding (@clcoding) April 23, 2023
Complete Playlist : https://t.co/ExeeauixjT pic.twitter.com/TEio3zArGP
Saturday 22 April 2023
Python Quiz | Day 73 | What is the output of following Python code ?
Python Coding April 22, 2023 Python No comments
Python Quiz | Day 74 | What is the output of following Python code ?
Python Coding April 22, 2023 Python No comments
Solutions :
Python Quiz | Day 74 | What is the output of following Python code ?
— Python Coding (@clcoding) April 16, 2023
Complete Playlist : https://t.co/ExeeauixjT pic.twitter.com/dCPJruiBjc
Python Quiz | Day 75 | What is the output of following code ?
Python Coding April 22, 2023 Python No comments
Python Quiz | Day 75 | What is the output of following Python code ? Complete Playlist : https://t.co/ExeeauixjT pic.twitter.com/z4gfILNxYQ
— Python Coding (@clcoding) April 21, 2023
Object Oriented Programming in Python
Python Coding April 22, 2023 Python No comments
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects," which can contain data and code to manipulate that data. Python is an object-oriented programming language that supports OOP concepts such as inheritance, encapsulation, and polymorphism. Here are some key concepts and syntax used in Python for OOP:
Class: A class is a blueprint or template for creating objects. It defines a set of attributes and methods that the objects of that class will have.
Syntax:
class ClassName:
# class attributes
attribute1 = value1
attribute2 = value2
# class methods
def method1(self):
# method code
def method2(self):
# method code
Sunday 26 March 2023
Top 5 examples of Python decorators:
Python Coding March 26, 2023 Python No comments
@staticmethod: This decorator is used to define a static method in a class. A static method is a method that can be called on the class itself rather than on an instance of the class. Here's an example:
class MyClass:
@staticmethod
def my_static_method():
print("This is a static method")
@classmethod: This decorator is used to define a class method in a class. A class method is a method that takes the class itself as its first argument rather than an instance of the class. Here's an example:
class MyClass:
class_var = "Hello"
@classmethod
def my_class_method(cls):
print(cls.class_var)
@property: This decorator is used to define a method as a property of a class. Properties allow you to access and set the value of an attribute of an instance of the class without explicitly calling a getter or setter method. Here's an example:
class MyClass:
def __init__(self):
self._x = 0
@property
def x(self):
return self._x
@x.setter
def x(self, value):
if value < 0:
raise ValueError("Value must be non-negative")
self._x = value
@log_calls: This decorator can be used to log all calls to a function. Here's an example:
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"Finished {func.__name__}")
return result
return wrapper
@log_calls
def my_function(x, y):
return x + y
@cache: This decorator can be used to cache the results of a function so that the function doesn't need to be called again with the same arguments. Here's an example:
def cache(func):
results = {}
def wrapper(*args):
if args in results:
return results[args]
result = func(*args)
results[args] = result
return result
return wrapper
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
5 awesome hidden features in Python
Python Coding March 26, 2023 Python No comments
Walrus operator (:=): This operator allows you to assign and return a value in the same expression. It can be particularly useful in list comprehensions or other situations where you need to assign a value to a variable and use it in a subsequent expression. Here's an example:
if (n := len(my_list)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
Wednesday 22 March 2023
Creating a LOG IN form by taking image in background
In this we are going to make a Log_In form in which login filling options will be in a transparent box. And you can add your own background image also.
Note*:- TO change the background go inside the style tag. Inside style tag go to the body and in background-image change the address of the url , give the address of the image which you want to keep in your background. Now,your image will be display on background.
CODE:-
LOG IN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LOG_IN_FORM</title>
<style>
body{
background-image: url('/images/flower.jpg');
background-position-x: center;
background-size: cover;
}
.container{
text-align: center;
padding: 28px ;
margin-left: 30%;
margin-right: 30%;
background-color: rgb(238, 192, 234);
border-radius: 20px;
display: block;
box-shadow: 0 15px 20px rgba(0,0,0,.2);
opacity: 0.8;
}
.txt{
background-color: rgba(223, 210, 227, 0.9);
border-radius: 25px;
opacity: 0.9;
margin-left: 30%;
margin-right: 30%;
text-align: center;
font-family:cursive;
font-size:xx-large;
}
input[type=text] , input[type=password]
{
width: 350px;
margin: 8px 0;
padding: 12px 20px;
display: inline-block ;
border: 2px solid skyblue;
border-radius: 9px;
box-sizing: border-box ;
}
button{
background-color: #c120ac;
width: 30%;
border-radius: 20px;
color: black;
padding: 15px;
margin: 10px 0px;
border: none;
cursor: pointer;
}
button:hover{
opacity: 0.7;
}
</style>
</head>
<body>
<h2 class="txt">
LOG IN
</h2>
<form action="login.php">
<div class="container">
<label>Username</label> <br>
<input type="text" name="username" placeholder="Enter Your Username" required> <br>
<label >Password</label> <br>
<input type="password" name="password" placeholder="Enter Your Password" required> <br>
<button type="submit">LOG IN</button>
<button type="reset">SIGN UP</button> <br>
<a href="#">Foget Password?</a>
</div>
</form>
</body>
</html>
OUTPUT:-The image in background is what I have selected in background you can choose your own it will be displayed like this only and you can change the colour of the box also inside the style tag in .txt and .container.
Friday 17 March 2023
Fancy Hover Buttons in HTML using CSS
In this we are going to add three types of hover button styles which will make your buttons very innovative and attractive.
1.Border Pop
2.Background Slide
3.Background Circle
Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fancy Buttons</title>
<style>
* ,*::before ,*::after{
box-sizing: border-box;
}
body{
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 0;
}
button{
margin: 1rem;
}
.btn{
background-color: var(--background-color);
color: #222;
padding: .5em 1em;
border: none;
outline: none;
position: relative;
cursor: pointer;
--background-color: #E3E3E3;
--border-size:2px;
--accent-color: #0af;
}
.btn.btn-border-pop::before{
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom:0;
z-index: -1;
border: var(--border-size) solid var(--background-color);
transition: top,left,right,bottom,100ms ease-in-out;
}
.btn.btn-border-pop:hover::before,
.btn.btn-border-pop:focus::before{
top: calc(var(--border-size)* -2);
left: calc(var(--border-size)* -2);
right: calc(var(--border-size)* -2);
bottom: calc(var(--border-size)* -2);
}
.btn.btn-background-slide::before{
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--accent-color);
z-index: -1;
transition: transform 300ms ease-in-out;
transform: scale(0);
transform-origin: left;
}
.btn.btn-background-slide:hover::before,
.btn.btn-background-slide:focus::before{
transform: scale(1);
}
.btn.btn-background-slide{
z-index: 1;
transition: color 300ms ease-in-out;
}
.btn.btn-background-slide:hover,
.btn.btn-background-slide:focus{
color: white;
}
.btn.btn-background-circle::before{
content: "";
position: absolute;
top: 0;
left:0;
right:0;
bottom: 0;
z-index: -1;
background-color: var(--background-color);
border-radius: 50%;
transition: transform 500ms ease-in-out;
transform: scale(1.5);
}
.btn.btn-background-circle:hover::before,
.btn.btn-background-circle:focus::before{
transform:scale(0);
}
.btn.btn-background-circle{
z-index:1;
overflow: hidden;
background-color: black;
transition: color 500ms ease-in-out;
}
.btn.btn-background-circle:hover,
.btn.btn-background-circle:focus{
color: white;
}
.btn.btn-border-underline::before {
content: "";
color: brown;
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: var(--border-size);
background-color: var(--accent-color);
transform: scaleX(0);
}
</style>
</head>
<body>
<button class="btn btn-border-pop">Border Pop</button>
<button class="btn btn-background-slide">Background Slide</button>
<button class="btn btn-background-circle">Background Circle</button>
</body>
</html>
Output:-
Popular Posts
-
This textbook grew out of notes for the ECE143 Programming for Data Analysis class that the author has been teaching at University of Cali...
-
1. What is the output of following Python code? a = 'a' print(int(a, 16)) Solution and Explanation: Let's break down the expr...
-
Introduction to Modern Statistics is a re-imagining of a previous title, Introduction to Statistics with Randomization and Simulation. The...
-
What you'll learn Gain an immersive understanding of the practices and processes used by a junior or associate data analyst in their d...
-
Code: g = [1, 2, 3] h = [1, 2, 3] print(g is h) print(g == h) Solution and Explanation: In Python, the expressions g = [1, 2, 3] and h ...
-
Code: str_a = "hello" str_b = "hello" print(str_a is str_b) print(str_a == str_b) Solution and Explanation: In Pytho...
-
Code: dict_a = {"a": 1, "b": 2} dict_b = {"a": 1, "b": 2} print(dict_a is dict_b) print(dict_a == ...
-
Code: num = [7, 8, 9] *mid, last = num[:-1] print(mid, last) Solution and Explanation: let's break down the code: num = [7, 8, 9] *m...
-
Code: h = [5, 6, 7, 8] h.pop() h.pop(0) print(h) Solution and Explanation: Let's break down the given Python code and explain what ea...
-
import statsmodels.api as sm import numpy as np # Generate some sample data x = np.random.rand(100) y = 2 * x + np.random.randn(100) # Fit...