How to Make Program Run Again After User Input Python

Let's Programme with Python: Reacting to User Input (Office 4)

In the fourth (and terminal) form in this series you'll larn how to make your Python programs interactive by letting them react to user input.

In this guest postal service series by Doug Farrell you'll acquire the basics of programming with Python from scratch. If yous've never programmed before or need a fun footling class to work through with your kids, you're welcome to follow along.

Looking for the rest of the "Allow's Program with Python" series? Here you go:

  • Function one: Statements, Variables, and Loops
  • Part ii: Functions and Lists
  • Part three: Conditionals and "if" Statements
  • Function 4: Reacting to User Input (This article)

Tabular array of Contents – Part 4

  1. Let's Write a Programme Together
  2. Getting Information From the Player
  3. Converting a String to a Number
  4. Another Kind of Loop
  5. More Things Nosotros Can Do With Lists
  6. How Many Items Are in a List?
  7. How to Option Random Things From a List?
  8. Our Completed "Guess My Number" Program
  9. Congratulations!
  10. Appendix – Python Info That Doesn't Fit in Class

Permit'south Write a Program Together

For this class we're going to write a "Estimate My Number" game plan. In this game the plan will pick a random number from ane to x and the player volition try to guess what the number is. The programme will answer in different ways depending on whether the thespian guessed correctly or incorrectly. The thespian can also end the game whenever they desire by telling the program to "quit".

The interesting part of this plan is y'all're going to tell me how to write it instead of the other manner effectually. But earlier we go started, we need to learn a few more things about Python to help us build our game.

Getting Information From the Actor

In club to play our game the role player has to interact with it. We need a way to become guesses from the player and so the game can compare its secret number to the players guess. To exercise this nosotros apply the input() function.

The input() office let's us enquire the user for some information, and then wait for them to enter something using the keyboard. In the Python interactive fashion it looks like this:

                            >>>              guess              =              input              (              "Please enter a number: "              )              Delight              enter              a              number              :            

At the point where the input() role runs, the cursor is at the cease of the "Please enter a number: " cord, waiting for you to type something.

Y'all can blazon anything you lot desire, when you hitting the <ENTER> central whatever you typed will exist assigned to the guess variable as a cord. This is a very unproblematic way to go input from the user using the keyboard.

Converting a String to a Number

We haven't talked about this yet, only there is a divergence between a string like "10" and the number ten. Try this in the interactive mode:

                            >>>              10              ==              10              True              >>>              "10"              ==              10              False            

On the first line we are comparison the two number 10's to each other to see if they are equal. Python knows they are, and so information technology responds by printing True to the screen.

Only the next comparison, "x" == ten, why does Python respond with Imitation? The simple reply is Python doesn't think they're equal.

Only why aren't they equal? This can be confusing, "10" looks similar the number 10. And ten definitely looks like the number ten too. For Python even so, this isn't truthful.

The number 10 is exactly that, the numerical value 10. The cord "10" is just a cord, it has no numerical value, fifty-fifty though "10" looks similar ten to usa.

The difference is the representation. The "x" represents a string to Python, it doesn't know that cord represents ten to usa. The 10 notwithstanding does hateful numerical ten to Python, ten things, ten cars, 10 whatever.

What does this accept to do with our game? A lot really. When the game starts the program volition randomly pick a number from ane to 10, not a cord, a number. However when the player types something into our guess = input("Delight enter a number: ") prompt, approximate is a string variable.

Fifty-fifty if the player enters a "1" and then a "0" and so hits enter, the guess variable will exist a cord. This is where a problem comes in. Let'southward say we phone call the game's variable for its number secret_number. If we write some Python lawmaking that compares them, like this:

                            if              secret_number              ==              approximate              :            

This lawmaking will neglect because comparing a string to a number will ever be Imitation. We need to make Python compare two of the same kinds of things. For our game, both things need to be numbers. Nosotros need to convert the player'due south guess variable to a number. Python can do this using the int() function. Information technology looks like this:

                            guess_number              =              int              (              judge              )            

With this code we're taking the player's input, guess, which could be something like "8", and converting it to the numerical value 8 and assigning it to the new variable guess_number. Now when nosotros compare guess_number with secret_number, they are the same kind of thing (numbers) and will compare correctly when we write Python code like this:

                            if              guess_number              ==              secret_number              :            

Another Kind of Loop

We've only used the for loop so far because it'southward handy when you know ahead of time how many times you want to loop. For our game program we won't know alee of time how many guesses it will have our player to approximate the secret_number. Nosotros also don't know how many times they'll want to play the game.

This is a perfect employ for the other loop Python supports, the while loop. The while loop is called a conditional loop because it will continue looping until some condition it is testing is Truthful. Here'due south an case of a while loop:

                            game_running              =              True              while              game_running              :              # Run some Python statements            

What these program lines mean is that while the variable game_running is True, the while loop will keep looping. This also means something in the while loop will have to modify the value of game_running in order for the program to exit the loop.

Forgetting to provide a style for the while loop to terminate creates what's called an infinite loop. This is unremarkably a bad thing and ways in club to go out the program it has to be crashed or stopped in some other way.

More than Things Nosotros Tin can Do With Lists

Nosotros've used Python lists earlier to hold things we want to deal with as one thing, like lists of turtles. We've created lists and appended things to lists. So far we've used the things in the list one at a fourth dimension using the for loop. Simply how do we get to the private things inside a list? For instance, suppose I accept this list in Python:

                            names              =              [              "Andy"              ,              "George"              ,              "Emerge"              ,              "Sharon"              ,              "Sam"              ,              "Chris"              ]            

How can I go just the "Sally" proper noun from the names list variable? We use something called list indexing to do that. Everything in a list has a position in the list, and all lists in Python start at position 0. The position is called an index, then to get "Sally" from the listing, remembering all lists start at index 0, we do this:

When nosotros do this the variable name will be equal to "Sally" from our list. The [2] above is called the index into the listing. We've told Python we want the thing inside the names listing at index ii.

How Many Items Are in a List?

It's oftentimes useful to exist able to observe out how many things are in a list. For instance, our names list above has six strings in information technology. Simply how could we find this out using Python? We use the len() function. Information technology looks like this:

                            number_of_names_in_list              =              len              (              names              )            

This volition set the variable number_of_names_in_list equal to six. Notice something about the number of items in the names list and the largest alphabetize, the proper noun "Chris". To get the proper noun "Chris" from our names list we would practice this:

The final matter in the list is at alphabetize 5, simply the number of things in the list is 6. This is because all lists kickoff with index 0, which is included in the number of things in the list. So for the names list we have indexes 0, 1, 2, 3, 4 and v, totaling half dozen things.

How to Choice Random Things From a List?

Now we know how to selection individual things from a listing, how to determine how long a list is and what the maximum index value in a list is. Tin can nosotros use this information to choose a random thing from a list? For a minute allow's think almost our turtle programs, we had a list something like this:

                            colors              =              [              "black"              ,              "red"              ,              "organge"              ,              "yellowish"              ,              "green"              ,              "blue"              ]            

How could we selection a random color from this listing to apply when we were creating a turtle? Nosotros know the smallest index is 0, which would exist the colour "black". Nosotros also know by looking at the list that our largest index is 5, the color bluish. This is ane less than the number of colors in the listing. And then nosotros could do something like this:

                            colors              =              [              "black"              ,              "crimson"              ,              "organge"              ,              "yellow"              ,              "dark-green"              ,              "blue"              ]              turtle_color              =              colors              [              random              .              randint              (              0              ,              v              )]            

This Python argument would prepare the turtle_color variable to a random color from our colors list. But what if we added more colors to our list? Something like this:

                            colors              =              [              "black"              ,              "reddish"              ,              "organge"              ,              "yellow"              ,              "dark-green"              ,              "blue"              ,              "violet"              ,              "pink"              ]              turtle_color              =              colors              [              random              .              randint              (              0              ,              5              )]            

Unless we change the 5 in the random.randint(5) office we'll yet be picking from the first six colors and ignoring the new ones nosotros added. What if we're picking random colors all over our program, we'd accept to modify all the lines that pick a color every time we inverse the number of colors in our colors listing. Tin we become Python to handle this for u.s.a.? Sure nosotros can, nosotros can utilise the len() function to aid the states out. We can change our lawmaking to await like this:

                            colors              =              [              "black"              ,              "red"              ,              "organge"              ,              "yellow"              ,              "greenish"              ,              "blue"              ,              "violet"              ,              "pink"              ]              turtle_color              =              colors              [              random              .              randint              (              0              ,              len              (              colors              )              -              1              )]            

What's going on hither? Nosotros still take our colors listing variable, but at present we're using the len() function inside our random.randint() role. This is okay, the len() function returns a number and random.randint() expects a number every bit its second parameter.

But now we're telling random.randint() the upper alphabetize limit of the numbers we desire to choose from is one less than the number of things in the colors list variable. And as we've seen, one less than the number of things in a list will always exist the highest index in the listing. Past using the code above nosotros tin can add together or subtract as many items from the colors list as we want and our random selection will notwithstanding piece of work, using all the things in the list.

Our Completed "Approximate My Number" Program

Here's our Guess My Number programme, consummate with comments:

                            #              # Estimate My Number              #              import              random              # Set our game ending flag to False              game_running              =              Truthful              while              game_running              :              # Greet the user to our game              print              ()              print              (              "I'one thousand thinking of a number betwixt 1 and ten, tin you guess it?"              )              # Have the plan choice a random number between 1 and 10              secret_number              =              random              .              randint              (              0              ,              10              )              # Gear up the player's gauge number to something outside the range              guess_number              =              -              1              # Loop until the thespian guesses our number              while              guess_number              !=              secret_number              :              # Get the player's judge from the histrion              print              ()              approximate              =              input              (              "Please enter a number: "              )              # Does the user want to quit playing?              if              gauge              ==              "quit"              :              game_running              =              Fake              interruption              # Otherwise, nope, player wants to continue going              else              :              # Catechumen the players estimate from a string to an integer              guess_number              =              int              (              guess              )              # Did the player guess the program's number?              if              guess_number              ==              secret_number              :              impress              ()              print              (              "Congratulations, you guessed my number!"              )              # Otherwise, whoops, nope, get around once again              else              :              print              ()              impress              (              "Oh, to bad, that's not my number..."              )              # Say goodbye to the player              print              ()              impress              (              "Thanks for playing!"              )            

Congratulations!

We've completed our class and I hope you lot've had equally much fun every bit I had! We've written some pretty amazing programs together and learned quite a bit about programming and Python forth the mode. My wish is this interested you plenty to proceed learning most programming and to continue on to discover new things yous can do with Python.


Appendix – Python Info That Doesn't Fit in Grade

Differences Between Python and Other Languages

There are many programming languages out in the wild y'all can use to plan a calculator. Some have been around for a long time, like Fortran and C, and some are quite new, like Dart or Go. Python falls in the middle ground of being fairly new, simply quite mature.

Why would a developer cull one linguistic communication to learn over some other? That's a somewhat complicated question as most languages will allow you to practice anything you desire. However information technology can be difficult to express what yous desire to practice with a item linguistic communication instead of something else.

For instance, Fortran excels at computation and in fact it'southward name comes from Fromula Translation (ForTran). However information technology'south not known equally a groovy language if you need to do a lot of cord/text manipulation. The C programming language is a great language if your goal is to maximize the performance of your programme. If yous program it well y'all can create extremely fast programs. Notice I said "if you program information technology well", if you don't you lot tin can completely crash non simply your program, but perhaps fifty-fifty your calculator. The C language doesn't hold your hand to prevent you from doing things that could be bad for your program.

In addition to how well a linguistic communication fits the trouble yous're trying to solve, it might not be able to exist used with the tools you like, or might non provide the tools you demand, a particular language just may non appeal to you visually and appear ugly to you.

My choice of pedagogy Python fits a "sweetness spot" for me. It's fast enough to create the kinds of programs I want to create. It's visually very appealing to me, and the grammer and syntax of the linguistic communication fit the manner I want to express the problems I'chiliad trying to solve.

Python Vocabulary

Allow's talk about some of the vocabulary used in the course and what it means. Programming languages have their own "jargon", or words, significant specific things to programmers and that language. Here are some terms we've used in relation to Python.

IDLE – control prompt: IDLE is the programming environs that comes with Python. Information technology'south what'due south called an IDE, or Integrated Development Environment, and pulls together some useful things to assist write Python programs. When you lot start IDLE it opens upwardly a window that has the Python interactive prompt >>> in it.

This is a window running the Python interpreter in interactive mode. This is where you tin play around with some simple Python program statements. It'south kind of a sandbox where yous can effort things out. However, there is no way to relieve or edit your work; in one case the Python interpreter runs your statements, they're gone.

IDLE – editor window: The file window (File → New Window) opens up a unproblematic text editor. This is like Notepad in Windows, except it knows about Python code, how to format it and colorizes the text. This is where yous can write, edit and relieve your work and run information technology over again afterwards. When y'all run this lawmaking, behind the scenes IDLE is running the programme in the Python interpreter, just like information technology is in the offset IDLE window.

Syntax Highlighting: When we edit code in the file window of IDLE information technology knows most Python code. 1 of the things this means is the editor tin "colorize", or syntax highlight, diverse parts of the Python code you're entering. It sets the keywords of Python, like for and if, to certain colors. Strings to other colors and comments to another. This is just the file window being helpful and providing syntax highlighting to brand it easier for the developer to read and understand what's going on in the program.

Python Command Line: In Windows if you open up a command line window, what used to be chosen a DOS box, and run python, the organization will respond with the Python command prompt >>>. At this signal you're running Python in it'southward interactive mode, but like when you're within of IDLE. In fact they are the same thing, IDLE is running it'southward own Python command line inside the window, they are functionally identical.

Yous might remember "what utilize is that?", and I agree, I'd rather work in IDLE if I'm going to using the interactive fashion and play with the sandbox mode and the >>> command prompt. The existent utilise of the Python command line is when you enter something like this at the organisation command prompt:

If I've written a programme chosen myprogram.py and entered the line above, instead of going into interactive style, Python will read myprogram.py and run the lawmaking. This is very useful if yous're written a programme yous desire to use and not run inside of IDLE. Equally a developer I run programs in this manner all day long, and in many cases these programs run essentially forever equally servers.

Attribute and Belongings: We've thrown around the terms "attribute" and "property" kind of randomly, and this can pb to some confusion. The reason it's disruptive is these things mean substantially the aforementioned thing. When talking about programming there is e'er the goal to use specific words and terms to eliminate confusion about what you're talking about.

For example let's talk nearly you. Y'all accept many qualities that different people want to limited. Your friends want to know your name and phone number. Your school wants to know that also, and your age, the grade yous're in and our omnipresence record. In programming terms nosotros can call up of these equally attributes or properties most yous.

The attributes and backdrop of a matter (you for example) help get more specific data about the thing. And the specific information wanted depends on the audition asking. For case when meeting someone new they are more probable to be interested in your name belongings. Whereas your school might be more interested in your attendance belongings.

In Python we've been working with turtles, and those turtles have attributes and backdrop. For example a turtle every bit a property chosen forward. This holding happens to exist a function that moves the turtle forward, but it'due south even so a property of the turtle. In fact all the properties and attributes associated with a turtle are expressed as functions. These functions either make the turtle practice something, or tell us something almost the turtle.

Attributes and properties lead into a concept of Object Oriented Programming (OOP) that adds the concept of "things" to programs rather than just information and statements. Object Oriented Programming is beyond the telescopic of this book, just is very interesting and useful.

Interpreter vs Compiler

In class you've heard me talk near the Python interpreter, what does this mean. As we've talked about, computer languages are a way for people to tell a computer what to do. But the truth is a calculator only understands 0's and one's, and so how does a computer understand a language like Python? That'southward where a translation layer comes into play, and that translation layer is the interpreter for Python (and other interpreted languages) and a compiler for compiled languages. Allow's talk about compilers outset.

Compiler: A compiler is a translator that converts a reckoner language into car lawmaking, the 0'southward and ane'southward a estimator understands. A compiler commonly produces an executable file, on Windows machines this is a file that ends in .exe. This file contains machine code information the reckoner can run straight. Languages like C, C++ and Fortran are compiled languages and have to exist processed past a compiler before the program can run. Ane thing this ways is you can't run a compiled language direct, you have to compile information technology first. It also means in that location is nothing similar the interactive way (the >>> prompt in Python) in a compiled linguistic communication. The entire program has to be compiled, it can't compile and run single statements.

Interpreter: Here'southward where things get a footling more confusing. Most interpreted languages as well have a compiled pace, but the output of that step isn't machine code, no 0's and 1'due south. Instead the compilation footstep produces what is called ByteCode. The ByteCode is kind of an intermediate pace betwixt the about English computer language and the machine code understood by the estimator.

The ByteCode can't be run straight, it is run past a thing chosen a virtual motorcar. When the programme is run, the virtual machine reads the ByteCode and it generates the computer specific car code that actually is run by the estimator. When y'all run the program the virtual machine is constantly "interpreting" the ByteCode and generating computer specific machine code. Dissimilar a compiled language, languages like Python with virtual machines can provide an interactive mode (the >>> prompt) as the interpreter and virtual machine tin translate and run programme statements on the fly.

Advantages And Disadvantages: Then why would a developer pick a compiled linguistic communication over an interpreted language, and vice versa? Well, what nosotros said earlier still applies, expressiveness of the language, style, etc, those are important things to remember about when choosing a language for a projection. Simply there are some differences beyond that. In general compiled languages produce programs that run faster than programs produced by an interpreter. Recall, compiled languages produce programs containing auto lawmaking that can be run directly, whereas interpreted languages usually have a virtual machine between the ByteCode and the machine code, then in that location's a speed penalty in that location. Even so, also go on in mind mod computers are then fast this difference is less important. In improver, interpreted languages are beingness constantly improved so their performance gets better and improve, so the performance difference betwixt the two is shrinking.

Nearly interpreted languages also offer safe features to prevent the programmer from crashing the program. Interpreted languages brand information technology hard to corrupt retentiveness. They make it difficult to go direct access to the hardware. They don't force the programmer to manage memory explicitly. Compiled programs like C offering none of this, and therefore it's easy to do all of those things, which tin can put your program at gamble, unless you're a skilled developer. The condom features can be added to a C programme, but this has to be done manually by the programmer and isn't handled by the language natively.

Python Reference Materials

Included beneath is a listing of reference materials to help yous go further in your study of Python.

  • Python Website – Master Python website
  • Python Documentation – Official Python iii Documentation
  • Python Turtle Documentation – Official Python Documentation for Turtle
  • Python Tutorials for Beginners on dbader.org
  • Learn Python – An interesting tutorial to assistance learn Python
  • How To Think Similar A Computer Scientist – Interesting and interactive mode to learn Python
  • PyGame – An add together on module for writing games with Python
This article was filed under: programming, and python.

Related Articles:

  • Allow's Program with Python: Statements, Variables, and Loops (Function i) – In this four-office introduction for new programmers you'll learn the basics of programming with Python using footstep-by-footstep descriptions and graphical examples.
  • Permit's Program with Python: Functions and Lists (Role ii) – In part two of this four-office Python introduction yous'll come across how to write reusable "code edifice blocks" in your Python programs with functions.
  • Let'south Program with Python: Conditionals and "if" Statements (Role 3) – In part three of this four-part Python introduction y'all'll see how to teach your plan how to make decisions with conditionals and if-statements.
  • How Practise I Make My Own Command-Line Commands Using Python? – How to plow your Python scripts into "real" control-line commands you lot can run from the organisation terminal.
  • Comprehending Python's Comprehensions – One of my favorite features in Python are list comprehensions. They can seem a bit arcane at get-go just when you break them down they are actually a very simple construct.
Latest Articles:
  • Interfacing Python and C: The CFFI Module – How to employ Python's congenital-in CFFI module for interfacing Python with native libraries as an alternative to the "ctypes" approach.
  • Write More Pythonic Lawmaking by Applying the Things You Already Know – There'due south a mistake I frequently make when I learn new things most Python… Here's how you lot can avoid this pitfall and learn something about Python's "enumerate()" role at the same time.
  • Working With File I/O in Python – Learn the basics of working with files in Python. How to read from files, how to write data to them, what file seeks are, and why files should be closed.
  • How to Reverse a String in Python – An overview of the 3 main ways to opposite a Python cord: "slicing", reverse iteration, and the archetype in-place reversal algorithm. Also includes performance benchmarks.
  • Mastering Click: Writing Advanced Python Command-Line Apps – How to improve your existing Click Python CLIs with advanced features like sub-commands, user input, parameter types, contexts, and more.
  • Working with Random Numbers in Python – An overview for working with randomness in Python, using only functionality built into the standard library and CPython itself.
← Browse All Articles

brodiedwellied1975.blogspot.com

Source: https://dbader.org/blog/python-intro-reacting-to-user-input

0 Response to "How to Make Program Run Again After User Input Python"

แสดงความคิดเห็น

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel