Transcription of Real Python: Python 3 Cheat Sheet
1 Real Python : Python 3 Cheat SheetContents1 Introduction22 Primitives3 Numbers..3 Strings..5 Booleans..73 Collections9 Lists..9 Dictionaries..114 Control Statements12IF Statements..12 Loops..145 Functions151 Chapter 1 IntroductionPython is a beautiful language. It s easy to learn and fun, and its syntax is simple yet ele-gant. Python is a popular choice for beginners, yet still powerful enough to back some of theworld smostpopularproductsandapplicationsfromc ompanieslikeNASA,Google,Mozilla,Cisco, Microsoft, and Instagram, among others. Whatever the goal, Python s design makesthe programming experience feel almost as natural as writing in Emailyourques-tions or feedback 2 PrimitivesNumbersPython has integers and floats.
2 Integers are simply whole numbers, like 314, 500, and , meanwhile, are fractional numbers like , , You can use the typemethod to check the value of an >>>type(3)2<class 'int'>3>>>type( )4<class 'float'>5>>> pi = >>>type(pi)7<class 'float'>In the last example,piis the variable name, the can use the basic mathematical operators:1>>> 3 + 3263>>> 3 - 3405>>> 3 / >>> 3 / >>> 3 * 310911>>> 3 ** 3122713>>> num = 314>>> num = num - 115>>> print(num)16217>>> num = num + 1018>>> print(num)191220>>> num += 1021>>> print(num)222223>>> num -= 1224>>> print(num)251026>>> num *= 1027>>> num28100 There s also a special operator called modulus,%, that returns the remainder after >>> 10 % 321 Onecommonuseofmodulusisdeterminingifanum berisdivisiblebyanothernumber.
3 Forexample, we know that a number is even if it s divided by 2 and the remainder is >>> 10 % 2203>>> 12 % 240 Finally, make sure to use parentheses to enforce >>> (2 + 3) * 52253>>> 2 + 3 * 54174 StringsStrings are used quite often in Python . Strings, are just that, a string of characters - whichs anything you can type on the keyboard in one keystroke, like a letter, a number, or a recognizes single and double quotes as the same thing, the beginning and end of >>>"stringlist"2'string list'3>>> 'string list'4'string list'What if you have a quote in the middle of the string? Python needs help to recognize quotesas part of the English language and not as part of the Python >>>"I cantdothat"2'I cantdothat'3>>>"Hesaid\"no\"tome"4'He said"no"to me'Now you can also join (concatenate) strings with use of variables as >>> a ="first"2>>> b ="last"3>>> a + b4'firstlast'If you want a space in between, you can changeato the word with a space >>> a ="first"2>>> a + b3'first last'There are different string methods for you to choose from as well - likeupper(),lower(),replace(), andcount().
4 Upper()does just what it sounds like - changes your string to all uppercase >>> str = 'woah!'2>>> ()3'WOAH!'Can you guess whatlower()does?51>>> str = 'WOAH!'2>>> ()3'woah!'replace()allows you to replace any character with another >>> str = 'rule'2>>> ('r', 'm')3'mule'Finally,count()lets you know how many times a certain character appears in the >>> number_list =['one', 'two', 'one', 'two', 'two']2>>> ('two')33 You can also format/create strings with theformat() >>>"{0}isalotof{1}".format(" Python ","fun !")2' Python is a lot of fun!'6 BooleansBoolean values are simply True or False .Check to see if a value is equal to another value with two equal >>> 10 == 102 True3>>> 10 == 114 False5>>>"jack"=="jack"6 True7>>>"jack"=="jake"8 FalseTo check for inequality use!
5 =.1>>> 10 != 102 False3>>> 10 != 114 True5>>>"jack"!="jack"6 False7>>>"jack"!="jake"8 TrueYou can also test for>,<,>=, and<=.1>>> 10 > 102 False3>>> 10 < 114 True5>>> 10 >= 106 True7>>> 10 <= 118 True9>>> 10 <= 10 < 010 False11>>> 10 <= 10 < 1112 True13>>>"jack">"jack"14 False715>>>"jack">="jack"16 True8 Chapter 3 CollectionsListsLists are containers for holding >>> fruits = ['apple','lemon','orange','grape']2>>> fruits3['apple', 'lemon', 'orange', 'grape']To access the elements in the list you can use their associated index value. Just rememberthat the list starts with0, >>> fruits[2] 2orangeIf the list is long and you need to count from the end you can do that as >>> fruits[-2] 2orangeNow,sometimeslistscangetlongandyo uwanttokeeptrackofhowmanyelementsyouhave in your list.
6 To find this, use thelen() >>> len(fruits)24 Useappend()to add a new element to the end of the list andpop()to remove an elementfrom the >>> ('blueberry')2>>> fruits3['apple', 'lemon', 'orange', 'grape', 'blueberry']4>>> ('tomato')5>>> fruits6['apple', 'lemon', 'orange', 'grape', 'blueberry', 'tomato']7>>> ()8'tomato'9>>> fruits10['apple', 'lemon', 'orange', 'grape', 'blueberry']Check to see if a value exists using in the >>> 'apple'infruits2 True3>>> 'tomato'infruits4 False10 DictionariesAdictionaryoptimizeselementl ookups. Ituseskey/valuepairs,insteadofnumbersasp lace-holders. Each key must have a value, and you can use a key to look up a >>> words = {'apple': 'red','lemon': 'yellow'}2>>> words3{'apple': 'red', 'lemon': 'yellow'}4>>> words['apple']5'red'6>>> words['lemon']7'yellow'This will also work with >>> dict = {'one': 1, 'two': 2}2>>> dict3{'one': 1, 'two': 2}Output all the keys withkeys()and all the values withvalues().
7 1>>> ()2dict_keys(['apple', 'lemon'])3>>> ()4dict_values(['red', 'yellow'])11 Chapter 4 Control StatementsIF StatementsThe IF statement is used to check if a condition is , if the condition is true, the Python interpreter runs a block of statements calledtheif-block. Ifthestatementisfalse,theinterpreterskip stheifblockandprocessesanotherblock of statements called the else-block. The else clause is s look at two quick >>> num = 202>>>ifnum == 20 print('the number is 20') print('the number is not 20') number is 208>>> num = 219>>>ifnum == 20 print('the number is 20') print('the number is not 20') number is not 20 You can also add an elif clause to add another condition to check >>> num = 21122>>>ifnum == 20 print('the number is 20') > 20 print('the number is greater than 20') print('the number is less than 20')
8 Number is greater than 2013 LoopsThere are 2 kinds of loops used in Python - theforloop and are also commonly used to loop or iterate over >>> colors = ['red', 'green', 'blue']2>>> colors3['red', 'green', 'blue']4>>> print('I love ' + color) love red8I love green9I love bluewhileloops, like theforLoop, are used for repeating sections of code - but unlike aforloop, thewhileloop continues until a defined condition is >>> num = 12>>> num314>>>whilenum <= 5 print(num) num += 5 FunctionsFunctions are blocks of reusable code that perform a single (orcreate)anewfunctionthenyoucallafunctionbyaddingparametersto the function >> def multiply(num1, num2) * >>> multiply(2, 2)54 You can also set default values for >>> def multiply(num1, num2=10) * >>> multiply(2)520 Ready to learn more?
9 VisitReal Pythonto learn Python and web development. Cheers!15