Example: confidence

Introduction to Python - 2018

CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data StructuresIntroduction to Python - 20181 What is Python ?A snake! A snake! A scaaary snake? Yes, but Python is also a programming language thatyou ll be learning this semester! Python bears some resemblance to Java, but in generalit is cleaner and easier to read. There are a few important differences from Java that youshould note:First, you don t need to declare the types of variables. Thus, you writex = 1ratherthanint x = 1. Variables do have types, but you don t need to announce the type whenyou first use a variable. In fact, you can writex = 1and thenx = "abcd"in the sameprogram; after the first assignment, x is an integer; after the second, it s a string. ( Ingeneral this is a very bad idea, so avoid it!)Second, the environment in which you work with Python lets you type bits of code andsee what happens without an intermediate compiling step. This makes experimentationand testing very , a feature of Python that you will grow to love and cherish is how easy it is toread.

CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data Structures 2. Change the Tab Length to be 4 and make sure the Tab Type is set to soft.

Tags:

  Introduction, Python, 2018, Introduction to python 2018

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of Introduction to Python - 2018

1 CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data StructuresIntroduction to Python - 20181 What is Python ?A snake! A snake! A scaaary snake? Yes, but Python is also a programming language thatyou ll be learning this semester! Python bears some resemblance to Java, but in generalit is cleaner and easier to read. There are a few important differences from Java that youshould note:First, you don t need to declare the types of variables. Thus, you writex = 1ratherthanint x = 1. Variables do have types, but you don t need to announce the type whenyou first use a variable. In fact, you can writex = 1and thenx = "abcd"in the sameprogram; after the first assignment, x is an integer; after the second, it s a string. ( Ingeneral this is a very bad idea, so avoid it!)Second, the environment in which you work with Python lets you type bits of code andsee what happens without an intermediate compiling step. This makes experimentationand testing very , a feature of Python that you will grow to love and cherish is how easy it is toread.

2 Instead of using a lot of punctuation and other symbols, which are what makes codein most programming languages look daunting and scary, Python uses English keywordsand natural-sounding syntax. For example, this is a declaration and an if-condition inPython:x = 1if x > 0:print "x is positive"print "What beautiful syntax!"print "Do you love Python yet?"You ll notice that instead of using curly braces to delimit code blocks, Python uses whites-pace indentation. That means that correctly nesting your code now has semantic meaning,instead of just making it easier for you (and your TAs) to read. We ll learn more aboutsyntax later, so for now, just marvel at its is similar to Java in that it also handles your memory management, meaning itallocates memory and has a garbage collector to free up that memory once it is no longerneeded, making your life a whole lot easier. If you re not already convinced that Why should you learn Python ?We ll be using Python throughout the semester to code up some of the algorithms you ll belearning.

3 As a computer scientist you should get used to learning new languages readily,not only because it s an important part of the subject, but also because it s useful (andIntroduction to Python - 2018 March 4, 20181CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data Structuresfun!). Python is especially important to learn because it is usedverywidely as a scriptinglanguage Pixar uses it for all their tools, for instance so knowing it could one day helpyou get a job making a movie like Toy Story Day 1 Your journey through Python begins Writing your first program in PythonIt s tradition when learning a new programming language that your first program is a HelloWorld program, so let s start out by writing a simple one-line program that prints HelloWorld! Setting upRuncs0160install pythonIntrofrom the command line. This will install a folderpythonIntroin yourcs0160directory. It should contain two we begin programming, we need to configure the editor you will use to writeyour Python code.

4 While you are free to use any editor of your choice, we recommendyou use Atom. If you are working from a computer in the Sunlab or MSlab, completeSection , which will tell you how to configure Atom universally for Python code, andskip over Section If you have Atom locally on your personal computer, you can followthe same instructions to configure it, although some of the instructions may be a littledifferent depending on how you work locally. If you are working remotely, jump right tosection to learn how to set up Gedit, which performs better over SSH. Either way, besure to begin again at Section , where you will write your first Python program! Working from the Sunlab or MSlabOpen the text editor Atom, by typingatom &in your terminal. First we will make you will write your program Create a new file: File>New File2. Save this file, File>Save, naming very important!!Make sure the file is saved in your~/course/cs0160 now need to configure Atom to work best with Python :1.

5 From the menu bar, select Edit>Preferences. This should open up a new tab in theeditor. Scroll down to theEditor Settingssection. This is where you can configuredifferent preferences for your Atom. Take a look at some of the options and feel freeto play around with to Python - 2018 March 4, 20182CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data Structures2. Change theTab Lengthto be4and make sure theTab Typeis set Close this tab and you re ready to go! Working romotely over SSHG edit performs much better over SSH, so you should use this program to work on the labif you are not on a CS department &into a terminal and press Enter to open we will make you will write your program Save the current (blank) new file: File>Save Name the very important!! Make sure the file is savedin your~/course/cs0160 , we have to configure Gedit to work well with Go toEdit->Preferences2. Click on theEditortab3. Ensure thatTab widthis set to 44.

6 Check the box that saysInsert spaces instead of tabsClose out of the preferences window. You re all set! Let s get to coding!From CS15, you are probably familiar with using these text editors to write Java (.java)code. We ll be using them to write Python (.py) files in s important you have configured your editor as specified above because Python useswhitespace indentation to delimit your code (more on this later). For the sake of conve-nience, we insist that you use 4 spaces to indent your code. It will make your code lookconsistent across machines and prevent inconsistencies between spaces and hard , let s begin! Type:print Hello world! and save your file. Now go back to your terminal, make sure you are in thepythonIntrodirectory and typepython run the program. It will printHello world!to your on, do you really have to typepython time you wantto run a program? (Or for the especially lazy, scroll through your commands until you findthe last time you typed it?)

7 Heck no! Go back to your editor and type: Introduction to Python - 2018 March 4, 20183CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data Structures#! /usr/bin/pythonat the top of This tells your machine to use Python to interpretthe file when executed. Then save the file, go back to your terminal, and typechmod + make the file an executable. (If you haven t usedchmodbefore, it s aterminal command used to change file permissions, in this case to make your Python fileexecutable. The+xargument adds executability for the owner of the file, you!) Now ifyou your terminal your program printsHello world!to theterminal. From now on, all of your Python files should start with#! /usr/ Python SyntaxLet s say that instead of wanting to write a program that just prints Hello world! andthen ends, you wanted to write a program with a function that takes in a string with yourname as the parameter, and prints Hello<name>! Following the CS16 Python codingconventions, the function would look like this:def say_hello(name):"""say_hello: string -> nothingPurpose: prints a greeting of the form "Hello <name>!

8 "Example: say_hello("Seny") -> "Hello Seny!""""print "Hello " + name + "!" #this is the function bodyWhen you define a function in Python , you simply writedef(which is short for define),followed by the name of the function, with all words lowercase and separated by underscores,then the parameters in parentheses, and lastly a colon. Note that you do not need tospecify the type of your parameters in Python ! Next, document your function with a blockcomment! Use triple quotes ("""to create block comments much like/*would in Java. Foran in-line comment, use#, instead of the//from Java. This block comment should includea description of the parameters and return type, the purpose of the method, and an exampleof the method in use. This type of block comment is called adocstringand is crucialto writing readable code that is easy to understand later. There is a detailed handout oncoding conventions on the course website that you can read for more information on writinggood actual body of this function is simple.)

9 First off, it is indented four spaces fromthe function declaration. This iscrucial. If you do not indent your code correctly, it willnot work. Whitespace indentation is used in Python to nest blocks of code, rather thancurly braces. Each subordinating code block must be indented four spaces relative to thecode on which it depends. As you get used to programming in Python , this will becomesecond nature. The code hereprints the concatenated string of"Hello" + str + "!"to the shell. Note that theprintstatement doesn t require that you enclose the string inIntroduction to Python - 2018 March 4, 20184CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data Structuresparentheses since it is what is known as a statement, not a function. Functions in Pythondo require test out this function, type it into Atom, and put this code at the end:if __name__ == "__main__":say_hello("Seny") #substitute your nameIt s very important this code comesafterthe function definition, because functions mustbe defined before they can be called.

10 (Note that this is different than Java).This bit of code will allow you to run it as a standalone program. The main line here issimilar to Java spublic static void main(String args[]). It contains the code thatwill run when you execute the program. Save your file (make sure it ends ) and thenrun it using one of the two techniques we discussed earlier. The terminal will now greetyou as if your name is your name into the parameters and watch your terminal try to befriend if you try to say hi back, you will see this:gemini ~/course/cs0160 $ Python Seny!gemini ~/course/cs0160 $ Hello Terminal!bash: Hello: command not foundSo much for that :(Let s look at something a little more complicated. Say you had written out somepseudocode for a function that prints out the numbers 1 tonforn 1. It might looksomething like this:Algorithm printOneToN(n):This algorithm prints out the numbers from 1 to n for n n is less than 1, it prints an error message to alert the : an integer nOutput: noneif n < 1 thenprint "Invalid input: integer value cannot be less than 1"returnfor i from 1 to nprint iIn Python , following the CS16 Python coding conventions, it would look like this:def print_one_to_n(n):"""print_one_to_n: int -> nothingPurpose: this function prints out the numbers from 1 to n for n >= n is less than 1, it prints an error message to alert the to Python - 2018 March 4, 20185CS 16 Introduction to Python - 2018 Introduction to Algorithms and Data Structures"""if n < 1:print "Invalid input: integer value cannot be less than 1"returnfor i in range(1, n + 1):print iYou ll notice that there aren t many differences between the pseudocode and Python .)


Related search queries