Transcription of The Python Guide for Beginners - renanmf.com
1 The Python Guide for BeginnersRenan Moura2 The Python Guide for Beginners1 Preface2 Introduction to Python3 Installing Python 34 Running Code5 Syntax6 Comments7 Variables8 Types9 Typecasting10 User Input11 Operators12 Conditionals13 Lists14 Tuples15 Sets16 Dictionaries17 while Loops18 for Loops19 Functions20 Scope21 List Comprehensions22 Lambda Functions23 Modules324 if __name__ == '__main__'25 Files26 Classes and Objects27 Inheritance28 Exceptions29 Conclusion41 PrefacePython has become one of the fastest-growing programming languagesover the past few only it is widely used, it is also an awesome language to tackle if youwant to get into the world of Python Guide for Beginners allows you to learn the core of thelanguage in a matter of hours instead of intention of this book is not to be an exhaustive manual oneverything Python has to offer as one of the major languages in focus on what you will need to use most of the time to solve most of theproblems as a deeply believe that you should be able to learn the core of anyprogramming language and then go from there to dive into specifics anddetails as 'm Renan Moura and I write about Software Development can also find me as @renanmouraf on:Twitter.
2 Introduction to PythonPython was created in 1990 by Guido Van Rossum in of the objectives of the language was to be accessible to was also designed to be a second language for programmers tolearn due to its low learning curve and ease of runs on Mac, Linux, Windows, and many other is:Interpreted: it can execute at runtime, and changes in a programare instantly perceptible. To be very technical, Python has acompiler. The difference when compared to Java or C++ is howtransparent and automatic it is. With Python , we don't have to worryabout the compilation step as it's done in real-time. The tradeoff isthat interpreted languages are usually slower than compiled Dynamic: you don't have to specify types for variablesand there is nothing that makes you do : everything in Python is an object.
3 But you canchoose to write code in an object-oriented, procedural, or evenfunctional level: you don't have to deal with low-level machine has been growing a lot recently partly because of its many usesin the following areas:System scripting: it's a great tool to automate everyday Analysis: it is a great language to experiment with and hastons of libraries and tools to handle data, create models, visualizeresults and even deploy solutions. This is used in areas likeFinance, E-commerce, and Development: frameworks like Django and Flask allow thedevelopment of web applications, API's, and learning : Tensorflow and Pytorch are some of the librariesthat allow scientists and the industry to develop and deploy ArtificialIntelligence solutions in Image Recognition, Health, Self-drivingcars, and many other can easily organize your code in modules and reuse them or sharethem with , we have to keep in mind that Python had breaking changesbetween versions 2 and 3.
4 And since Python 2 support ended in 2020,this article is solely based on Python let's get Installing Python 3If you use a Mac or Linux you already have Python installed. ButWindows doesn't come with Python installed by also might have Python 2, and we are going to use Python 3. So youshould check to see if you have Python 3 the following in your -VNotice the uppercase your result is something similar to ' Python ', for instance, , then you are ready to not, follow the next instructions according to your Operating Installing Python 3 on WindowsGo to the latest the download, double-click the the first screen, check the box indicating to "Add Python to PATH"and then click on "Install Now".9 Wait for the installation process to finish until the next screen with themessage "Setup was successful".
5 Click on "Close". Installing Python 3 on MacInstall XCode from the App the command line tools by running the following in your --installI recommend using Homebrew. Go to and follow theinstructions on the first page to install installing Homebrew, run the following brew commands to installPython updatebrew install python3 Homebrew already adds Python 3 to the PATH, so you don't have to doanything Installing Python 3 on LinuxTo install using apt, available in Ubuntu and Debian, enter the following:sudo apt install python310To install using yum, available in RedHat and CentOS, enter the following:sudo yum install python3114 Running CodeYou can run Python code directly in the terminal as commands or youcan save the code in a file with the .py extension and run the Python TerminalRunning commands directly in the terminal is recommended when youwant to run something the command line and type python3:renan@mypc:~$ python3 You should see something like this in your terminal indicating the version(in my case, Python ), the operating system (I'm using Linux), andsome basic commands to help >>> tells us we are in the Python (default, Nov 7 2019, 10:44:02) [GCC ] on linuxType "help", "copyright", "credits" or "license" for more information.
6 >>>Let's test it by running our first program to perform basic math and addtwo numbers.>>> 2 + 212 The output is:4To exit the Python console simply type exit().>>> exit() Running .py filesIf you have a complex program, with many lines of code, the Pythonconsole isn't the best alternative is simply to open a text editor, type the code, and savethe file with a .py 's do that, create a file called with the ('Second Program')The print() function prints a message on the message goes inside the parentheses with either single quotes ordouble quotes, both work the run the program, on your terminal do the following:renan@mypc:~$ python3 output is:Second Program145 SyntaxPython is known for its clean language avoids using unnecessary characters to indicate SemicolonsPython makes no use of semicolons to finish lines.
7 A new line is enoughto tell the interpreter that a new command is print() function will display this example, we have two commands that will display the messagesinside the single ('First command')print('Second command')Output:First commandSecond commandThis is wrong due to the semicolons in the end:print('First command');print('Second command'); IndentationMany languages use curly-brackets to define 's interpreter uses only indentation to define when a scope endsand another one means you have to be aware of white spaces at the beginning ofeach line -- they have meaning and might break your code if definition of a function works:def my_function(): print('First command')This doesn't work because the indentation of the second line is missingand will throw an error:def my_function():print('First command') Case sensitivity and variablesPython is case sensitive.
8 So the variables name and Name are not the samething and store different = 'Renan'16 Name = 'Moura'As you could see, variables are easily created by just assigning values tothem using the = means name stores 'Renan' and Name stores 'Moura'. CommentsFinally, to comment something in your code, use the hash mark #.The commented part does not influence the program flow.# this function prints somethingdef my_function(): print('First command')This was an overview, minor details on each of these will become moreclear in the next chapters with examples and broader CommentsThe purpose of comments is to explain what is happening in the are written along with your code but do not influence yourprogram you work by yourself, maybe comments don't feel like somethingyou should write. After all, at the moment, you know the whys of everysingle line of what if new people come on board your project after a year and theproject has 3 modules, each with 10,000 lines of code?
9 Think about people who don't know a thing about your app and who aresuddenly having to maintain it, fix it, or add new , there is no single solution for a given problem. Your way ofsolving things is yours and yours only. If you ask 10 people to solve thesame problem, they will come up with 10 different you want others to fully understand your reasoning, good code designis mandatory, but comments are an integral part of any How to Write Comments in PythonThe syntax of comments in Python is rather easy: just use the hash mark# symbol in front of the text you want to be a #This is a comment and it won't influence my program flowYou can use a comment to explain what some piece of code does.#calculates the sum of any given two numbersa + Multiline CommentsMaybe you want to comment on something very complex or describehow some process works in your these cases, you can use multiline do that, just use a single hash mark # for each line.
10 #Everything after the hash mark # is a comment#This is a comment and it won't influence my program flow#Calculates the cost of the project given variables a and b#a is the time in months it will take until the project is finished#b is how much money it will cost per montha + b * 10 197 VariablesIn any program, you need to store and manipulate data to create a flowor some specific 's what variables are can have a variable to store a name, another one to store the age ofa person, or even use a more complex type to store all of this at once likea Creating also known as DeclaringDeclaring a variable is a basic and straightforward operation in pick a name and attribute a value to it use the = 'Bob'age=32 You can use the print() function to show the value of a (name)print(age)Bob2032 Notice that in Python there is no special word to declare a moment you assign a value, the variable is created in also has dynamic typing, which means you don't have to tell it ifyour variable is a text or a number, for interpreter infers the typing based on the value you need it, you can also re-declare a variable just by changing itsvalue.