投稿時間:2022-06-10 22:20:02 RSSフィード2022-06-10 22:00 分まとめ(25件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 12インチの新型「MacBook」は「MacBook Pro」シリーズの新モデルか − M2 Pro/M2 Maxチップ搭載で2023年に発売予定?? https://taisy0.com/2022/06/10/158029.html apple 2022-06-10 12:36:46
IT 気になる、記になる… 楽天モバイル、「AirPods Pro (MagSafe対応)」を値下げ https://taisy0.com/2022/06/10/158025.html airpodspromagsafe 2022-06-10 12:27:25
python Pythonタグが付けられた新着投稿 - Qiita PID制御でライントレースするときの注意点 https://qiita.com/kikou0517/items/22b52011415615bc06d4 注意点 2022-06-10 21:53:34
js JavaScriptタグが付けられた新着投稿 - Qiita 【Rails】テーブル内の特定の文字列を含む行の背景を変更する方法 https://qiita.com/mzmz__02/items/8d912140a3f43fc5eea8 rails 2022-06-10 21:29:26
AWS AWSタグが付けられた新着投稿 - Qiita AWSCompromisedKeyQuarantineというポリシー https://qiita.com/pict3/items/a744e36336cf242d689a compromisedkeyquarantine 2022-06-10 21:23:43
Ruby Railsタグが付けられた新着投稿 - Qiita 【Rails】テーブル内の特定の文字列を含む行の背景を変更する方法 https://qiita.com/mzmz__02/items/8d912140a3f43fc5eea8 rails 2022-06-10 21:29:26
技術ブログ Developers.IO 猫吸いの因果関係?繰り返し発生する問題の真因を因果ループ図で探る https://dev.classmethod.jp/articles/causal-loop/ 因果関係 2022-06-10 12:36:01
海外TECH MakeUseOf Convert HEIC Files for Free With These 7 Online Tools https://www.makeuseof.com/convert-heic-files-tools/ online 2022-06-10 12:30:13
海外TECH DEV Community Python from the word ...Go (Pt2) https://dev.to/gateremark/python-from-the-word-go-pt2-31k0 Python from the word Go Pt Basics PartHelloooo there Welcome back Wait are you new here Don t worry I got you covered Here we are breaking the flow Have you checked Python from the word Go Basics Part It s an awesome resource to first check out if you are not familiar with Python s variables and data types which comprise a few in built Python data structures They are really gonna come in handy for this section Set Lets go In the previous module we learnt about the fundamental Python data types and also covered some of the terms used when talking about code like variables statements expressions functions methods etc Most importantly we covered how to perform actions on the data types Both functions and methods for each data type Up until now we were still scratching the surface Every time we write code we wrote it line by line and hence our interpreter would go line by line running each code up to the last line gt gt gt do something gt gt gt do something gt gt gt do something gt gt gt do somethingWe are now going to incorporate the idea of running multiple lines over and over to discover the true power of programming for machines haha Hence in this section we gonna talk about the idea of conditions and conditional logic We gonna discuss more on looping and loops where we can perform actions multiple times over and over We are now going to break into a new world where instead of going from line by line in order we gonna loop over till a condition is met Conditional LogicWe previously covered Boolean variables True or False When we come to conditional logic Booleans are super important Example A person a wants to purchase a car from a company with specific conditions The car must be new The car must have a license Hence for person a to purchase the car is new Trueis licensed TrueIn conditional logic we use the if keyword If the car is new and licensed then person a can purchase it Then if any of the conditions in purchasing the car is not met person a cannot purchase the car Example Let s assume that for one to get into a specific event the person has to be old years and above Create a program to only allow old people to the event If is old True allowed to get into the event For the syntax gt gt gt is old True gt gt gt if is old gt gt gt print You are allowed to get in You are allowed to get in gt gt gt is old False gt gt gt if is old gt gt gt print You are allowed to get in nothing will be printed out Note Any code that comes after the colon in the condition is automatically indented hence run if the condition is True whereas any code that ain t indented after the condition is not under the condition and hence run separately Example gt gt gt is old True gt gt gt if is old gt gt gt print You are allowed to get in gt gt gt print Hello there You are allowed to get inHello there gt gt gt is old False gt gt gt if is old gt gt gt print You are allowed to get in gt gt gt print Hello there Hello thereWhat if when a condition is not met False we want to perform another condition Here is an example I leave my house If it s cloudy I bring an umbrella otherwise I bring sunglasses We use the keyword else Using our example of letting people in for the event we can add If is old True allowed to get into the event otherwise if is old False not allowed to get in gt gt gt is old True gt gt gt if is old gt gt gt print You are allowed to get in gt gt gt else gt gt gt print Not allowed in You are allowed to get in gt gt gt is old False gt gt gt if is old gt gt gt print You are allowed to get in gt gt gt else gt gt gt print Not allowed in Not allowed inWhat if by chance you have more than one condition Example I m in a restaurant If I want meat I order steak otherwise If I want Pasta I order spaghetti and meatballs otherwise I order salad For such cases we use the elif keyword else if Using a different example A person b wants to order chicken pizza If there is no chicken pizza the person b can order beef pizza otherwise if there is none the person b can order rice gt gt gt chicken pizza True gt gt gt beef pizza True gt gt gt if chicken pizza gt gt gt print Serve me chicken pizza gt gt gt elif beef pizza gt gt gt print Serve me beef pizza gt gt gt else gt gt gt print Serve me rice Serve me chicken pizza gt gt gt chicken pizza False gt gt gt beef pizza True gt gt gt if chicken pizza gt gt gt print Serve me chicken pizza gt gt gt elif beef pizza gt gt gt print Serve me beef pizza gt gt gt else gt gt gt print Serve me rice Serve me beef pizza gt gt gt chicken pizza False gt gt gt beef pizza False gt gt gt if chicken pizza gt gt gt print Serve me chicken pizza gt gt gt elif beef pizza gt gt gt print Serve me beef pizza gt gt gt else gt gt gt print Serve me rice Serve me rice For a person to be legalized to drive a car in public one must have a national identification card and a driving license These are two conditions that one must have to avoid being fined by the cops To develop such a program we must have both conditions True hence we can use the keyword and to check whether both conditions are True When using and both conditions must be True to execute the condition if any of them is False the program will run the elif and else part gt gt gt has id True gt gt gt has license True gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Allowed to drive gt gt gt has id False gt gt gt has license True gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Not allowed to drive gt gt gt has id True gt gt gt has license False gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Not allowed to drivePython IndentationThe interpreter in python finds meaning in the spacing hence indentation tabs and white spaces in python is essential Truthy Vs FalsyIn python whenever there s a value the interpreter recognizes that as True Otherwise when there s a zero or no value python interpreter recognizes that as False These are referred to as Truthy and Falsy values gt gt gt print bool hello gt gt gt print bool gt gt gt print bool gt gt gt print bool gt gt gt print bool None TrueTrueFalseFalseFalseAll values are considered truthy except the following which are considered falsy NoneFalsejDecimal Fraction an empty list an empty dict an empty tuple an empty strb an empty bytesset an empty setrange an empty rangeObjects for which obj bool returns Falseobj len returns Note A truthy value will satisfy the check performed by if or while statements We use truthy and falsy to differentiate from the bool values True and False Example gt gt gt has id hello gt gt gt has license gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Allowed to drive gt gt gt has id hello gt gt gt has license gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Not allowed to drive gt gt gt has id None gt gt gt has license True gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Not allowed to drive gt gt gt has id True gt gt gt has license gt gt gt if has id and has license gt gt gt print Allowed to drive gt gt gt else gt gt gt print Not allowed to drive Not allowed to driveA good though not perfect example on the use of truthy and falsy application is in forms or in keying in log in credentials When a field is set to as a required field the system expects the field to be truthy hence should not be left blank as this will lead to it being assigned falsy Ternary Operator Conditional Expression This is another way to do conditional logic This works the same as if statements but can in a way be referred to as a shortcut so can only be used in certain conditional logic In this mode we start with the condition then incorporate the if statement condition if true if condition else condition if false Example Let s use an example to determine if a user is your friend eg on Facebook whether the user can message you gt gt gt is friend True gt gt gt can message Message allowed if is friend else not allowed to message gt gt gt print can message Message allowed gt gt gt is friend True gt gt gt can message Message allowed if is friend else not allowed to message gt gt gt print can message not allowed to messageShort CircuitingPreviously we saw how to use the and keyword to validate whether both statements are True gt gt gt is friend True gt gt gt is user True gt gt gt print is friend and is user True gt gt gt is friend True gt gt gt is user False gt gt gt print is friend and is user FalseIn short circuiting the interpreter ignores one part of the condition despite it being false and returns either True or False Example using the or keyword if the first part of the condition is True the interpreter returns True without checking the second part When we use the and keyword when the the first part of the statement is False the interpreter ignores short circuits the second part and returns False An example using the or keyword gt gt gt is friend True gt gt gt is user False gt gt gt print is friend or is user True gt gt gt is friend True gt gt gt is user True gt gt gt print is friend or is user True gt gt gt is friend False gt gt gt is user True gt gt gt if is friend or is user gt gt gt print Best friends forever Best friends forever gt gt gt is friend False gt gt gt is user True gt gt gt if False or is user gt gt gt print Best friends forever gt gt gt else gt gt gt print Never friends Best friends forever gt gt gt is friend True gt gt gt is user False gt gt gt if False or is user gt gt gt print Best friends forever gt gt gt else gt gt gt print Never friends Never friends gt gt gt if True or True gt gt gt print Best friends forever gt gt gt else gt gt gt print Never friends Best friends foreverLogical OperatorsWe have looked at a few logical operators previously and and or A logical operator allows us to perform logic between two things Other logical operators include Greater than gt Less than lt Equal to Greater than or equal to gt Less than or equal to lt Not equal to Opposite of equal to not keyword Function It negates the statement Can also be written with bracket not They return either True or False gt gt gt print gt False gt gt gt print lt True gt gt gt print False gt gt gt print gt True gt gt gt print lt False gt gt gt print gt True gt gt gt print False gt gt gt print not True False gt gt gt print not True False gt gt gt print not False True gt gt gt print not False gt gt gt print not TrueNote A single equal sign symbol is used in assigning values to variables hence to use the equal to operator for comparison we use a double symbol gt gt gt print a gt b False gt gt gt print a gt A TrueBut why how is a gt b False and a gt A True In the case of strings Python compares the ASCII values of the characters Hence a ASCII value is b is and A ASCII value is that s why a is greater than A and b is greater than a optionalIn the case of print abc lt bac the result will be True Though this is a bit beyond the scope of the course This kind of comparison uses lexicographical ordering first the first two items are compared and if they differ this determines the outcome of the comparison if they are equal the next two items are compared and so on until either sequence is exhausted Lexicographical ordering for strings uses the Unicode code point number to order individual characters gt gt gt print lt lt lt True gt gt gt print lt gt lt FalseExercise Done below You have been hired by a gaming company to create a program for a game where the character has magic powers and is an expert If the character has magic and is an expert the output should be You are a master magician Otherwise if the character has magic but is not an expert the output should be At least you re getting there Else if the character has no magic the output should be You need magic powers gt gt gt print Enter Yes or No for each question gt gt gt has magic bool int input Does the character has magic gt gt gt is expert bool int input Is the character an expert gt gt gt if has magic and is expert gt gt gt print You are a master magician gt gt gt elif has magic and not is expert gt gt gt print At least you re getting there gt gt gt elif not has magic gt gt gt print You need magic powers Enter Yes or No for each question Does the character has magic Is the character an expert You are a master magician Re run the program Enter Yes or No for each question Does the character has magic Is the character an expert You need magic powers Re run the program Enter Yes or No for each question Does the character has magic Is the character an expert At least you re getting there is keywordUnlike the double equal sign which compares the equality in values is is a keyword that checks if the location in memory where one value is stored is the same as the other s Example gt gt gt print True gt gt gt print gt gt gt print gt gt gt print gt gt gt print gt gt gt print gt gt gt print TrueFalseFalseFalseTrueTrueTrue gt gt gt print True is gt gt gt print is gt gt gt print is gt gt gt print is gt gt gt print is gt gt gt print is gt gt gt print is FalseFalseFalseFalseFalseFalseFalse gt gt gt print True is True True gt gt gt print is True gt gt gt print is TrueOnce a list is created it is stored in different memory space hence print is or print is will always evaluate to False All Data Structures in Python are stored in different memory locations For LoopsLoops are one of the most powerful features of a programming languages The concept of looping allows us to run lines of code over and over till we accomplish a specific task In creating a for loop we use the keyword for Example for i in name i in the loop is a variable for each element in the loop and can be any different name for item in name for teddy in name and is created for each item in name iterable An iterable is something that can be looped over gt gt gt for item in name gt gt gt print item name gt gt gt for item in gt gt gt print item gt gt gt name Mark gt gt gt for i in name gt gt gt print i Mark gt gt gt for item in gt gt gt print item gt gt gt for item in gt gt gt print item gt gt gt for item in gt gt gt print item gt gt gt print item gt gt gt print item gt gt gt print Hello Hello gt gt gt for item in gt gt gt print item gt gt gt print item gt gt gt print item gt gt gt print item Nested for loops gt gt gt for item in gt gt gt for x in a b c gt gt gt print item x a b c a b c a b c a b c a b cIterablesAn iterable is an object or a collection that can be iterated over looped over An iterable can be a list tuple dictionary set and string This means that one can go one by one checking each item in the collection Iterating over a dictionary gt gt gt user gt gt gt name Mark gt gt gt age gt gt gt can swim False gt gt gt gt gt gt for item in user gt gt gt print item nameagecan swimWhen we iterate over a dictionary we only get the keys but can use the dictionary methods to loop over the dictionary items which includes its values One is x items where we get the key value pairs in tuples form gt gt gt user gt gt gt name Mark gt gt gt age gt gt gt can swim False gt gt gt gt gt gt for item in user items gt gt gt print item name Mark age can swim False Second is x values where we get only the values in the dictionary gt gt gt user gt gt gt name Mark gt gt gt age gt gt gt can swim False gt gt gt gt gt gt for item in user values gt gt gt print item MarkFalseThird is x keys where we get only the keys in the dictionary Works the same as iterating the dictionary without including a method gt gt gt user gt gt gt name Mark gt gt gt age gt gt gt can swim False gt gt gt gt gt gt for item in user keys gt gt gt print item nameagecan swimWhat if you want to print the items key and values in the dictionary separately We can use tuple unpacking gt gt gt user gt gt gt name Mark gt gt gt age gt gt gt can swim False gt gt gt gt gt gt for item in user items gt gt gt key value item gt gt gt print key value name Markage can swim False second way of unpacking gt gt gt user gt gt gt name Mark gt gt gt age gt gt gt can swim False gt gt gt gt gt gt for key value in user items gt gt gt print key value name Markage can swim FalseExercise Done below Building a simple counter to loop over a list and sum up the items in the list The list is provided below my list gt gt gt my list gt gt gt sum gt gt gt for i in my list gt gt gt sum i gt gt gt print sum range in loopsIt returns an object that produces a sequence of integers from the start which is inclusive to stop exclusive gt gt gt print range range gt gt gt print range range We can iterate a range of numbers gt gt gt for num in range gt gt gt print num gt gt gt for i in range gt gt gt print i gt gt gt for i in range gt gt gt print my name is my name ismy name ismy name ismy name ismy name ismy name ismy name ismy name ismy name ismy name isWhen one does not want to use a variable name in the loop the person can use an underscore gt gt gt for in range gt gt gt print gt gt gt for in range gt gt gt print my name is my name ismy name ismy name ismy name ismy name ismy name ismy name ismy name ismy name ismy name is start stop stepover in range gt gt gt for in range gt gt gt print gt gt gt for in range gt gt gt print nothing will be printed out gt gt gt for in range gt gt gt print gt gt gt for in range gt gt gt print gt gt gt for in range gt gt gt print list range enumerate It returns each item in the iterable with its index in tuple form gt gt gt for i in enumerate mark gt gt gt print i m a r k gt gt gt for i j in enumerate mark gt gt gt print i j m a r k gt gt gt for i char in enumerate list range gt gt gt if char gt gt gt print f The index of is i The index of is gt gt gt for i j in enumerate Mark gt gt gt if j r gt gt gt print f The index of r is i The index of r is While LoopsIn While loop a command is run when a specific condition is met till the condition becomes false after constant looping eg gt gt gt i gt gt gt while lt gt gt gt print i will run infinitely for will always be less than gt gt gt i gt gt gt while i lt gt gt gt i gt gt gt print i break command in while loopWhen a break keyword is used in while loop it breaks the loop after the first run gt gt gt i gt gt gt while lt gt gt gt print i gt gt gt breakusing else in while loop gt gt gt i gt gt gt while i lt gt gt gt i gt gt gt print i gt gt gt else gt gt gt print Done with work Done with work gt gt gt i gt gt gt while i gt gt gt gt i gt gt gt print i gt gt gt else gt gt gt print Done with work Done with workThe else block in while loop will only execute when there is no break statement in the while loop gt gt gt i gt gt gt while i lt gt gt gt i gt gt gt print i gt gt gt break gt gt gt else gt gt gt print Done with work How for loops and while loops relates gt gt gt my list gt gt gt for item in my list gt gt gt print item gt gt gt my list gt gt gt i gt gt gt while i lt len my list gt gt gt print my list i gt gt gt i While loops are more flexible for we have a conditional statement but for loops are simpler With the while loop we have to remember to hope the loop in the course or use a break statement to avoid getting an infinite loop gt gt gt while True gt gt gt input Say something gt gt gt breakSay something hi gt gt gt while True gt gt gt response input Say something gt gt gt if response bye gt gt gt breakSay something hi Say something hi Say something bye break continue passThe break keyword breaks out of the loop The continue keyword continues the loop till the condition is met without running the indented line s below it The pass keyword is used to pass to the next line It is mainly used as a placeholder gt gt gt my list gt gt gt for item in my list gt gt gt continue gt gt gt print item nothing will be printed gt gt gt i gt gt gt while i lt len my list gt gt gt i gt gt gt continue gt gt gt print my list i nothing will be printed gt gt gt my list gt gt gt for item in my list gt gt gt pass gt gt gt i gt gt gt while i lt len my list gt gt gt print my list i gt gt gt i gt gt gt passExercise Done below Our First GUI Exercise Basic Version In this exercise we are going to simulate what the computer does when we have a graphical user interface GUI Assuming below are the pixels of an image Christmas Tree in a nested list picture You gonna loop over the list s and the moment you encounter a zero you will display on the screen an empty space but when you encounter a one you gonna simulate a pixel hence display a star For this challenge we will include a new special print parameter option known as end By default the print function ends with a newline when we print anything we get a new line for the next statement Passing the whitespace to the end parameter end indicates that the end character has to be identified by whitespace and not a newline which we will use for in this case we don t want a new line after printing each and every character end String appended after the last value Without using the end parameter gt gt gt picture gt gt gt for row in picture gt gt gt for pixel in row gt gt gt if pixel gt gt gt print gt gt gt else gt gt gt print After using the end parameter to include a blank space empty string after the end of the line gt gt gt picture gt gt gt for row in picture gt gt gt for pixel in row gt gt gt if pixel gt gt gt print end gt gt gt else gt gt gt print end After each loop of the pixels we also wanna include a blank space empty string so that each single loop will be by default in each line gt gt gt picture gt gt gt for row in picture gt gt gt for pixel in row gt gt gt if pixel gt gt gt print end gt gt gt else gt gt gt print end gt gt gt print Exercise Done below Finding Duplicates in a list using loops and conditional logic Note No use of sets in this case After finding the duplicate values the program should print the duplicate values gt gt gt some list a b c b d m n n gt gt gt duplicates gt gt gt for value in some list gt gt gt if some list count value gt gt gt gt if value not in duplicates gt gt gt duplicates append value gt gt gt print duplicates b n FunctionsUp until now we ve worked with python functions like print list input function and many more that allowed us to perform actions on our data types We can also create our own functions and use them on our program When creating functions in Python we use the def define keyword We then give our function a name defining the function as we do with variables then we add the brackets and a colon at the end For one to use a function one has to call it gt gt gt def say hello defining the function gt gt gt print Hellooo gt gt gt say hello calling the functionHelloooFunctions are super useful because the work under the principle of DRY Don t Repeat Yourself because instead of the programmer re typing the code each and every time the programmer can just call the function as many times as possible to run a specific block of code Example Using our Christmas tree example above we can use the function to output it multiple of times gt gt gt picture gt gt gt def show tree gt gt gt for row in picture gt gt gt for pixel in row gt gt gt if pixel gt gt gt print end gt gt gt else gt gt gt print end gt gt gt print gt gt gt show tree gt gt gt show tree gt gt gt show tree The function is stored in a specific place in memory once created gt gt gt def say hello gt gt gt print Hellooo gt gt gt print say hello lt function say hello at xBBE gt The characters xBBE show the memory location where the function has been stored Arguments Vs Parameters in functions The power of functions beyond it being able to be called multiple times is the ability of the programmer to make it dynamic In its brackets one can pass parameters The values which are defined at the time of the function prototype or definition of the function are called as parameters When a function is called the actual values that are passed during the call are called as arguments gt gt gt def say hello name age name and age are parameters gt gt gt print f Hello name You re age yrs gt gt gt say hello Mark Mark and are arguments Hello Mark You re yrs gt gt gt def say hello name age gt gt gt print f Hello name You re age yrs gt gt gt say hello Mark gt gt gt say hello Emily gt gt gt say hello Dan Hello Mark You re yrsHello Emily You re yrsHello Dan You re yrsThe above arguments are referred to as positional arguments because they are required to be in the proper position gt gt gt def say hello name age gt gt gt print f Hello name You re age yrs gt gt gt say hello Mark Hello You re Mark yrsDefault Parameters and Keyword ArgumentsKeyword arguments as opposed to positional arguments allow us to not worry about the position hence the arguments can be in any position However this makes the code more complicated and not a proper practice way gt gt gt def say hello name age gt gt gt print f Hello name You re age yrs gt gt gt say hello age name Mark Hello Mark You re yrsDefault parameters allow us to give constant values as we define the function Default parameters only work when no values have been passed as arguments to the function gt gt gt def say hello name Emily age gt gt gt print f Hello name You re age yrs gt gt gt say hello Hello Emily You re yrs gt gt gt def say hello name Emily age gt gt gt print f Hello name You re age yrs gt gt gt say hello Dan gt gt gt say hello Hello Dan You re yrsHello Emily You re yrs gt gt gt def say hello name Emily age gt gt gt print f Hello name You re age yrs gt gt gt say hello Irene Hello Irene You re yrsReturn StatementThis is a keyword in python mostly used together with functions Functions always have to return something and when there is no return statement the function will always return None gt gt gt def sum num num gt gt gt num num gt gt gt print sum NoneWhen the return statement is used gt gt gt def sum num num gt gt gt return num num gt gt gt print sum A function should do one thing really well and or should return something This however doesn t mean that the code only has to be one line gt gt gt def sum num num gt gt gt return num num gt gt gt total sum gt gt gt print sum total gt gt gt def sum num num gt gt gt return num num gt gt gt print sum sum gt gt gt def sum num num gt gt gt def another func num num gt gt gt return num num gt gt gt total sum gt gt gt print total Nonedef sum num num def another func num num return num num return another functotal sum print total lt function sum lt locals gt another func at xBFB gt gt gt gt def sum num num gt gt gt def another func num num gt gt gt return num num gt gt gt return another func gt gt gt total sum gt gt gt print total gt gt gt def sum num num gt gt gt def another func num num gt gt gt return num num gt gt gt return another func num num gt gt gt total sum gt gt gt print total To avoid confusion when working with more than one function function in a function it is advisable to use different names for the parameter gt gt gt def sum num num gt gt gt def another func n n gt gt gt return num num gt gt gt return another func num num gt gt gt total sum gt gt gt print total Note A return keyword automatically exits the function in that any code to output below the return statement is never run gt gt gt def sum num num gt gt gt def another func n n gt gt gt return num num gt gt gt return another func num num gt gt gt return gt gt gt print Hello gt gt gt total sum gt gt gt print total Methods Vs FunctionsExamples of inbuilt functions in python include list print max min input We ve also found out that we can use the keyword def to define our own functions When using methods we use the dot notation Methods are owned by whatever is to the left of the dot be it strings tuples integers etc Methods of the fundamental data types have been covered in the previous module where all the data types have been covered too Both Functions and Methods allow us to take actions on the data types None Similar to functions we can also build our own methods which will be explained in details in the next module as we discuss on classes and objects DocstringsThis is using triple quotes to comment multiple lines It can also be used in functions to give more info about a function It works the same as the more info about a function provided by the developer environments when typing the inbuilt functions Help functionUsed to give more info about a function When a docstring is passed in a function the help function returns the docstring gt gt gt help print print print value sep end n file sys stdout flush False Prints the values to a stream or to sys stdout by default Optional keyword arguments file a file like object stream defaults to the current sys stdout sep string inserted between values default a space end string appended after the last value default a newline flush whether to forcibly flush the stream gt gt gt def test a Info This is a function that prints the testing data print a gt gt gt help test test a Info This is a function that prints the testing data We can also use the dunder method Magic method will get into it later in the course to get more info on a function gt gt gt def test a Info This is a function that prints the testing data print a gt gt gt print test doc Info This is a function that prints the testing data Docstrings are really useful to add comments and definition to a function to enable other people understand what your function does without searching through your multiple files Writing clean code gt gt gt def is even num gt gt gt if num gt gt gt return True gt gt gt elif num gt gt gt return False gt gt gt print is even TrueVs gt gt gt def is even num gt gt gt if num gt gt gt return True gt gt gt else gt gt gt return False gt gt gt print is even TrueVs gt gt gt def is even num gt gt gt if num gt gt gt return True gt gt gt return False gt gt gt print is even TrueVs gt gt gt def is even num gt gt gt return num gt gt gt print is even True args and kwargs args arguments kwargs Keyword argumentsIn function we have special characters called args and kwargs gt gt gt def super func num gt gt gt return sum num gt gt gt super func returns an error because the function should take just positional argument but we gave args adding an asterisk at the start of the parameter allows one to pass more than one positional argument gt gt gt def super func num gt gt gt print num gt gt gt return sum num gt gt gt super func gt gt gt def super func num gt gt gt print num gt gt gt return sum num gt gt gt super func gt gt gt def super func num gt gt gt return sum num gt gt gt print super func kwargs allows us to use keyword arguments It returns a dictionary of the values gt gt gt def super func num kwargs gt gt gt print kwargs gt gt gt super func num num num num gt gt gt def super func num kwargs gt gt gt print kwargs gt gt gt total gt gt gt for items in kwargs values gt gt gt total items gt gt gt return sum num total gt gt gt print super func num num num num There s a rule of positioning when one is using parameters default parameters args and kwargs parameters args default parameters kwargs gt gt gt def super func name num greet hi kwargs gt gt gt print kwargs gt gt gt total gt gt gt for items in kwargs values gt gt gt total items gt gt gt return sum num total gt gt gt print super func Andy num num num num Exercise Done below Create a function called highest even that is passed a list of integers and returns the highest even integer The list is given below my list gt gt gt my list gt gt gt even list gt gt gt def highest even gt gt gt for i in my list gt gt gt if i gt gt gt even list append i gt gt gt even list sort gt gt gt print even list gt gt gt print even list gt gt gt highest even gt gt gt my list gt gt gt even list gt gt gt def highest even gt gt gt for i in my list gt gt gt if i gt gt gt even list append i gt gt gt even list sort gt gt gt print even list gt gt gt highest even We can also use the max keyword to return the maximum even number gt gt gt my list gt gt gt def highest even gt gt gt even list gt gt gt for i in my list gt gt gt if i gt gt gt even list append i gt gt gt return max even list gt gt gt print highest even Walrus Operator The walrus operator is a new feature in python It is explained in depths in the python documentation It is used to assign values to variables as part of a larger expression eg in if statements in while loops etc gt gt gt a Helloooooooooooooooo gt gt gt if len a gt gt gt gt print f Too long len a elements Too long elementsUsing the walrus operator gt gt gt a Helloooooooooooooooo gt gt gt if n len a gt gt gt gt print f Too long n elements Too long elementsWalrus Operator while loop gt gt gt a Helloooooooooooooooo gt gt gt while n len a gt gt gt gt print n gt gt gt a a gt gt gt print a H gt gt gt a Helloooooooooooooooo gt gt gt while n len a gt gt gt gt print a gt gt gt a a gt gt gt print a HellooooooooooooooooHelloooooooooooooooHellooooooooooooooHelloooooooooooooHellooooooooooooHelloooooooooooHellooooooooooHelloooooooooHellooooooooHelloooooooHellooooooHelloooooHellooooHelloooHellooHelloHellHelHeHScope What variables do I have access to gt gt gt print name returns an error NameError name name is not definedOnce a variable is not defined one cannot have access to it A variable with a global scope is a variable that can be accessed by anybody in the file and can be used anywhere in the conditional logic in the while loop in a function etc gt gt gt total gt gt gt print total total has a global scopeA variable with a functional scope is a variable that can only be accessed in within the function gt gt gt def some func gt gt gt total gt gt gt print total returns an error NameError name total is not defined gt gt gt def some func gt gt gt total gt gt gt print total Scope Rules What would you expect the output of the code below to be gt gt gt a gt gt gt def confusion gt gt gt a gt gt gt return a gt gt gt print a gt gt gt print confusion The output will be and This is because the first print function print a outputs the value stored in the a with the global scope while the second print function print confusion returns the value stored in the a variable in the function The a is not modified after the function because of scope Rules the interpreter follow in scope Local Scope Scope within the functional scope gt gt gt a gt gt gt def confusion gt gt gt a gt gt gt return a gt gt gt print confusion gt gt gt print a gt gt gt a gt gt gt def confusion gt gt gt return a gt gt gt print confusion gt gt gt print a Parent Local scope Works where there s a function within a function gt gt gt a gt gt gt def parent gt gt gt a gt gt gt def confusion gt gt gt return a gt gt gt return confusion gt gt gt print parent gt gt gt print a Global scope gt gt gt a gt gt gt def parent gt gt gt def confusion gt gt gt return a gt gt gt return confusion gt gt gt print parent gt gt gt print a Built in python functions gt gt gt a gt gt gt def parent gt gt gt def confusion gt gt gt return sum gt gt gt return confusion gt gt gt print parent gt gt gt print a lt built in function sum gt Note Parameters are part of the local scope gt gt gt b gt gt gt def confusion b gt gt gt print b gt gt gt confusion gt gt gt b gt gt gt def confusion b gt gt gt print b gt gt gt confusion b Global keyword What if one wants to refer to a global variable while in the function without creating a new variable Example gt gt gt total gt gt gt def count gt gt gt total gt gt gt return total gt gt gt print count returns an error UnboundLocalError local variable total referenced before assignmentThe error occurs because the function count does not recognize total Hence we have to add a variable total in the function gt gt gt total gt gt gt def count gt gt gt total gt gt gt total gt gt gt return total gt gt gt print count To avoid recreating another variable in the function we can use the global keyword to tell the interpreter that we want to use the global scope on the variable in the function gt gt gt total gt gt gt def count gt gt gt global total gt gt gt total gt gt gt return total gt gt gt print count gt gt gt total gt gt gt def count gt gt gt global total gt gt gt total gt gt gt return total gt gt gt count gt gt gt count gt gt gt print count Dependency injection A simplified version of global scope gt gt gt total gt gt gt def count total gt gt gt total gt gt gt return total gt gt gt print count total gt gt gt total gt gt gt def count total gt gt gt total gt gt gt return total gt gt gt print count count count total Nonlocal KeywordThis is a new keyword feature in python and its used to refer to the parent local scope gt gt gt def outer gt gt gt x local gt gt gt def inner gt gt gt nonlocal x gt gt gt x nonlocal gt gt gt print inner x gt gt gt inner gt gt gt print outer x gt gt gt outer inner nonlocalouter nonlocal Without the nonlocal keyword gt gt gt def outer gt gt gt x local gt gt gt def inner gt gt gt x nonlocal gt gt gt print inner x gt gt gt inner gt gt gt print outer x gt gt gt outer inner nonlocalouter localWhy do we need scope Why not just have every variable with a global scope so that everything has access to everything Machines don t have infinite power memory hence we need to be cautious of the resources we use Scope is a good demonstration of this Eg When a function is run we create one memory space hence when for instance we use nonlocal we instead of creating another memory space we use an existing one Hurraay We come to the end of the second module Hope you ve learnt a lot and ready to implement the skills in different fields As we wrap up here is a simple exercise for you to try before checking the answer done below gt gt gt age input What is your age gt gt gt if int age lt gt gt gt print Sorry you are too young to drive this car Powering off gt gt gt elif int age gt gt gt gt print Powering On Enjoy the ride gt gt gt else gt gt gt print Congratulations on your first year of driving Enjoy the ride Given the code above perform the actions below on the code Wrap the above code in a function called checkDriverAge that whenever you call this function you will get prompted for age Instead of using the input make the checkDriverAge function accept an argument of age so that if you enter eg checkDriverAge it returns Powering On Enjoy the ride Make the default age set to if no argument is given Answer gt gt gt def checkDriverAge age gt gt gt if int age lt gt gt gt print Sorry you are too young to drive this car Powering off gt gt gt elif int age gt gt gt gt print Powering On Enjoy the ride gt gt gt else gt gt gt print Congratulations on your first year of driving Enjoy the ride gt gt gt checkDriverAge Sorry you are too young to drive this car Powering offWhat next Let s meet in the next module Advanced Python Till next time bye bye 2022-06-10 12:37:07
海外TECH DEV Community What is react? https://dev.to/rathoremanpreet/what-is-react-151l What is react Simplest meaningA JavaScript library for building user interfacesReact is a javascript library which is used for building user interfaces It contains three important thingsDeclarativeComponent BasedLearn Once Write Anywhere DeclarativeReact makes it painless to create interactive UIs For example If we want to add a tag to the other tag so we have to write code like this in javascriptfirst get the id or class name of another tagthen put the tag in it with the help of innerHTMLbut in react we don t need this kind of stuffJust create a function like a javascript functionAnd return the tag that s it And everything is maintained by the react Now you have created the component what is a component we will talk about it in the component section Component BasedComponent means dividing the big UI code into the small UI block of codeFor examplelet s say we have a home page where have put all the code in it like buttons navbar sidebar body and so on right Suppose we created a new page like about us where we want to add a button So what we do is just copy the button code from the home page and past it on the about us pageBut there is a problem if we change the colour of the button so we have to change the button colour on every pageSo this problem is resolved by COMPONENTLet s take the previous example how does the component help us to solve this problem First it creates a separate file like button js Component for the button code OkThen it just links the button js file with a home page and about us pageSo if any changes occur in the button so we just need to change the button file and then all the files which import it their button will change Learn Once Write Anywherethis one means reusabilityRight Now code is more reusablewe can take the button example create a new button component and put the button code into it And use this component in every file where we want to add button code this is reusable 2022-06-10 12:30:42
海外TECH DEV Community Create NFT Market Place without any libraries https://dev.to/sananayab/create-nft-market-place-without-any-libraries-3hj9 Create NFT Market Place without any librariesCreate NFT Market Place without any libraries like openZeppelin part Create smart contracts To develop on the blockchain we need a blockchain environment like TruffleTruffle is the most popular development framework for Ethereum with a mission to make your life a whole lot easier To Install it I consider you already have npm in your machine just run the following command npm install truffle gafter the truffle is installed successfully we still need a personal blockchain for Ethereum development that provides us with a development blockchain environment with fake accounts with a ETH balance so we can develop contracts and deploy them and run tests you can download it easily from here After that install it on your system and open it then click on QUICKSTARTto start a blockchain development you will getNow after we installed the requirements we need to init our project Open the terminal and run truffle int yNow let s take a look at the project structure we ve truffle config jsand that s the configuration of our project let s make some changes to it go to the networks and add the network development to work with Ganache Ganache works with the following network info develop host Localhost port Standard Ethereum port for Ganache network id Ganache network Id we named the network develop now we have the test folder to test our contracts and the migrations folder for the contract deployment and lastly in the contracts folder that includes the contract files we ll find the default file named Integration sol and that s for the truffle integration so do not delete it now create a file in the contract folder name it CreateNFT sol we ll work with the solidity compiler with the version more than or equal to and less just put the following lines SPDX License Identifier MITpragma solidity gt lt now create a contract name it CreateNFT SPDX License Identifier MITpragma solidity gt lt contract CreateNFT uint private tokensIds mapping uint gt string private tokenURIs function createTokenURI string memory tokenURI public returns uint string memory uint currentTokenId tokensIds length setTokenURI currentTokenId tokenURI tokensIds push currentTokenId return currentTokenId tokenURI function setTokenURI uint tokenId string memory tokenURI public tokenURIs tokenId tokenURI function getTokenURI uint tokenId public view returns string memory string memory tokenURI tokenURIs tokenId return tokenURI Let s discuss this file Here we create tokens Ids uint array to store them in the blockchain and the same thing about the URIs but here we created it with the mapping function because of the string type Then we three functions two to create the URI Token and the second one is to fetch the token URI by the token id the createTokenURI function is a function that we ll create the token for the passed URI in this function we just decrease the number of the ids and then pass the current id to the next function setTokenURI bypassing the current id and the URI and it ll refer the id to the URI and that s it We can now call to get our URI by passing the id to the last function getTokenURI id Now let s call these functions first we need to deploy our contract Go to The migration folder and create a folder name it nft creator jsand put the following code const TicketNFT artifacts require TicketNFT module exports function deployer deployer deploy TicketNFT now run the following command at the root of our project truffle migrate compile all reset network developwe ll migrate then deploy our contract at the network develop that works with ganache if everything goes fine you ll notice that a new folder created named build now our contract has been built we need now to start development on the blockchain to do that just run truffle developnow in we need to get an instance for our contract in the terminal runCreateNFT deployed then instance gt app instance get an instance from our contractto create a token for a URI just call the createTokenURI and pass the URI like so app createTokenURI the resultafter we call the function we created the token and we spent some Gas also when we deployed our contract as you can see below and created a new block after we call the function we created the token and we spent some Gas also when we deployed our contract as you can see below and created a new block and get the TX hash code and the transactionHash gasUsed etc now let s retrieve our URI by passing the token Id we know we created just one token so logically we ve can call it with the tokenURIs now let s call the function getTokenURIapp getTokenURI and Voila we Got it again now we can fetch our data from the IPFS In the next part we ll create an NFT market item and pass its data like the pricing the owner the seller etc 2022-06-10 12:28:51
Apple AppleInsider - Frontpage News iOS 16 deep-dive, iPhone custom Lock Screens, and iPad Stage Manager, on the AppleInsider podcast https://appleinsider.com/articles/22/06/10/deep-dives-into-ios-16-iphone-custom-lock-screens-and-ipad-stage-manager-on-the-appleinsider-podcast?utm_medium=rss iOS deep dive iPhone custom Lock Screens and iPad Stage Manager on the AppleInsider podcastIt s time to go in depth on new features across iOS and macOS Ventura plus Stage Manager in iPadOS and just what desktop class apps could mean on M iPads all on the new AppleInsider podcast Apple s iOS contains numerous updates to Messages Wallet and notably the ability to customize the iPhone lock screen In the current beta custom widgets on the lock screen are iPhone only though and the iPad lock screen has yet to gain the same features There are though many features that Apple failed to mention at the WWDC keynote including the ability to finally use Face ID on iPhone in landscape mode Also only alluded to was how deleted Messages threads are placed in a recently deleted area for days and the ability to edit or undo iMessages is limited to minutes after being sent Read more 2022-06-10 12:43:48
海外TECH Engadget The Beats Fit Pro are back on sale for $180 https://www.engadget.com/the-beats-fit-pro-are-back-on-sale-for-180-124438229.html?src=rss The Beats Fit Pro are back on sale for If you missed the previous sale in April you have another chance to pick up the Beats Fit Pro wireless earbuds for less right now Amazon has them for which is percent off and one of the best prices we ve seen We saw the buds drop to around in January of this year but it was only for a brief period of time and that sale price hasn t returned since That makes the current sale even more appealing if you ve had your eye on Beats latest buds Buy Beats Fit Pro at Amazon Being owned by Apple has its perks and it shows in the Beats Fit Pro These buds have most of the convenient features that AirPods do but with a more comfortable and secure design They look similar to the Beats Studio Buds with the exception of the flexible wingtip that helps them fit better into different ear shapes and stay put during intense workouts Their design is also IPX rated so sweat won t bother them either These buds also impressed with their sound quality and ANC They pumped out audio with depth and clarity plus punchy bass that never overpowered and the buds support Adaptive EQ and spatial audio ANC is good as well and while it s not as strong as that from Bose or Sony it gets the job done and will sufficiently block out surrounding noises Inside the Beats Fit Pro is Apple s H chip which powers things like one touch pairing Find My support and hands free Siri access Aside from Apple s own AirPods Beats earbuds like these are solid options for iPhone owners since they re designed to works seamlessly with all Apple devices As for battery life Beats estimates six hours of listening time with ANC turned on and you ll get up to hours of total use time when you employ the extra charges provided by the buds case Our biggest gripes with the Beats Fit Pro are is lack of wireless charging capabilities and the fact that some features are iOS exclusive however the latter is to be expected But Android users aren t totally out of luck the buds have their own dedicated Android app with supports fast pairing control customization and a battery status indicator Follow EngadgetDeals on Twitter for the latest tech deals and buying advice 2022-06-10 12:44:38
海外TECH Engadget Engadget Podcast: Apple's WWDC 2022 and the Surface Laptop Go 2 https://www.engadget.com/engadget-podcast-wwdc-2022-macbook-air-m2-macos-ventura-ios-16-watchos-9-surface-laptop-go-2-123049500.html?src=rss Engadget Podcast Apple x s WWDC and the Surface Laptop Go This week Cherlynn and guest co host Sam dive into all the announcements from WWDC as well as what it was like to cover the event both remotely and in person How did we and our audience feel about things that we did and didn t see at the show Plus Sam tells us more about Microsoft s new Surface Laptop Go plus news on regulations around USB C and our right to repair our devices Listen below or subscribe on your podcast app of choice If you ve got suggestions or topics you d like covered on the show be sure to email us or drop a note in the comments And be sure to check out our other podcasts the Morning After and Engadget News Engadget ·Apple s WWDC and the Surface Laptop Go Subscribe iTunesSpotifyPocket CastsStitcherGoogle PodcastsTopicsWWDC The new M MacBook Air and inch MacBook Pro New features in macOS Ventura What s coming to iOS and iPadOS Big changes to the iOS lock screen WatchOS Surface Laptop Go hands on The EU reaches deal to use USB C to charge all devices New York state passed a Right to Repair bill Working on Pop culture picks Video livestreamCreditsHosts Cherlynn Low and Sam RutherfordProducer Ben EllmanLivestream producers Julio Barrientos Luke BrooksGraphics artists Luke Brooks Brian OhMusic Dale North and Terrence O Brien 2022-06-10 12:30:49
海外科学 NYT > Science Blood Tests That Detect Cancers Create Risks for Those Who Use Them https://www.nytimes.com/2022/06/10/health/cancer-blood-tests.html Blood Tests That Detect Cancers Create Risks for Those Who Use ThemThe tests screen for cancers that often go undetected but they are expensive and some experts worry they could lead to unnecessary treatments without saving patients lives 2022-06-10 12:05:05
金融 RSS FILE - 日本証券業協会 新規公開に際して行う株券の個人顧客への配分状況 https://www.jsda.or.jp/shiryoshitsu/toukei/shinkikoukai/index.html 新規公開 2022-06-10 13:00:00
ニュース BBC News - Home Rwanda asylum plan: Home Office fights bid to block flight https://www.bbc.co.uk/news/uk-61758828?at_medium=RSS&at_campaign=KARANGA interest 2022-06-10 12:01:31
ニュース BBC News - Home Boy, 14, stabbed to death and mother hurt in Manchester https://www.bbc.co.uk/news/uk-england-manchester-61757631?at_medium=RSS&at_campaign=KARANGA manchester 2022-06-10 12:25:12
ニュース BBC News - Home Families of condemned Britons Aiden Aslin and Shaun Pinner call for help https://www.bbc.co.uk/news/uk-61754684?at_medium=RSS&at_campaign=KARANGA ukraine 2022-06-10 12:30:07
ニュース BBC News - Home Billy Bingham: Former Northern Ireland manager dies at the age of 90 https://www.bbc.co.uk/sport/football/61757384?at_medium=RSS&at_campaign=KARANGA finals 2022-06-10 12:25:42
ニュース BBC News - Home Sergio Perez fastest in Azerbaijan Grand Prix first practice https://www.bbc.co.uk/sport/formula1/61761633?at_medium=RSS&at_campaign=KARANGA azerbaijan 2022-06-10 12:10:23
ニュース BBC News - Home Worried households cut back on energy and food https://www.bbc.co.uk/news/business-61757183?at_medium=RSS&at_campaign=KARANGA foodofficial 2022-06-10 12:55:21
北海道 北海道新聞 運動会「脱マスク」戸惑う現場 文科省方針に釧根の小学生や保護者 https://www.hokkaido-np.co.jp/article/692119/ 根室管内 2022-06-10 21:07:00
北海道 北海道新聞 釧根管内59人感染 新型コロナ https://www.hokkaido-np.co.jp/article/692118/ 根室管内 2022-06-10 21:06:00
北海道 北海道新聞 巡査が酔って学校侵入、訓戒処分 宮崎県警、懲戒と刑事処分なし https://www.hokkaido-np.co.jp/article/692116/ 刑事処分 2022-06-10 21:02:00

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)