投稿時間:2022-05-31 02:16:22 RSSフィード2022-05-31 02:00 分まとめ(20件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… Yahoo!ニュース、特定メディアのエンタメ記事のコメント欄を閉鎖 https://taisy0.com/2022/05/31/157473.html yahoo 2022-05-30 16:04:57
海外TECH MakeUseOf 8 Tips and Tricks to Get the Most Out of Your AirTags https://www.makeuseof.com/tips-tricks-get-most-from-airtags/ airtags 2022-05-30 17:00:13
海外TECH MakeUseOf The 11 Best WW2 Strategy Games to Immerse Yourself in War https://www.makeuseof.com/tag/ww2-strategy-games/ battles 2022-05-30 16:45:13
海外TECH MakeUseOf Why Is Someone Suing Elon Musk Over His Bid to Buy Twitter? https://www.makeuseof.com/why-shareholders-suing-elon-musk-twitter/ twitter 2022-05-30 16:38:13
海外TECH DEV Community Testing Your Python Code https://dev.to/ahmedgouda/testing-your-python-code-17dd Testing Your Python CodeWhen you write a function or a class you can also write tests for that code Testing proves that your code works as it s supposed to in response to all the input types it s designed to receive When you write tests you can be confident that your code will work correctly as more people begin to use your programs You ll also be able to test new code as you add it to make sure your changes don t break your program s existing behavior Every programmer makes mistakes so every programmer must test their code often catching problems before users encounter them Testing a FunctionTo learn about testing we need code to test Here s a simple function that takes in a first and last name and returns a neatly formatted full name def get formatted name first last Generate a neatly formatted full name full name f first last return full name title The function get formatted name combines the first and last name with a space in between to complete a full name and then capitalizes and returns the full name To check that get formatted name works let s make a program that uses this function The program names py lets users enter a first and last name and see a neatly formatted full name from name function import get formatted nameprint Enter q at any time to quit while True first input nPlease give me a first name if first q break last input Please give me a last name if last q break formatted name get formatted name first last print f tNeatly formatted name formatted name This program imports get formatted name from name function py The user can enter a series of first and last names and see the formatted full names that are generated Enter q at any time to quit Please give me a first name ahmedPlease give me a last name gouda Neatly formatted name Ahmed Gouda Please give me a first name mohammedPlease give me a last name ali Neatly formatted name Mohammed Ali Please give me a first name qWe can see that the names generated here are correct But let s say we want to modify get formatted name so it can also handle middle names As we do so we want to make sure we don t break the way the function handles names that have only a first and last name We could test our code by running names py and entering a name like Mohammed Ali every time we modify get formatted name but that would become tedious Fortunately Python provides an efficient way to automate the testing of a function s output If we automate the testing of get formatted name we can always be confident that the function will work when given the kinds of names we ve written tests for Unit Tests and Test CasesThe module unittest from the Python standard library provides tools for testing your code A unit test verifies that one specific aspect of a function s behavior is correct A test case is a collection of unit tests that together prove that a function behaves as it s supposed to within the full range of situations you expect it to handle A good test case considers all the possible kinds of input a function could receive and includes tests to represent each of these situations A test case with full coverage includes a full range of unit tests covering all the possible ways you can use a function Achieving full coverage on a large project can be daunting It s often good enough to write tests for your code s critical behaviors and then aim for full coverage only if the project starts to see widespread use A Passing TestThe syntax for setting up a test case takes some getting used to but once you ve set up the test case it s straightforward to add more unit tests for your functions To write a test case for a function import the unittest module and the function you want to test Then create a class that inherits from unittest TestCase and write a series of methods to test different aspects of your function s behavior Here s a test case with one method that verifies that the function get formatted name works correctly when given a first and last name import unittestfrom name function import get formatted nameclass NamesTestCase unittest TestCase Tests for name function py def test first last name self Do names like Mohammed Ali work formatted name get formatted name Mohammed Ali self assertEqual formatted name Mohammed Ali if name main unittest main First we import unittest and the function we want to test get formatted name At class NamesTestCase unittest TestCase we create a class called NamesTestCase which will contain a series of unit tests for get formatted name You can name the class anything you want but it s best to call it something related to the function you re about to test and to use the word Test in the class name This class must inherit from the class unittest TestCase so Python knows how to run the tests you write NamesTestCase contains a single method that tests one aspect of get formatted name We call this method test first last name because we re verifying that names with only a first and last name are formatted correctly Any method that starts with test will be run automatically when we run test name function py Within this test method we call the function we want to test In this example we call get formatted name with the arguments Mohammed and Ali and assign the result to formatted name formatted name get formatted name Mohammed Ali At self assertEqual formatted name Mohammed Ali we use one of unittest s most useful features an assert method Assert methods verify that a result you received matches the result you expected to receive In this case because we know get formatted name is supposed to return a capitalized properly spaced full name we expect the value of formatted name to be Mohammed Ali To check if this is true we use unittest s assertEqual method and pass it formatted name and Mohammed Ali The line self assertEqual formatted name Mohammed Ali says “Compare the value in formatted name to the string Mohammed Ali If they are equal as expected fine But if they don t match let me know We re going to run this file directly but it s important to note that many testing frameworks import your test files before running them When a file is imported the interpreter executes the file as it s being imported The if blockif name main unittest main looks at a special variable name which is set when the program is executed If this file is being run as the main program the value of name is set to main In this case we call unittest main which runs the test case When a testing framework imports this file the value of name won t be main and this block will not be executed When we run test name function py we get the following output Ran test in sOKThe dot on the first line of output tells us that a single test passed The next line tells us that Python ran one test and it took less than seconds to run The final OK tells us that all unit tests in the test case passed This output indicates that the function get formatted name will always work for names that have a first and last name unless we modify the function When we modify get formatted name we can run this test again If the test case passes we know the function will still work for names like Mohammed Ali A Failing TestWhat does a failing test look like Let s modify get formatted name so it can handle middle names but we ll do so in a way that breaks the function for names with just a first and last name like Mohammed Ali Here s a new version of get formatted name that requires a middle name argument def get formatted name first middle last Generate a neatly formatted full name full name f first middle last return full name title This version should work for people with middle names but when we test it we see that we ve broken the function for people with just a first and last name This time running the file test name function py gives this output E ERROR test first last name main NamesTestCase Traceback most recent call last File test name function py line in test first last name formatted name get formatted name Mohammed Ali TypeError get formatted name missing required positional argument last Ran test in sFAILED errors There s a lot of information here because there s a lot you might need to know when a test fails The first item in the output is a single E which tells us one unit test in the test case resulted in an error Next we see that test first last name in NamesTestCase caused an error Knowing which test failed is critical when your test case contains many unit tests Then we see a standard traceback which reports that the function call get formatted name Mohammed Ali no longer works because it s missing a required positional argument We also see that one unit test was run Finally we see an additional message that the overall test case failed and that one error occurred when running the test case This information appears at the end of the output so you see it right away you don t need to scroll up through a long output listing to find out how many tests failed Responding to a Failed TestWhat do you do when a test fails Assuming you re checking the right conditions a passing test means the function is behaving correctly and a failing test means there s an error in the new code you wrote So when a test fails don t change the test Instead fix the code that caused the test to fail Examine the changes you just made to the function and figure out how those changes broke the desired behavior In this case get formatted name used to require only two parameters a first name and a last name Now it requires a first name middle name and last name The addition of that mandatory middle name parameter broke the desired behavior of get formatted name The best option here is to make the middle name optional Once we do our test for names like Mohammed Ali should pass again and we should be able to accept middle names as well Let s modify get formatted name so middle names are optional and then run the test case again If it passes we ll move on to making sure the function handles middle names properly To make middle names optional we move the parameter middle to the end of the parameter list in the function definition and give it an empty default value We also add an if test that builds the full name properly depending on whether or not a middle name is provided def get formatted name first last middle Generate a neatly formatted full name if middle full name f first middle last else full name f first last return full name title In this new version of get formatted name the middle name is optional If a middle name is passed to the function the full name will contain a first middle and last name Otherwise the full name will consist of just a first and last name Now the function should work for both kinds of names To find out if the function still works for names like Mohammed Ali let s run test name function py again Ran test in sOKThe test case passes now This is ideal it means the function works for names like Mohammed Ali again without us having to test the function manually Fixing our function was easy because the failed test helped us identify the new code that broke existing behavior Adding New TestsNow that we know get formatted name works for simple names again let s write a second test for people who include a middle name We do this by adding another method to the class NamesTestCase import unittestfrom name function import get formatted nameclass NamesTestCase unittest TestCase Tests for name function py def test first last name self Do names like Mohammed Ali work formatted name get formatted name Mohammed Ali self assertEqual formatted name Mohammed Ali def test first last middle name self Do names like Ahmed Mohammed Gouda work formatted name get formatted name Ahmed Gouda Mohammed self assertEqual formatted name Ahmed Mohammed Gouda if name main unittest main We name this new method test first last middle name The method name must start with test so the method runs automatically when we run test name function py We name the method to make it clear which behavior of get formatted name we re testing As a result if the test fails we know right away what kinds of names are affected It s fine to have long method names in your TestCase classes They need to be descriptive so you can make sense of the output when your tests fail and because Python calls them automatically you ll never have to write code that calls these methods To test the function we call get formatted name with a first last and middle name formatted name get formatted name Ahmed Gouda Mohammed and then we use assertEqual to check that the returned full name matches the full name first middle and last that we expect When we run test name function py again both tests pass Ran tests in sOKGreat We now know that the function still works for names like MohammedAli and we can be confident that it will work for names like Ahmed Mohammed Gouda as well Testing a ClassWe ve just wrote tests for a single function Now you ll write tests for a class You ll use classes in many of your own programs so it s helpful to be able to prove that your classes work correctly If you have passing tests for a class you re working on you can be confident that improvements you make to the class won t accidentally break its current behavior A Variety of Assert MethodsPython provides a number of assert methods in the unittest TestCase class As mentioned earlier assert methods test whether a condition you believe is true at a specific point in your code is indeed true If the condition is true as expected your assumption about how that part of your program behaves is confirmed you can be confident that no errors exist If the condition you assume is true is actually not true Python raises an exception Below table describes six commonly used assert methods With these methods you can verify that returned values equal or don t equal expected values that values are True or False and that values are in or not in a given list You can use these methods only in a class that inherits from unittest TestCase so let s look at how we can use one of these methods in the context of testing an actual class MethodUseassertEqual a b Verify that a bassertNotEqual a b Verify that a bassertTrue x Verify that x is TrueassertFalse x Verify that x is FalseassertIn item list Verify that item is in listassertNotIn item list Verify that item is not in list A Class to TestTesting a class is similar to testing a functionーmuch of your work involves testing the behavior of the methods in the class But there are a few differences so let s write a class to test Consider a class that helps administer anonymous surveys class AnonymousSurvey Collect anonymous answers to a survey question def init self question Store a question and prepare to store responses self question question self responses def show question self Show the survey question print self question def store response self new response Store a single response to the survey self responses append new response def show results self Show all the responses that have been given print Survey results for response in self responses print f response This class starts with a survey question that you provide def init self question and includes an empty list to store responses The class has methods to print the survey question def show question self add a new response to the response list def store response self new response and print all the responses stored in the list def show results self To create an instance from this class all you have to provide is a question Once you have an instance representing a particular survey you display the survey question with show question store a response using store response and show results with show results To show that the AnonymousSurvey class works let s write a program that uses the class This program defines a question What language did you first learn to speak and creates an AnonymousSurvey object with that question The program calls show question to display the question and then prompts for responses Each response is stored as it is received When all responses have been entered the user inputs q to quit show results prints the survey results What language did you first learn to speak Enter q at any time to quit Language ArabicLanguage EnglishLanguage EnglishLanguage q Thank you to everyone who participated in the survey Survey results Arabic English EnglishThis class works for a simple anonymous survey But let s say we want to improve AnonymousSurvey and the module it s in survey We could allow each user to enter more than one response We could write a method to list only unique responses and to report how many times each response was given We could write another class to manage non anonymous surveys Implementing such changes would risk affecting the current behavior of the class AnonymousSurvey For example it s possible that while trying to allow each user to enter multiple responses we could accidentally change how single responses are handled To ensure we don t break existing behavior as we develop this module we can write tests for the class Testing the AnonymousSurvey ClassLet s write a test that verifies one aspect of the way AnonymousSurvey behaves We ll write a test to verify that a single response to the survey question is stored properly We ll use the assertIn method to verify that the response is in the list of responses after it s been stored import unittestfrom survey import AnonymousSurveyclass TestAnonymousSurvey unittest TestCase Tests for the class AnonymousSurvey def test store single response self Test that a single response is stored properly question What language did you first learn to speak my survey AnonymousSurvey question my survey store response English self assertIn English my survey responses if name main unittest main We start by importing the unittest module and the class we want to test AnonymousSurvey We call our test case TestAnonymousSurvey which again inherits from unittest TestCase The first test method will verify that when we store a response to the survey question the response ends up in the survey s list of responses A good descriptive name for this method is test store single response If this test fails we ll know from the method name shown in the output of the failing test that there was a problem storing a single response to the survey To test the behavior of a class we need to make an instance of the class At my survey AnonymousSurvey question we create an instance called my survey with the question What language did you first learn to speak We store a single response English using the store response method Then we verify that the response was stored correctly by asserting that English is in the list my survey responses self assertIn English my survey responses When we run test survey py the test passes Ran test in sOKThis is good but a survey is useful only if it generates more than one response Let s verify that three responses can be stored correctly To do this we add another method to TestAnonymousSurvey import unittestfrom survey import AnonymousSurveyclass TestAnonymousSurvey unittest TestCase Tests for the class AnonymousSurvey def test store single response self Test that a single response is stored properly question What language did you first learn to speak my survey AnonymousSurvey question my survey store response English self assertIn English my survey responses def test store three responses self Test that three individual responses are stored properly question What language did you first learn to speak my survey AnonymousSurvey question responses Arabic English Spanish for response in responses my survey store response response for response in responses self assertIn response my survey responses if name main unittest main We call the new method test store three responses We create a survey object just like we did in test store single response We define a list containing three different responses responses Arabic English Spanish and then we call store response for each of these responses Once the responses have been stored we write another loop and assert that each response is now in my survey responses for response in responses When we run test survey py again both tests for a single response and for three responses pass Ran tests in sOKThis works perfectly However these tests are a bit repetitive so we ll use another feature of unittest to make them more efficient The setUp MethodIn test survey py we created a new instance of AnonymousSurvey in each test method and we created new responses in each method The unittest TestCase class has a setUp method that allows you to create these objects once and then use them in each of your test methods When you include a setUp method in a TestCase class Python runs the setUp method before running each method starting with test Any objects created in the setUp method are then available in each test method you write Let s use setUp to create a survey instance and a set of responses that can be used in test store single response and test store three responses import unittestfrom survey import AnonymousSurveyclass TestAnonymousSurvey unittest TestCase Tests for the class AnonymousSurvey def setUp self Create a survey and a set of responses for use in all test methods question What language did you first learn to speak self my survey AnonymousSurvey question self responses Arabic English Spanish def test store single response self Test that a single response is stored properly self my survey store response self responses self assertIn self responses self my survey responses def test store three responses self Test that three individual responses are stored properly for response in self responses self my survey store response response for response in self responses self assertIn response self my survey responses if name main unittest main The method setUp does two things it creates a survey instance self my survey AnonymousSurvey question and it creates a list of responses self responses Arabic English Spanish Each of these is prefixed by self so they can be used anywhere in the class This makes the two test methods simpler because neither one has to make a survey instance or a response The method test store single response verifies that the first response in self responsesーself responses ーcan be stored correctly and test store three responses verifies that all three responses in self responses can be stored correctly When we run test survey py again both tests still pass These tests would be particularly useful when trying to expand AnonymousSurvey to handle multiple responses for each person After modifying the code to accept multiple responses you could run these tests and make sure you haven t affected the ability to store a single response or a series of individual responses When you re testing your own classes the setUp method can make your test methods easier to write You make one set of instances and attributes in setUp and then use these instances in all your test methods This is much easier than making a new set of instances and attributes in each test method When a test case is running Python prints one character for each unit test as it is completed A passing test prints a dot a test that results in an error prints an E and a test that results in a failed assertion prints an F This is why you ll see a different number of dots and characters on the first line of output when you run your test cases If a test case takes a long time to run because it contains many unit tests you can watch these results to get a sense of how many tests are passing 2022-05-30 16:26:57
海外TECH DEV Community What is GitHub Copilot ?. https://dev.to/makendrang/what-is-github-copilot--2l19 What is GitHub Copilot IntroductionGitHub Copilot is used to write code faster and with less work Individual lines and whole functions are suggested instantly by the Copilot OpenAI Codex is a new artificial intelligence system Working of GitHub CopilotOpenAI Codex was trained on publicly available source code and natural language so it understands both programming and human languages The GitHub Copilot editor extension sends your comments and code to the service which uses OpenAI Codex to suggest individual lines and whole functions GitHub Copilot has been trained on a selection of English language and source code from publicly available sources Suggestions of codeThe code it suggests may not always work or even make sense as it tries to understand your intent and to generate the best code it can Code suggested by GitHub Copilot should be carefully tested reviewed and checked out like any other code You are always in charge as a developer Exploring the developer JobsChange to the developer experience can be brought about by bringing in more intelligent systems Existing engineers will be able to be more productive reduce manual tasks and focus on interesting work GitHub Copilot has the potential to lower barriers to entry and allow more people to explore software development and join the next generation of developers Usage of Data collection in GitHub CopilotIn order to generate suggestions you must transmit part of the file you are editing to the service This context is used to make suggestions The suggestions are recorded on the Copilot This data is used to improve future versions of the system so that Copilot can make better suggestions for users in the future Users will be able to control how their data is used in the future Supported development environments areVisual Studio Code NeovimIntelliJ based IDEs like JetBrains IntelliJ IDEA Android Studio or PyCharm Gratitude for perusing my article till end I hope you realized something unique today If you enjoyed this article then please share to your buddies and if you have suggestions or thoughts to share with me then please write in the comment box 2022-05-30 16:26:30
海外TECH DEV Community Code in Rust : Guess Z Number https://dev.to/bekbrace/code-in-rust-guess-z-number-402n Code in Rust Guess Z NumberHello Coders Just thought of sharing with you this min new video for beginner to intermediate level programmers in Rust on how to code a Guess The Number in Rust Rust is fun I m studying it and in parallel I m creating YT videos on what I ve learned to help other fellow programmers who are in their first steps in learning Rust I have also a whole tutorial on Rust language make sure to check it out and if you have any comments or anything that you see is not correct please correct me as I m in favor of positive and constructive criticism And don t forget Keep Learning Be Humble Help Each Other Join Bek Brace Page bekbraceincInstagram 2022-05-30 16:06:05
海外TECH DEV Community How Keyboard Events Work in JavaScript https://dev.to/nnekajenny/how-keyboard-events-work-in-javascript-1g66 How Keyboard Events Work in JavaScript IntroductionAs a new JavaScript developer you will often encounter errors in your work One of the kinds of challenges you ll face growing as a developer is how to handle keyboard events in JavaScript In this tutorial I will try my best to explain how keyboard events work in JavaScript Let s get started if you re ready What is a Keyboard Event When a user presses a key on the Keyboard various events occur under the hood They happen when input from the keyboard is received These events describe the keyboard interaction with users In other words Keyboard Event simply indicates the user s interaction with a key on the keyboard at a low level without providing any context for that interaction For example when dealing with text input use the input event If the user is using an alternative method of entering text such as a handwriting system on a tablet or graphics tablet keyboard events may not be fired These events that occur when the user presses a key on the keyboard is what is known as the Keyboard Event Object Working with keyboard events in JavaScript Keyboard events in JavaScript as we know are used to detect the key that has been pressed They are different kinds types of keyboard events namely keydown keypress and keyup Keydown These are events triggered when a button on the keyboard has been pressed down Keypress These events are triggered when you press a key that represents a character such as a letter a number or a punctuation mark It also tells a program what character the key represents Keyup These events are triggered when a button that has been pressed on the keyboard is released Keydown and keyup uses different codes to represent a letter numbers and other keys available on the keyboard These events only tell a program what character or key has been pressed or released A key code is just a number that represents a key on the keyboard A keycode returns to the button when a number has been pressed or released ASCII keycode returns ASCII codes and works with keypress events only ASCII stands for American Standard Code for Information Interchange It s a bit character code where every single bit represents a unique character If you are using keydown or keyup you use keycodesIf you are using keypress you use ASCII key code Let s take an example This is a program to check if the a letter on the keyboard was pressed If it is it will display a little simple massage The a letter represents in the ASCII table you can find out by searching on google for keycodes Letters and numbers have keycode numbers lt DOCTYPE html gt lt html gt lt head gt lt meta charset utf gt lt meta name viewport content width device width initial scale gt lt title gt keyboard Events lt title gt lt head gt lt body gt lt script gt window addEventListener keydown checkkeyPress false function checkkeyPress key if key keyCode alert the a letter has been pressed lt script gt lt body gt lt html gt I added an event listener called checkkeypress what it does is to trigger an alert whenever the character a is pressed on the keyboard Again it is worth mentioning that the a represents in the ASCII table This is because computers don t understand alphabetical characters View the code on the browser try hitting the b c f g h etc nothing will happen But when you hit the letter a it gives you a message that the letter a key has been pressed The example we above can also be implemented for keydown and keyup events Note By holding a button and pressing other keys nothing will happen until the button is released Then it gives you a message It s triggered once the button has been released ConclusionFinally we have come to the completion of this tutorial and hopefully you got value from it Thanks for reading please hit the like clap or heart button to show some love I will see you in the next tutorial…We learned what keyboard events are and how they work We also covered the various JavaScript keyboard events such as keydown keypress and keyup If you have any question please leave it on the comments Like and share and till next time all the best About the AuthorI am Jenifer Eze an enthusiastic developer with passion for JavaScript PHP HTML amp CSS I work as a freelancer building websites for clients and love writing technical tutorials to teach others what I do I am eager to hear from you Reach me on LinkedIn Github or my website 2022-05-30 16:01:36
海外TECH DEV Community Python cheatsheet and snippets for beginners https://dev.to/llxd/python-cheatsheet-and-snippets-for-beginners-26i Python cheatsheet and snippets for beginners EPTA Forge PythonUseful Links Replit Online CompilerDownload PythonGithub Repo in PT br Declaration of Variables and Types To declare a variable just put its name followed by an followed by the value you want to assign to it my variable There are several types of variables some of them are int Integers str String Text char Character float Decimal numbers boolean True or False Basic Mathematical Operations We can do several mathematical operations with Python the most basic and most likely to be used are Addition gt Symbol Subtraction gt Symbol Multiplication gt Symbol Exponentiation gt Symbol Division gt Symbol Integer Division gt Symbol Module Rest of Division gt Booleans and comparative operatorsBooleans are values ​​that can only be True or False We also have in Python several comparative operators and they will always return booleans Greater than gt Symbol gt Less than gt Symbol lt Greater equals gt Symbol gt Less than equal to gt Symbol lt Not equal to gt Symbol Conditional LogicConditional logic allows us programmers to execute code snippets only if an initial condition is True Its structure is as follows if CONDITION things that need to be done if true elif OTHER CONDITION if you don t enter the first condition and a second condition is true else if you don t meet any of the conditions Exercise Calculation of BMI Statement Our program must calculate the BMI of a userBMIFORMULA WEIGHT HEIGHT² POSSIBLE RESULTS lt THINNESS gt AND lt NORMAL gt AND lt OVERWEIGHT gt OBESITYSpoiler Warningheight float input Enter your height weight float input Enter your weight bmi weight height if bmi lt print thinness elif bmi gt and bmi lt print normal elif bmi gt and bmi lt print overweight else print obesity ListsThe list or array is an amazing data structure for storing multiple values ​​in sequence We have several methods that can help us in our day to day with lists they are append gt Add to the end of the listremove gt Remove an item from the listinsert gt Insert at a specified positionsort gt Sort the listExamples with list list of numbers list of numbers remove shopping list banana street milk cookie shopping list append onion shopping list sort print shopping list Loops In order to be able to execute the same code several times we use loops These are for and while Examples with for and while For shopping list banana street milk cookie for purchase in shopping list print purchase for counter in range print counter for purchase in shopping list if purchase milk print I found the milk continues print purchase for purchase in shopping list if purchase milk print I found the milk break print purchase Watch out for break and continue reserved words While counter while counter lt counter counter print counter counter while True counter counter print counter if counter gt break Watch out for infinite loops too Functions In order to encapsulate our code and organize ourselves better we can separate code blocks into functionsExamples of functions def hello print Hello def hello with parameters name print Hello name hello hello with parameters Lucas Exercise Encapsulating the BMI calculation code in a functionThe idea of ​​this exercise is simply to encapsulate all the logic of the BMI exercise in a function so that we can make our code more organized Spoiler Warningheight float input Enter your height weight float input Enter your weight def calculate bmi weight height bmi weight height if bmi lt print thinness elif bmi gt and bmi lt print normal elif bmi gt and bmi lt print overweight else print obesity return bmifinal value calculate bmi weight height print final value Recursive FunctionsRecursive functions are functions that call themselves while in themselves It s a complex concept and takes time to digest and understand properly You can read more here The important thing is to remember the stop condition also called the base case which is a case of our function that will be the moment of return where the function ends so we don t end up with an infinite loop Example of recursive function def factorial number print number if number lt BASE CASE return else return number factorial number factorial Interesting libraries and cool modules DIn this section I ll introduce some modules and cool stuff that python provides for us to work with These are just a few examples of things that Python can do but in general there are many things beyond that You can check some things out here RandomnessFor randomness we normally use the random module import random random dice sides random randint print dice sides Unit testsIt is important to keep tests of our code automated ensuring that our code actually produces the desired result without having to manually check for this we can use the unittest module import randomimport unittest unittest dice sides random randint print dice sides def dice unit test dice value assert dice value lt The value of the dice obtained was greater than print The dice has the value lt D print All tests passed dice unit test dice value Normally tests are in another file which can be run separately via terminal Also there is a test driven software development method called TDD which you can learn more about here Scientific MathematicsPython is amazing with math and you can use the math module the numpy lib and the matplotlib lib to generate a lot of scientific content in terms of math Here are some examples import math math matplotlib numpy math gt Some more complicated calculationsprint math sqrt print math sin math pi print math cos math radians numpy more advanced math and amazing helper functions matplotlib plotting chartsimport matplotlib pyplot as pltimport numpy as npplt style use mpl gallery make datex np linspace y np sin x plotfig ax plt subplots ax plot x y linewidth ax set xlim xticks np arange ylim yticks np arange plt show plt savefig matplotlib png Object Oriented Programming OOP In this paradigm we use the idea of ​​a class to create new types of data structures that can help us build an application The init method is called a constructor OOP is very extensive and this section is just an idea to pop into your head OOP is widely used in games and more robust applications precisely because of its greater ease in leaving large codebases organized and with a certain ease in terms of maintenance When we create a new variable based on a class we created we call this process instantiating an object of the class Examples class Person def init self name str age int self name name self age age def hello self print Hello I m self name and I m str self age years old lucas Person name Lucas age lt lucas is an instance of personprint lucas age lucas hello class Rectangle def init self height float width float self height height self width width def area self return self height self width def perimeter self return self height self width my first rectangle Rectangle height width lt my first rectangle is an instance of Rectanglemy second rectangle Rectangle height width lt my second rectangle is another Rectangle instanceprint my first rectangle area print my second rectangle area You can check the original PT br material here Thanks for reading and if you enjoyed this kind of material leave a comment or a reaction 2022-05-30 16:01:02
Apple AppleInsider - Frontpage News Month-end AirPods deals drive prices down to $99.99 https://appleinsider.com/articles/22/05/30/month-end-airpods-deals-drive-prices-down-to-9999?utm_medium=rss Month end AirPods deals drive prices down to Memorial Day AirPods deals are in full swing with discounts of up to off and prices dipping to under Apple s entire AirPods range is on sale this weekAmazon is leading the way with the lowest AirPods prices on in ear models with AirPods dipping to and AirPods Pro with MagSafe falling to off Both offer steeper price cuts this Monday compared to last week s prices Read more 2022-05-30 16:54:55
海外TECH CodeProject Latest Articles Photino: Open Source for Building Cross-Platform Desktop Apps via .NET Core https://www.codeproject.com/Articles/5333548/Photino-Open-Source-for-Building-Cross-Platform-De building 2022-05-30 16:18:00
ニュース BBC News - Home Champions League final: France blames 'massive' ticket fraud as policing row rages https://www.bbc.co.uk/news/world-europe-61630201?at_medium=RSS&at_campaign=KARANGA pepper 2022-05-30 16:36:21
ニュース BBC News - Home Shropshire earthquake: Thuds and shudders felt in 3.8 magnitude tremor https://www.bbc.co.uk/news/uk-england-shropshire-61636678?at_medium=RSS&at_campaign=KARANGA geological 2022-05-30 16:52:18
ニュース BBC News - Home Oaks: Hollie Doyle targets 'dream' success in Epsom Classic https://www.bbc.co.uk/sport/horse-racing/61636114?at_medium=RSS&at_campaign=KARANGA classic 2022-05-30 16:11:28
ニュース BBC News - Home 'I watched from afar Russia’s latest merciless assault on Severodonetsk' https://www.bbc.co.uk/news/world-europe-61634050?at_medium=RSS&at_campaign=KARANGA x I watched from afar Russia s latest merciless assault on Severodonetsk x Quentin Sommerville describes relentless artillery bombardment in Donbas ahead of Russian forces entering Severodonetsk 2022-05-30 16:18:21
北海道 北海道新聞 チェルシーの買収成立 ドジャース共同オーナー https://www.hokkaido-np.co.jp/article/687502/ 買収 2022-05-31 01:29:00
北海道 北海道新聞 仏テレビ記者、砲撃で死亡 ウクライナ東部で取材中 https://www.hokkaido-np.co.jp/article/687501/ 記者 2022-05-31 01:27:00
北海道 北海道新聞 「おびひろ平原まつり」3年ぶり開催へ 「ホコテン」は6月19日から https://www.hokkaido-np.co.jp/article/687436/ 十勝管内 2022-05-31 01:15:34
北海道 北海道新聞 介護施設に技能実習生 中標津で初 インドネシアから3人 https://www.hokkaido-np.co.jp/article/687426/ 介護施設 2022-05-31 01:13:00
北海道 北海道新聞 「つなぐ道」未来に響け 釧路市発祥の地・元町テーマソング、6月19日披露 https://www.hokkaido-np.co.jp/article/687428/ 釧路市 2022-05-31 01:12:14

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)