IT |
気になる、記になる… |
「Nintendo Switch 2」は新しいカメラ機能を搭載か ー 一部のプレスや開発者には披露されたとの情報も |
https://taisy0.com/2023/08/30/176047.html
|
nintendo |
2023-08-30 14:20:15 |
AWS |
AWS Partner Network (APN) Blog |
Data Ingestion in a Multi-Tenant SaaS Environment Using AWS Services |
https://aws.amazon.com/blogs/apn/data-ingestion-in-a-multi-tenant-saas-environment-using-aws-services/
|
Data Ingestion in a Multi Tenant SaaS Environment Using AWS ServicesAWS experts break down how you can build a multi tenant data ingestion and processing engine using AWS services We examine each component of this data pipeline and examine some of the key considerations that can influence how you approach designing a SaaS multi tenant data ingestion process We also explore how multi tenant streaming data can be ingested transformed and stored using AWS services while ensuring there are constructs built in to the pipeline to ensure secure processing of the data |
2023-08-30 14:16:31 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ジョジョの奇妙な ELYZA-japanese-Llama-2-7b-instruct |
https://qiita.com/maskot1977/items/f75abdbaccdc2a20da80
|
yzajapanesellamabinstruct |
2023-08-30 23:10:09 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
リセットボタンでJSが走る処理を書いたらうまくいかなかった |
https://qiita.com/ishi0123/items/e081f525adb2eef98037
|
reset |
2023-08-30 23:33:04 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
Slim【入門の書】 |
https://qiita.com/iijima-naoya-45b/items/5082639118c47b50a32d
|
概要 |
2023-08-30 23:43:26 |
Azure |
Azureタグが付けられた新着投稿 - Qiita |
Azure Database for PostgreSQL への Azure Service Connector の作成に失敗する(回避策あり) |
https://qiita.com/takashiuesaka/items/f1ed81e257179cd6751a
|
azure |
2023-08-30 23:33:04 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
【Rails】Deviseでパスワードのバリデーションを追加する方法 |
https://qiita.com/P-man_Brown/items/759256ffb35ee5237598
|
validpasswordregexaazdazd |
2023-08-30 23:58:18 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
Slim【入門の書】 |
https://qiita.com/iijima-naoya-45b/items/5082639118c47b50a32d
|
概要 |
2023-08-30 23:43:26 |
海外TECH |
MakeUseOf |
4 Ways to Cut Down Your Work Hours |
https://www.makeuseof.com/4-ways-to-cut-down-your-work-hours/
|
control |
2023-08-30 14:31:22 |
海外TECH |
MakeUseOf |
Function Keys Not Working in Windows 10? Here's What to Do |
https://www.makeuseof.com/function-keys-not-working-windows-10/
|
fixes |
2023-08-30 14:16:27 |
海外TECH |
MakeUseOf |
What Is Backend as a Service (BaaS)? |
https://www.makeuseof.com/what-is-backend-as-a-service/
|
kitchen |
2023-08-30 14:01:25 |
海外TECH |
DEV Community |
AWS Project: Architecting a Secure and Scalable Network with AWS VPCs and Subnets |
https://dev.to/brandondamue/aws-project-architecting-a-secure-and-scalable-network-with-aws-vpcs-and-subnets-1174
|
AWS Project Architecting a Secure and Scalable Network with AWS VPCs and SubnetsAfter consistently focusing my time and attention mostly on writing articles that explore and examine theoretical cloud computing concepts I have decided to switch lanes and drive into Projects Boulevard see what I did there Starting with this article my focus is now on creating tutorial content by working on small AWS projects aimed at helping beginners and aspiring cloud professionals In today s episode maybe I should have said today s edition since I m writing right But I hope you get the point regardless the project we are going to work on configuring a custom VPC with a public and private subnet in the AWS cloud After having done this we are going to deploy a bastion host in the public subnet which will allow us SSH to an EC instance in the private subnet The objective of this project is to help beginners understand concepts like VPCs subnets Network ACLs routing and security groups Hope you are ready and excited because getting started right now Project PrerequisitesAn AWS account that is free tier eligible because we don t want to spend money on this project Basic knowledge of VPCs subnets Network ACLs routing and security groups Grit I had a deep conviction to include this because it is easy to give along the way when you hit a roadblock I beckon you to still strive to complete the project regardless of any roadblocks that might ensue With the prerequisites out of the way we can now start working on the project Step One Creating a custom VPC and SubnetsThe very first thing we have to do is to create our VPC To do this log into your AWS account to access the management console Make sure you are not using the root user account to complete this project as you will not be following one of AWS s best practices which advises that we should avoid using the root user for everyday tasks like this one Instead it s recommended that you create an IAM user with administrative privileges and use it for this project Once you have logged into your IAM user account that has admin permissions using the search bar of the management console search VPC and click on the first item in the search results that appear to open the VPC management console window as shown in the image below If you feel the need to refresh your knowledge about VPCs this article is the perfect resource for you For reference I will launch all the resources I use in this project in the North Virginia region If you want to follow along to the last detail make sure you are also launching your resources in the North Virginia region Now let s create our VPC Creating a VPC has been made easier as you can create your VPC and subnets and define route tables and other VPC resources in one go Following the steps as indicated in the image above will enable you to create your VPC and its associated resources Now let s move on the create a security group Step Two Configuring Security GroupsTo locate the security group console we have to search and navigate to the EC management console window Once in the EC dashboard navigate to the security groups tab and create a security group as shown in the image below Now that we have created the security group let us go on to configure its inbound and outbound rules In the inbound rules tab click on Edit inbound rules and do the following Search for the IP address of your computer by using this website and use it to create an inbound rule that allows SSH access to the resources that will be associated with the security group The image below makes it easier to understand what I m saying Using your IP address as the only allowed IP ensures that only your local machine computer with the specified IP address can establish SSH connections to the bastion host This helps mitigate potential security risks by limiting access to your resources Step Three Setting up a Bastion HostThe next step in the project is to launch a bastion host in the public subnet via which we are going to connect to an EC instance launched in the private subnet So let s get that done Within your management console navigate to the EC window To make sure we don t accrue any cost we are going to use an AMI that is free tier eligible While launching the EC instance be sure to select the security group we created earlier as its security group After having filled in all the details clicking on the Launch instance button launches our bastion host EC instance Now that it is up and running let s move on to the next step Step Four Launch Private EC InstanceWe need another EC instance in our private subnet which we are going to access it using SSH via the bastion host This instance is going to use the same key pair and security group as the bastion host in the public subnet Step Five SSH to Bastion HostThe time to start testing our work has come We are going to access our bastion host from our computer So open a terminal window and run the following commands chmod path to private key pemThis command will secure the key pair file that was downloaded when we created our key pair After that the next command to be run is ssh i path to key pem ec user bastion public ipMake sure you edit the command as needed before running it With that we will be connected to our bastion host and we can now connect to the private instance via SSH from the bastion host To do that run the following command ssh ec user private instance private ipThat s all that there is to it Now close the connection to your EC instances by running the exit command Last StepThe very last step in this article is to clean up our resources because we wouldn t want to wake up to unwanted AWS bills right So make sure you terminate the two EC instances we launched in this tutorial and delete the other resources as well Final WordsYou ve journeyed through the key aspects of AWS networks in this tutorial You ve learned about VPCs bastion hosts security groups and the dynamic interplay of public and private subnets These concepts might seem complex at first but remember they re the foundational blocks upon which secure and efficient AWS environments are built So as you continue to explore the AWS universe know that you ve laid the groundwork for creating safe interconnected spaces for your applications to thrive The skills you ve gained here will serve as your compass as you navigate more intricate cloud landscapes Keep building keep learning and may your future AWS ventures be as successful as your journey here Happy networking |
2023-08-30 14:45:27 |
海外TECH |
DEV Community |
Basic Python: 12. Python File Handling |
https://dev.to/akashsingh3031/basic-python-12-python-file-handling-1cjn
|
Basic Python Python File HandlingIn the realm of programming files serve as a means to store retrieve and manipulate data Python s file handling capabilities provide developers with the tools they need to work with various types of files In this blog post we ll delve into the world of Python file handling exploring how to read from and write to files and providing real world examples along the way Table of ContentsIntroduction to File HandlingOpening and Closing FilesReading from FilesWriting to FilesAppending to FilesFile Methods and AttributesWorking with ModesWorking with Context ManagersException Handling for File OperationsWorking with Binary FilesWorking with CSV FilesWorking with JSON FilesBest Practices for File Handling Introduction to File HandlingFile handling in Python refers to the ability to interact with files stored on the computer s storage system This is crucial for tasks like reading data from configuration files processing large datasets or storing program outputs Opening and Closing FilesBefore you can read from or write to a file you need to open it Python provides the open function for this purpose file open example txt r Opens the file in read modeAfter working with the file it s important to close it using the close method file close Reading from FilesYou can read the content of a file using methods like read readline or readlines file open example txt r content file read print content file close Writing to FilesTo write content to a file open it in write mode w and use the write method file open output txt w file write Hello world file close Appending to FilesTo add content to an existing file without overwriting it open the file in append mode a file open output txt a file write nAppending new content file close File Methods and AttributesPython provides various methods and attributes for file objects including read write seek tell and more Working with ModesPython provides different modes for file handling including r Read mode default w Write mode creates a new file or truncates an existing file a Append mode appends to an existing file b Binary mode x Exclusive creation mode Working with Context ManagersPython s with statement simplifies file handling by automatically closing files when you re done with them with open example txt r as file content file read print content File automatically closed outside the with block Exception Handling for File OperationsFile operations can lead to errors such as when a file is not found or when you lack permissions Proper exception handling is important try with open missing file txt r as file content file read except FileNotFoundError print File not found Working with Binary FilesBinary files e g images videos can be read and written using the binary mode rb and wb with open image jpg rb as binary file binary data binary file read with open copy image jpg wb as copy file copy file write binary data Working with CSV FilesCSV Comma Separated Values files are widely used for storing tabular data Python s csv module simplifies reading and writing CSV files import csvwith open data csv r as file csv reader csv reader file for row in csv reader print row Working with JSON FilesJSON JavaScript Object Notation is a popular format for data interchange Python s json module makes it easy to work with JSON files import jsondata name Akash age with open data json w as file json dump data file Best Practices for File HandlingUse context managers with statements to ensure proper file closure Handle exceptions to address potential errors during file operations Avoid hardcoding file paths use variables or configuration files Clearly document your file handling operations within your code Be cautious with file permissions especially when writing or appending |
2023-08-30 14:36:36 |
海外TECH |
DEV Community |
Basic Python: 11. Python Modules and Packages |
https://dev.to/akashsingh3031/basic-python-11-python-modules-and-packages-26el
|
Basic Python Python Modules and PackagesPython s power lies not just in its core language features but also in its expansive ecosystem of modules and packages These tools allow you to tap into existing code enhance your projects and collaborate more efficiently In this blog post we ll dive deep into Python modules and packages understanding their significance how to create them and their real world applications Let s get started Table of ContentsIntroduction to Modules and PackagesImporting ModulesCreating Your Own ModulesExploring the Standard LibraryIntroducing Python PackagesCreating PackagesUsing Third Party PackagesVirtual Environments for Package IsolationModule Aliases and Namespace ConflictsBest Practices for Working with Modules and Packages Introduction to Modules and PackagesIn Python modules are files containing Python code while packages are directories containing multiple modules These allow you to organize and reuse code effectively leading to more manageable and maintainable projects Importing ModulesTo use a module you need to import it using the import statement import mathprint math sqrt Output Creating Your Own ModulesYou can create your own modules by simply creating a py file Let s say you have a file named my module py my module pydef greet name print f Hello name def add a b return a bTo use this module place it in the same directory as your main script and use the import statement import my modulemy module greet Akash Output Hello Akash Exploring the Standard LibraryPython comes with a rich standard library containing modules for various tasks such as working with files regular expressions and more import datetimecurrent time datetime datetime now print current time Introducing Python PackagesPackages are directories containing multiple modules often organized by functionality Creating PackagesCreating a package involves creating a directory with an init py file Let s say you have a directory named my package my package init py module py module pyYou can then use the modules in the package as follows from my package import module modulemodule function module function Using Third Party PackagesPython s strength lies in its community contributed packages To use them you need to install them using tools like pip pip install requests Virtual Environments for Package IsolationVirtual environments help isolate project specific dependencies avoiding conflicts between packages python m venv myenvsource myenv bin activate On macOS Linuxmyenv Scripts activate On Windows Module Aliases and Namespace ConflictsYou can use aliases to rename imported modules preventing namespace clashes import my long module name as mln Best Practices for Working with Modules and PackagesOrganize Code Divide code into modules and packages for clarity Use Descriptive Names Choose meaningful names for modules and packages Document Code Add docstrings and comments to explain functionality Avoid Circular Imports Circular imports can lead to unexpected behavior |
2023-08-30 14:36:27 |
海外TECH |
DEV Community |
Basic Python: 10. Exception Handling |
https://dev.to/akashsingh3031/basic-python-10-exception-handling-3h38
|
Basic Python Exception HandlingIn the world of programming errors are inevitable However Python provides a robust mechanism for dealing with errors and preventing your program from crashing This mechanism is called exception handling In this blog post we will explore the concepts of exception handling in Python how to catch and handle different types of exceptions and best practices to ensure your code remains robust and resilient Let s dive in Table of ContentsIntroduction to Exception HandlingBasic Syntax of try exceptCatching Specific ExceptionsHandling Multiple ExceptionsUsing else and finallyRaising Custom ExceptionsCommon Built in ExceptionsBest Practices for Exception HandlingReal world Example File Handling Introduction to Exception HandlingAn exception in Python is an event that occurs during the execution of a program and disrupts its normal flow Exception handling allows you to gracefully deal with these unexpected situations and prevent your program from crashing Basic Syntax of try exceptThe core of exception handling in Python is the try and except blocks Here s a simple example try Code that might raise an exceptionexcept ExceptionType Code to handle the exceptionFor instance try num int input Enter a number result num print Result result except ZeroDivisionError print Cannot divide by zero except ValueError print Invalid input Please enter a valid number Catching Specific ExceptionsYou can catch specific exceptions to handle different types of errors more precisely try Code that might raise an exceptionexcept SpecificException Code to handle the specific exception Handling Multiple ExceptionsYou can handle multiple exceptions in a single try block try Code that might raise an exceptionexcept ExceptionType ExceptionType Code to handle the exceptions Using else and finallyThe else block is executed when no exception occurs and the finally block is always executed whether an exception is raised or not try Code that might raise an exceptionexcept SpecificException Code to handle the exceptionelse Code to execute when no exception occursfinally Code that always executes Raising Custom ExceptionsYou can raise your own exceptions using the raise statement This is useful when you want to handle specific scenarios in your code def validate age age if age lt raise ValueError Age cannot be negative try user age int input Enter your age validate age user age except ValueError as ve print ve Common Built in ExceptionsPython provides a variety of built in exceptions that cover different error scenarios such as TypeError IndexError KeyError and more Best Practices for Exception HandlingBe Specific Catch specific exceptions rather than using a generic except block Keep it Simple Avoid excessive nesting of try and except blocks Document Your Code Use comments or docstrings to explain the purpose of your exception handling Log Exceptions Use the logging module to log exceptions for debugging Test Exception Cases Write test cases to ensure your exception handling works as intended Real world Example File HandlingException handling is crucial in file operations where unforeseen issues can occur Let s look at an example of reading from a file Consider you have a file named example txt with the following content Hello this is an example file It contains some text for demonstration Now let s write code to read the content of this file using exception handling file path example txt try with open file path r as file content file read print content except FileNotFoundError print f File file path not found except Exception as e print f An error occurred e In this code snippet we first attempt to open and read the file using a with statement which automatically closes the file when we re done If the file is found its content is read and printed However two exceptions are being handled FileNotFoundError If the file specified by file path doesn t exist a FileNotFoundError will be raised We catch this exception and print a user friendly error message Exception This is a catch all exception that handles any other unexpected errors that might occur while trying to open and read the file We print a generic error message along with the specific error message provided by the exception By using exception handling in this scenario we can ensure that our program doesn t crash if the file is missing or if some other unexpected error occurs during the file operations |
2023-08-30 14:36:14 |
海外TECH |
DEV Community |
Basic Python: 9. Python Functions |
https://dev.to/akashsingh3031/basic-python-9-python-functions-53gb
|
Basic Python Python FunctionsIn the world of programming functions are like building blocks that enable you to organize and structure your code Functions in Python play a pivotal role in making your code modular reusable and efficient In this blog post we will take a deep dive into Python functions exploring their syntax benefits and how to create and use them effectively Let s get started Table of ContentsIntroduction to FunctionsDefining and Calling FunctionsFunction Parameters and ArgumentsReturn Statement and ValuesScope and Lifetime of VariablesDefault ArgumentsKeyword ArgumentsArbitrary ArgumentsAnonymous Functions Lambda Functions Recursion Functions Calling ThemselvesFunction DecoratorsBuilt in Python FunctionsBest Practices for Writing Functions Introduction to FunctionsA function in Python is a block of code designed to perform a specific task It encapsulates a set of instructions and can be called multiple times throughout your program eliminating code duplication and enhancing readability Defining and Calling FunctionsHere s the basic syntax of defining a function in Python def function name Code goes hereTo call a function you simply use its name followed by parentheses def greet print Hello there Calling the functiongreet Function Parameters and ArgumentsFunctions can accept parameters which are variables that hold the data passed into the function These are defined within the parentheses of the function definition def greet name print Hello name Calling the function with an argumentgreet Akash Return Statement and ValuesA function can return a value using the return statement This is useful when you want to use the result of a function in other parts of your code def add a b return a bresult add print Sum result Scope and Lifetime of VariablesVariables defined inside a function have a local scope meaning they are accessible only within that function They are destroyed once the function call is complete Default ArgumentsYou can provide default values to function parameters which are used if no argument is provided during the function call def greet name Guest print Hello name greet Output Hello Guestgreet Akash Output Hello Akash Keyword ArgumentsPython allows you to pass arguments to functions using the parameter names as keywords def show info name age print Name name print Age age show info age name Akash Arbitrary ArgumentsYou can pass a variable number of arguments to a function using the args syntax def show items items for item in items print item show items apple banana cherry Anonymous Functions Lambda Functions Lambda functions are small unnamed functions often used for simple operations double lambda x x print double Output Recursion Functions Calling ThemselvesRecursion is a technique where a function calls itself to solve a problem It s commonly used for tasks that can be broken down into simpler instances of the same problem def factorial n if n return else return n factorial n print factorial Output Function DecoratorsDecorators are a powerful feature in Python that allow you to modify the behavior of a function without changing its code def uppercase decorator func def wrapper text result func text return result upper return wrapper uppercase decoratordef greet name return f Hello name print greet Akash Output HELLO AKASH Built in Python FunctionsPython comes with a wide range of built in functions that perform various tasks from mathematical operations to working with data structures num list sorted list sorted num list print sorted list Output Best Practices for Writing FunctionsUse Descriptive Names Choose meaningful names for functions Keep It Simple Functions should do one thing and do it well Limit Function Length Avoid overly long functions break them down if needed Document Your Functions Use comments or docstrings to explain what your functions do Test Your Functions Write test cases to ensure your functions work as intended |
2023-08-30 14:36:04 |
海外TECH |
DEV Community |
Basic Python: 8. Python Inputs & Outputs |
https://dev.to/akashsingh3031/basic-python-8-python-inputs-outputs-2nl6
|
Basic Python Python Inputs amp OutputsPython is a versatile programming language known for its simplicity and ease of use One of the fundamental aspects of programming is dealing with input and output operations In this blog we ll explore how to handle input and output in Python along with examples to illustrate these concepts Table of ContentsTaking User Input in PythonDisplaying Output in PythonFormatted OutputFile Input and Output I O in PythonError Handling and ValidationWorking with Standard StreamsReal World Examples Taking User Input in PythonGathering input from users or external sources is referred to as input Python provides a built in function called input that simplifies capturing user input Example Taking user input and displaying a messagename input Enter your name print Hello name Welcome to our blog In this instance the input function prompts users for their name The entered data is stored in the variable name which is then utilized to create a personalized welcome message Displaying Output in PythonOutput involves conveying information to users writing data to files or presenting data in other ways The most common method to produce output in Python is using the print function Examples Printing a messageprint Welcome to the Python Input Output Blog Printing the value of a variableage print Your age is age Formatted OutputFormatted output allows you to present data in a structured and readable manner Python provides the format method and f strings for achieving formatted output Using format name Alice age print Name Age format name age Using f strings Python name Bob age print f Name name Age age File Input and Output I O in PythonPython not only interacts with users but also handles reading and writing data to files This is invaluable for preserving information beyond a program s runtime Writing to a File The open function is used to create and write to a file Writing to a filewith open my file txt w as file file write This is some content written to the file Reading from a File To read data from a file you can employ methods like read readline and readlines Reading from a filewith open my file txt r as file content file read print content Error Handling and ValidationEffective input handling involves error detection and validation Python s try and except blocks are used to catch and handle errors gracefully try num int input Enter a number result num print Result result except ZeroDivisionError print Cannot divide by zero except ValueError print Invalid input Please enter a valid number Working with Standard StreamsPython provides three standard streams stdin standard input stdout standard output and stderr standard error import sysuser input sys stdin readline sys stdout write This is standard output n sys stderr write This is an error message n Real World Examples Example Creating a To Do Listwith open todo txt a as file task input Enter a task file write task n print Task added to the to do list Example Reading CSV Dataimport csvwith open data csv r as file reader csv reader file for row in reader print row |
2023-08-30 14:35:52 |
海外TECH |
DEV Community |
Basic Python: 7. Python Loops |
https://dev.to/akashsingh3031/basic-python-7-python-loops-5jj
|
Basic Python Python LoopsLoops allow you to repeat certain actions multiple times The for loop and the while loop are commonly used in Python Table of ContentsThe for LoopThe while LoopLoop Control StatementsNested LoopsLooping Through Iterables The for LoopThe for loop is used to iterate over a sequence such as a list tuple string or range and execute a block of code for each element in the sequence Syntax for element in sequence Code block to be executed Example Iterating Through a Listfruits apple banana cherry for fruit in fruits print fruit Example Using the range Functionfor num in range Iterates from to print num The while LoopThe while loop repeatedly executes a block of code as long as a given condition is true Syntax while condition Code block to be executed Example Counting Down with while Loopcount while count gt print count count Example Sum of Numbers Using while Looptotal num while num lt total num num print Sum total Loop Control StatementsPython provides loop control statements to modify the flow of loops break Statement Terminates the loop prematurely numbers for num in numbers if num break print num continue Statement Skips the remaining code and moves to the next iteration numbers for num in numbers if num continue print num pass Statement Acts as a placeholder for future code without affecting the loop s execution numbers for num in numbers if num print f num is even else pass Placeholder for future codeprint Loop finished Nested LoopsYou can nest loops within each other to handle more complex tasks rows cols for i in range rows for j in range cols print f i j end print Looping Through IterablesPython s built in functions like enumerate zip and iteritems make it easy to loop through and manipulate iterables Using enumerate to loop through a list with index and valuefruits apple banana cherry for index fruit in enumerate fruits print f Index index Fruit fruit Using zip to loop through multiple lists simultaneouslynames Alice Bob Charlie ages for name age in zip names ages print f Name name Age age Using items to loop through key value pairs in a dictionarystudent scores Alice Bob Charlie for name score in student scores items print f Name name Score score |
2023-08-30 14:35:40 |
海外TECH |
DEV Community |
Basic Python: 6. Python Conditional Statements |
https://dev.to/akashsingh3031/basic-python-6-python-conditional-statements-3gm8
|
Basic Python Python Conditional StatementsConditional statements are an essential part of programming that allow you to control the flow of your code based on certain conditions In Python you can achieve this using if elif and else statements These statements help your program make decisions and execute different blocks of code based on whether specific conditions are true or false Table of ContentsThe if StatementThe if else StatementThe if elif else StatementNested Conditional StatementsTernary Operator Combining ConditionsUsing Logical Operators The if StatementThe if statement is used to execute a block of code only if a certain condition is true Syntax if condition Code to be executed if the condition is trueHere s a simple example that checks if a number is positive num if num gt print The number is positive The if else StatementThe if else statement allows you to execute one block of code when a condition is true and another block when the condition is false Syntax if condition Code to be executed if the condition is trueelse Code to be executed if the condition is falseLet s see an example that checks whether a number is even or odd num if num print The number is even else print The number is odd The if elif else StatementThe if elif else statement is used when you have multiple conditions to check elif stands for else if and allows you to test multiple conditions in sequence Syntax if condition Code to be executed if condition is trueelif condition Code to be executed if condition is trueelse Code to be executed if none of the conditions are trueHere s an example that categorizes a student s score into different grades score if score gt print A elif score gt print B elif score gt print C else print F Nested Conditional StatementsYou can also nest conditional statements within each other to handle more complex scenarios Just be mindful of proper indentation to maintain code readability Here s a basic example x y if x gt if y gt print Both x and y are positive else print Only x is positive else print Neither x nor y is positive Ternary OperatorThe ternary operator is a concise way to write simple if else statements in a single line The ternary operator expression if condition else expression is a concise way to write conditional expressions is sunny Trueweather It s sunny if is sunny else It s cloudy print weather Combining ConditionsYou can combine conditions using logical operators and or and not temperature is raining Falseif temperature gt and not is raining print Perfect weather for a picnic Using Logical OperatorsLogical operators help you build complex conditions by combining simpler ones x y if x gt and y gt print Both x and y are positive elif x gt or y gt print At least one of x or y is positive else print Neither x nor y is positive |
2023-08-30 14:35:25 |
海外TECH |
DEV Community |
Basic Python: 5. Python Operators |
https://dev.to/akashsingh3031/basic-python-5-python-operators-53db
|
Basic Python Python OperatorsOperators are essential components of any programming language and Python is no exception They allow you to perform various operations on variables and values making your code more dynamic and powerful In this blog we ll explore different types of operators in Python and provide simple examples to help you understand their usage Table of ContentsArithmetic OperatorsComparison OperatorsLogical OperatorsAssignment OperatorsIdentity OperatorsMembership OperatorsBitwise Operators Arithmetic OperatorsArithmetic operators are used for mathematical calculations Addition Adds two values a b result a b print result Output Subtraction Subtracts the second value from the first x y result x y print result Output Multiplication Multiplies two values p q result p q print result Output Division Divides the first value by the second m n result m n print result Output Modulus Returns the remainder of division numerator denominator result numerator denominator print result Output Exponentiation Raises the first value to the power of the second base exponent result base exponent print result Output Floor Division Returns the floor value after division dividend divisor result dividend divisor print result Output Comparison OperatorsComparison operators are used to compare values Equal to Checks if two values are equal x y result x y Trueprint result Output True Not Equal to Checks if two values are not equal a b result a b Trueprint result Output True Greater than gt Checks if the first value is greater than the second num num result num gt num Trueprint result Output True Less than lt Checks if the first value is less than the second p q result p lt q Trueprint result Output True Greater than or equal to gt Checks if the first value is greater than or equal to the second m n result m gt n Trueprint result Output True Less than or equal to lt Checks if the first value is less than or equal to the second alpha beta result alpha lt beta Trueprint result Output True Logical OperatorsLogical operators are used to combine and manipulate boolean values AND and Returns True if both operands are True p Trueq Falseresult p and q Falseprint result Output False OR or Returns True if at least one operand is True x Truey Falseresult x or y Trueprint result Output True NOT not Returns the opposite of the operand s value value Trueresult not value Falseprint result Output False Assignment OperatorsAssignment operators are used to assign values to variables Assignment Assigns a value to a variable a print a Output Add and Assign Adds a value to the variable and assigns the result num num num num print num Output Subtract and Assign Subtracts a value from the variable and assigns the result value value value value print value Output Multiply and Assign Multiplies the variable by a value and assigns the result count count count count print count Output Divide and Assign Divides the variable by a value and assigns the result total total total total print total Output Identity OperatorsIdentity operators are used to compare the memory locations of two objects They are often used to determine if two variables refer to the same object in memory is Operator This operator returns True if two variables point to the same object in memory and False otherwise x y xz print x is y Output Trueprint x is z Output False is not Operator This operator returns True if two variables do not point to the same object in memory and False if they do a b print a is not b Output False Membership OperatorsMembership operators are used to test whether a value or variable is found in a sequence such as a list tuple or string in Operator This operator returns True if a value is found in the sequence and False otherwise fruits apple banana orange print apple in fruits Output Trueprint grape in fruits Output False not in Operator This operator returns True if a value is not found in the sequence and False if it is numbers print not in numbers Output Trueprint not in numbers Output False Bitwise OperatorsBitwise operators are used to perform operations at the bit level They are often used in low level programming and when working with binary representations of data Bitwise AND amp Performs a bitwise AND operation on each bit of the operands a Binary b Binary result a amp b Binary Decimal print result Output Bitwise OR Performs a bitwise OR operation on each bit of the operands x Binary y Binary result x y Binary Decimal print result Output Bitwise XOR Performs a bitwise XOR operation on each bit of the operands p Binary q Binary result p q Binary Decimal print result Output Bitwise NOT Inverts the bits of the operand effectively changing s to s and vice versa num Binary result num Binary Decimal print result Output Left Shift lt lt Shifts the bits of the left operand by the number of positions specified by the right operand value Binary shifted value lt lt Binary Decimal print shifted Output Right Shift gt gt Shifts the bits of the left operand to the right by the number of positions specified by the right operand number Binary shifted number gt gt Binary Decimal print shifted Output |
2023-08-30 14:35:07 |
海外TECH |
DEV Community |
Basic Python: 4. Python Data Types |
https://dev.to/akashsingh3031/basic-python-4-python-data-types-1m2l
|
Basic Python Python Data TypesEvery value in Python has a data type which determines what kind of data it represents and what operations can be performed on it Some common data types in Python are Table of ContentsNumeric Data Types Integer int Floating Point float Complex complex Textual Data Types String str String OperationsSequence Data Types List list Tuple tuple Range range Mapping Data Type Dictionary dict Set Data Type Set set Frozenset frozenset Boolean Data Type bool Boolean ValuesBinary Types bytes Bytes bytearray Byte ArraysNoneType None The None ObjectType Conversion Casting User Defined ClassesChecking Data Types Numeric Data Types Integer int Integers represent whole numbers without decimal points They can be positive or negative x y Floating Point float Floating point numbers are numbers with decimal points They are used to represent real numbers pi temperature Complex complex Complex numbers consist of a real part and an imaginary part z j Textual Data Types String str Strings are sequences of characters enclosed in single or double quotes name Akash message Hello world String OperationsStrings support various operations like concatenation slicing and formatting greeting Hello name Akash full greeting greeting name Concatenationsubstring full greeting Slicingformatted message f greeting name String formatting Sequence Data Types List list Lists are ordered collections that can contain elements of different types fruits apple banana orange Tuple tuple Tuples are similar to lists but are immutable coordinates Range range Ranges represent sequences of numbers numbers range Creates a range from to Mapping Data Type Dictionary dict Dictionaries store key value pairs and allow fast lookup person name Akash age city Pune Set Data Type Set set Sets are unordered collections of unique elements colors red green blue Frozenset frozenset Frozensets are like sets but are immutable immutable colors frozenset red green blue Boolean Data Type bool Boolean ValuesBoolean values represent truth True or falsehood False is valid True Binary Types bytes BytesBytes represent sequences of bytes integers from to data b hello bytearray Byte ArraysByte arrays are mutable sequences of bytes mutable data bytearray data None Type None The None ObjectThe None object represents the absence of a value result None User Defined ClassesYou can define your own data types using classes class Point def init self x y self x x self y y Type Conversion Casting Python allows you to convert between different data types using type casting functions x y int x Casting to integer Checking Data TypesPython provides the type function to determine the data type of a value This function returns the class type of the argument Here s how you can use it print type age Output lt class int gt print type temperature Output lt class float gt print type name Output lt class str gt print type is student Output lt class bool gt print type fruits Output lt class list gt print type coordinates Output lt class tuple gt print type person Output lt class dict gt print type unique numbers Output lt class set gt |
2023-08-30 14:34:43 |
海外TECH |
DEV Community |
Basic Python: 3. Python Variables |
https://dev.to/akashsingh3031/basic-python-3-python-variables-1ick
|
Basic Python Python VariablesIn the world of programming variables are the building blocks that store and manipulate data In Python a versatile and powerful programming language understanding variables is fundamental to writing effective code In this blog post we ll delve into the world of Python variables covering their basics naming conventions data types scope and best practices through real world examples Table of ContentsDefining and Assigning VariablesNaming Conventions for VariablesData Types and Type InferenceVariable Scope and LifetimeBest Practices for Using Variables Introduction to Python VariablesAt its core a variable is a named container that holds a value Variables play a crucial role in programming allowing us to store and manipulate data in a dynamic manner Defining and Assigning VariablesIn Python variables are created and assigned values using a simple syntax Assigning values to variablesname Akash age height is student True Naming Conventions for VariablesWhen naming variables in Python adhere to the following guidelines Variable names should be descriptive and meaningful Use lowercase letters for variable names Separate words with underscores for readability user name instead of username Avoid using Python s reserved keywords e g if for while as variable names Data Types and Type InferencePython is dynamically typed which means that you don t need to declare the type of a variable explicitly The interpreter infers the variable s type based on the assigned value Integer variableage String variablename Akash Float variableheight Variable Scope and LifetimeThe scope of a variable defines where it can be accessed or modified Python has three levels of variable scope local enclosing for nested functions and global A variable s lifetime refers to the duration for which it exists in memory Local ScopeA variable declared inside a function is in the local scope It s only accessible within that function def my function local var Local variable print local var my function print local var Error NameError Enclosing Scope Nested Functions When you have nested functions the enclosing function s scope becomes accessible to the inner function def outer function outer var Enclosing scope variable def inner function print outer var Accessible from inner function inner function outer function Global ScopeA variable declared outside of any function is in the global scope This means it s accessible from anywhere in the program global var Global variabledef my function print global var Accessible inside the functionmy function print global var Accessible outside the function Global Variables Inside FunctionsWhile global variables are accessible inside functions modifying them requires extra care If a global variable is modified inside a function without explicitly declaring it as global a new local variable with the same name is created instead global var Global variabledef modify global global var Creates a new local variable print global var modify global print global var Output unchanged Modifying Global VariablesTo modify a global variable inside a function you need to declare it as global global var Global variabledef modify global global global var global var Modifies the global variable print global var modify global print global var Output modified Using Local and Global Variables TogetherLocal and global variables can coexist each maintaining its scope total Global variabledef update total value global total Modifying the global variable total value Modifying the global variable local var Local variable print Local variable local var print Global variable total update total Best Practices for Using VariablesChoose meaningful variable names that reflect their purpose Initialize variables before using them to avoid unexpected behavior Avoid using single letter variable names unless for short lived iterators Keep variable names concise but not so short that they become unclear Group related variables together using appropriate data structures |
2023-08-30 14:34:27 |
海外TECH |
DEV Community |
Basic Python: 2. Python Comments |
https://dev.to/akashsingh3031/basic-python-2-python-comments-5a97
|
Basic Python Python CommentsComments in Python are annotations within your code that are ignored by the interpreter They serve as notes to explain code logic add reminders or provide context to fellow developers including your future self Table of ContentsSingle Line CommentsMulti Line CommentsInline CommentsDocumentation Strings Docstrings Using Comments EffectivelyBest Practices for Writing Comments Single Line CommentsA single line comment is a comment that spans only one line of code It s preceded by the symbol This is a single line commentprint Hello world Multi Line CommentsWhile Python doesn t have a dedicated syntax for multi line comments you can achieve the same effect using triple quotes or This is a multi line comment It spans multiple lines and can be usedto explain complex code sections Inline CommentsInline comments are short comments placed at the end of a line of code to provide context or clarification x Initialize x to Documentation Strings Docstrings Docstrings are special multi line comments used to document modules functions classes or methods They can be accessed using the help function def greet name This function greets the user by name print f Hello name help greet Using Comments Effectively Provide Context Fetch user data from API temporary mock data for example user data fetch user data api endpoint Explanation of Complex Logic Calculate the Fibonacci sequence using recursiondef fibonacci n if n lt return elif n return else Calculate the sum of the previous two terms return fibonacci n fibonacci n Clarification of Intentclass Customer def init self name email self name name self email email Initialize an empty list to store the customer s orders self orders def place order self order Add the order to the list of orders self orders append order TODO and FIXME Notesdef calculate tax amount TODO Implement tax calculation logic based on current tax rates return amount def fix bug FIXME There is an index out of bounds error in this code data value data Documentation of Algorithmsdef binary search arr target Perform binary search on a sorted array Args arr List int a sorted array target int the target element to find Returns int the index of the target element or if not found left right len arr while left lt right mid left right if arr mid target return mid elif arr mid lt target left mid else right mid return External References For more information about regular expressions refer to the official documentation import repattern r d Regular expression to match one or more digits Dealing with Workaroundsdef calculate discount price discount percent if discount percent lt or discount percent gt Workaround Limit the discount percent to a valid range discount percent max min discount percent discount amount discount percent price final price price discount amount return final price Best Practices for Writing CommentsKeep Comments Updated If code changes update the comments to match Be Concise Write clear and concise comments that deliver information efficiently Explain Logic Not Syntax Focus on explaining why not what the code does Maintain Consistency Follow a consistent style for commenting Avoid Redundancy Comments should add value not repeat what s obvious from the code itself Use Meaningful Variable Names Good variable names reduce the need for excessive commenting Use Proper Grammar and Spelling Maintain professionalism by writing error free comments Review and Refactor Regularly review your code and refactor as needed to maintain clear and relevant comments |
2023-08-30 14:34:02 |
Apple |
AppleInsider - Frontpage News |
Daily deals Aug. 30: $90 off iPad mini, $70 off Apple Mighty Mouse, 35% off iRobot Roomba, more |
https://appleinsider.com/articles/23/08/30/daily-deals-aug-30-90-off-ipad-mini-70-off-apple-mighty-mouse-35-off-irobot-roomba-more?utm_medium=rss
|
Daily deals Aug off iPad mini off Apple Mighty Mouse off iRobot Roomba moreToday s top deals include off a Gigabyte Aero gaming laptop off an HP LCD monitor up to off Sony TVs and PS bundles up to off Microsoft Windows Microsoft Office Professional and more Get a Newegg gift card with an LG K TV The AppleInsider team combs the internet for amazing discounts at ecommerce stores to develop a list of unbeatable deals on trending tech gear including sales on Apple hardware TVs accessories and other gadgets We post our top finds daily to help you save money Read more |
2023-08-30 14:33:47 |
海外科学 |
NYT > Science |
Cannabis Use Disorder ‘Common’ Among Marijuana Users, Study Finds |
https://www.nytimes.com/2023/08/29/health/cannabis-marijuana-disorder.html
|
problematic |
2023-08-30 14:37:04 |
ニュース |
BBC News - Home |
Criminals to be forced to attend sentencing hearings after Lucy Letby calls |
https://www.bbc.co.uk/news/uk-66660136?at_medium=RSS&at_campaign=KARANGA
|
letby |
2023-08-30 14:29:33 |
ニュース |
BBC News - Home |
Police officer killed on railway was 'everything you want in an officer' |
https://www.bbc.co.uk/news/uk-england-nottinghamshire-66655129?at_medium=RSS&at_campaign=KARANGA
|
colleague |
2023-08-30 14:38:31 |
ニュース |
BBC News - Home |
Families stranded by air traffic control glitch put thousands on credit |
https://www.bbc.co.uk/news/business-66657176?at_medium=RSS&at_campaign=KARANGA
|
travel |
2023-08-30 14:56:33 |
ニュース |
BBC News - Home |
Lego sees profits fall as pandemic boost fades |
https://www.bbc.co.uk/news/business-66658909?at_medium=RSS&at_campaign=KARANGA
|
market |
2023-08-30 14:04:01 |
ニュース |
BBC News - Home |
Man City reach verbal agreement on £47m Nunes deal |
https://www.bbc.co.uk/sport/football/66662060?at_medium=RSS&at_campaign=KARANGA
|
matheus |
2023-08-30 14:11:31 |
コメント
コメントを投稿