• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Coursera Python: Programming for everybody assignment 5.2

I have been taking Coursera's course, Programming for Everybody with Python. But one of the assignment 5.2 on week 7 got my attention.

The objective is to make the user enter some numbers and enter done, when he entered all the numbers he wanted. After that, the output should be the biggest number and smallest number he entered.

Here is the problem. If I enter a negative number it is not displayed. Let's say I enter: 32, 55,10, -2 76. The output should be 76 and -2. But what really happens is that 76 and 10 are printed out.

Do you guys have any idea why this happens?

Here is the code.

  • variable-assignment

J.Felipe's user avatar

  • 2 What do you think range(-2) does? –  José Sánchez Commented Dec 28, 2016 at 12:33
  • 1 Why are you even looping over a range? –  TigerhawkT3 Commented Dec 28, 2016 at 12:38

3 Answers 3

Well,the issue is that why are you iterating over an int if it isnt a list? You can rather do it with out a loop:

Taufiq Rahman's user avatar

  • The continue isn't necessary, as the only other code in that loop is the elif block which already won't run if the if executes. –  TigerhawkT3 Commented Dec 28, 2016 at 12:55
  • True,didnt see that. –  Taufiq Rahman Commented Dec 28, 2016 at 12:57

Well, this was my answer. Try this. Let me know what you don't understand.

Ihfaz666's user avatar

  • 2 Welcome to SO. While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please check how-to-answer for more details. –  alan.elkin Commented Jun 13, 2020 at 20:58

This code will work for your assignment

largest = None smallest = None while True: try: num = input("Enter a number: ") if num == "done": break # print (num)

print ("Maximum is", largest) print ("Minimum is", smallest)

MohaMmed MQ's user avatar

Not the answer you're looking for? Browse other questions tagged python numbers variable-assignment or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live

Hot Network Questions

  • Simple Bank Management System
  • Roadmap for self study in philosophy
  • Is this homebrew "Firemind Dragonborn" race overpowered?
  • Parts of Humans
  • I feel like doing a PhD is my only option but I am not excited about it. What can I do to fix my life?
  • How can photons interact with nuclei?
  • What did Jesus mean about the Temple as the Father's House in John 2:16?
  • Plant identification, please
  • What would large scale war with tactical nukes look like?
  • Unpaired socks in my lap
  • What enemies can you kill in one hit with Pure Nail?
  • 70's-80's sci-fi/fantasy movie (TV) with togas and crystals
  • How to make a place windy
  • Academic Interview Question: "What is the title of your second book?"
  • What is the time-travel story where "ugly chickens" are trapped in the past and brought to the present to become ingredients for a soup?
  • If humans colonized Earth 100,000 years ago, would we know it?
  • Can a creature with Mimicry activate command word magic items?
  • Will a rack-mounted child seat be safe if the rack's maximum load is 2kg less than the seat manufacturer describes as the minimum load?
  • Is there a reason why countries in the Global South don't complain about Chinese overcapacity?
  • Unsure whether to begin a PhD program
  • Why are worldships not shaped like worlds?
  • Psychology Today Culture Fair IQ test question
  • Round Cake Pan with Parchment Paper
  • Who was the first philosopher to describe approximation?

python assignment 5.2

python assignment 5.2

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • Function and String Mixed-Up Code Questions
  • Peer Instruction: Functions Multiple Choice Questions
  • Functions and Lists Mixed-Up Code Questions
  • Mixed-up Code Questions
  • Functions with Tuples and Dictionaries Mixed-Up Code Questions
  • Functions and Loops Mixed-Up Code Questions
  • Please join a research study to help us test new approaches to learning programming!
  • Functions Mixed-Up Code Questions
  • Practice Problems
  • An Introduction To Our System
  • Self-efficacy Post-Survey
  • Functions and Conditionals Mixed-Up Code Questions
  • Peer Instruction: Function Multiple Choice Questions
  • 5.1 Function calls
  • 5.2 Built-in functions
  • 5.3 Type conversion functions
  • 5.4 Math functions
  • 5.5 Random numbers
  • 5.6 Adding new functions
  • 5.7 Definitions and uses
  • 5.8 Flow of execution
  • 5.9 Parameters and arguments
  • 5.10 Fruitful functions and void functions
  • 5.11 Why functions?
  • 5.12 Debugging
  • 5.13 Glossary
  • 5.14 Multiple Choice Questions
  • 5.15 Mixed-up Code Questions
  • 5.16 Write Code Questions
  • 5.17 Group Work: Functions
  • 5.18 Functions Multiple Choice Questions
  • 5.19 Functions Mixed-Up Code Questions
  • 5.20 Functions Write Code Questions
  • 5.21 Group Work: Functions and Strings
  • 5.22 Functions and Strings Multiple Choice Questions
  • 5.23 Functions and Strings Mixed-Up Code Questions
  • 5.24 Functions and Strings Write Code Questions
  • 5.25 Group Work: Functions and Conditionals
  • 5.26 Functions and Conditionals Multiple Choice Questions
  • 5.27 Functions and Conditionals Mixed-Up Code Questions
  • 5.28 Functions and Conditionals Write Code Questions
  • 5.29 Group Work: Functions and Lists
  • 5.30 Functions with Lists Multiple Choice Questions
  • 5.31 Functions and Lists Mixed-Up Code Questions
  • 5.32 Functions and Lists Write Code Questions
  • 5.33 Group Work: Functions with Loops
  • 5.34 Functions with Loops Multiple Choice Questions
  • 5.35 Functions and Loops Mixed-Up Code Questions
  • 5.36 Functions and Loops Write Code Questions
  • 5.37 Group Work: Functions with Tuples and Dictionaries
  • 5.38 Functions with Tuples and Dictionaries Multiple Choice Questions
  • 5.39 Functions with Tuples and Dictionaries Mixed-Up Code Questions
  • 5.40 Functions with Tuples and Dictionaries Write Code Questions
  • 5.41 Group Work: Functions, Strings, and Conditionals
  • 5.42 Group Work: Functions with Lists and Loops
  • 5.1. Function calls" data-toggle="tooltip">
  • 5.3. Type conversion functions' data-toggle="tooltip" >

5.2. Built-in functions ¶

Python provides a number of important built-in functions that we can use without needing to provide the function definition. The creators of Python wrote a set of functions to solve common problems and included them in Python for us to use.

The max and min functions give us the largest and smallest values in a list, respectively:

The max function gives us the value 4 because it is the largest value in the list. The min function, inversely, give us the value -2 because it is the smallest value in the list.

Q-2: What will be printed as the output of this code?

  • Incorrect! You cannot use the max function to compare different data types. Try again.
  • There is an error
  • Correct! This code causes a TypeError because the max function cannot be used to compare different data types.

Another very common built-in function is the len function, which tells us how many items are in its argument. If the argument to len is a string, it returns the number of characters in the string.

These functions can operate on any set of values, as we will see in later chapters.

You should treat the names of built-in functions as reserved words (i.e., avoid using “max” as a variable name).

Activity: CodeLens 5.2.4 (functBuiltin_codelens_line2)

Q-5: Consider the code block below. What prints?

  • Incorrect! Spaces and punctuation characters count in the length. Try again.
  • Incorrect! Punctuation characters count in the length. Try again.
  • Incorrect! Spaces count in the length. Try again.
  • Correct! 13 is the length of all characters in the string, including spaces and punctuation.

Q-6: Which of the following would work as a variable name?

  • Incorrect! This is a reserved keyword because it is a built-in function in Python. Try again.
  • Correct! built_in is a valid variable name because it is not a built-in Python function.

python assignment 5.2

Assignment 5.2 | Week-7 | Programming for Everybody (Getting Started with Python) By Coursera

Coursera programming for everybody (getting started with python) week 5  assignment 5.2 .

 Question:    5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters ‘done’. Once ‘done’ is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.

Do Not Only Use These Quizzes For Getting Certificates.You Can Take Help From These Quizzes Answer. All Quizzes & Contents Are Free Of Charge. ✅ If You Want Any Quiz Answers Then Please  Contact Us

Related Questions & Answers:

Leave a comment cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Please Enable JavaScript in your Browser to Visit this Site.

Instantly share code, notes, and snippets.

@initiatorvaibhav

initiatorvaibhav / 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try,

  • Download ZIP
  • Star ( 0 ) 0 You must be signed in to star a gist
  • Fork ( 0 ) 0 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save initiatorvaibhav/3758f116f237ef60e9c5ca4e8b18f788 to your computer and use it in GitHub Desktop.
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done": break
try:
num = float(inp)
except:
print("Invalid input")
continue
if smallest is None:
smallest = num
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
print("Maximum is", int(largest))
print("Minimum is", int(smallest))

@initiatorvaibhav

initiatorvaibhav commented Feb 21, 2022

newer update

Sorry, something went wrong.

  • Python »
  • 3.12.4 Documentation »
  • The Python Standard Library »
  • Text Processing Services »
  • re — Regular expression operations
  • Theme Auto Light Dark |

re — Regular expression operations ¶

Source code: Lib/re/

This module provides regular expression matching operations similar to those found in Perl.

Both patterns and strings to be searched can be Unicode strings ( str ) as well as 8-bit strings ( bytes ). However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a bytes pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.

Regular expressions use the backslash character ( '\' ) to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\ , and each backslash must be expressed as \\ inside a regular Python string literal. Also, please note that any invalid escape sequences in Python’s usage of the backslash in string literals now generate a SyntaxWarning and in the future this will become a SyntaxError . This behaviour will happen even if it is a valid escape sequence for a regular expression.

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r' . So r"\n" is a two-character string containing '\' and 'n' , while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

It is important to note that most regular expression operations are available as module-level functions and methods on compiled regular expressions . The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters.

The third-party regex module, which has an API compatible with the standard library re module, but offers additional functionality and a more thorough Unicode support.

Regular Expression Syntax ¶

A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B , the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B ; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book [Frie09] , or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO .

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like 'A' , 'a' , or '0' , are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last' . (In the rest of this section, we’ll write RE’s in this special style , usually without quotes, and strings to be matched 'in single quotes' .)

Some characters, like '|' or '(' , are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted.

Repetition operators or quantifiers ( * , + , ? , {m,n} , etc) cannot be directly nested. This avoids ambiguity with the non-greedy modifier suffix ? , and with other modifiers in other implementations. To apply a second repetition to an inner repetition, parentheses may be used. For example, the expression (?:a{6})* matches any multiple of six 'a' characters.

The special characters are:

(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.

Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.

Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.

The '*' , '+' , and '?' quantifiers are all greedy ; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<a> b <c>' , it will match the entire string, and not just '<a>' . Adding ? after the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only '<a>' .

Like the '*' , '+' , and '?' quantifiers, those where '+' is appended also match as many times as possible. However, unlike the true greedy quantifiers, these do not allow back-tracking when the expression following it fails to match. These are known as possessive quantifiers. For example, a*a will match 'aaaa' because the a* will match all 4 'a' s, but, when the final 'a' is encountered, the expression is backtracked so that in the end the a* ends up matching 3 'a' s total, and the fourth 'a' is matched by the final 'a' . However, when a*+a is used to match 'aaaa' , the a*+ will match all 4 'a' , but when the final 'a' fails to find any more characters to match, the expression cannot be backtracked and will thus fail to match. x*+ , x++ and x?+ are equivalent to (?>x*) , (?>x+) and (?>x?) correspondingly.

Added in version 3.11.

Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match 'aaaab' or a thousand 'a' characters followed by a 'b' , but not 'aaab' . The comma may not be omitted or the modifier would be confused with the previously described form.

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous quantifier. For example, on the 6-character string 'aaaaaa' , a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible without establishing any backtracking points. This is the possessive version of the quantifier above. For example, on the 6-character string 'aaaaaa' , a{3,5}+aa attempt to match 5 'a' characters, then, requiring 2 more 'a' s, will need more characters than available and thus fail, while a{3,5}aa will match with a{3,5} capturing 5, then 4 'a' s by backtracking and then the final 2 'a' s are matched by the final aa in the pattern. x{m,n}+ is equivalent to (?>x{m,n}) .

Either escapes special characters (permitting you to match characters like '*' , '?' , and so forth), or signals a special sequence; special sequences are discussed below.

If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions.

Used to indicate a set of characters. In a set:

Characters can be listed individually, e.g. [amk] will match 'a' , 'm' , or 'k' .

Ranges of characters can be indicated by giving two characters and separating them by a '-' , for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59 , and [0-9A-Fa-f] will match any hexadecimal digit. If - is escaped (e.g. [a\-z] ) or if it’s placed as the first or last character (e.g. [-a] or [a-] ), it will match a literal '-' .

Special characters lose their special meaning inside sets. For example, [(+*)] will match any of the literal characters '(' , '+' , '*' , or ')' .

Character classes such as \w or \S (defined below) are also accepted inside a set, although the characters they match depend on the flags used.

Characters that are not within a range can be matched by complementing the set. If the first character of the set is '^' , all the characters that are not in the set will be matched. For example, [^5] will match any character except '5' , and [^^] will match any character except '^' . ^ has no special meaning if it’s not the first character in the set.

To match a literal ']' inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both [()[\]{}] and []()[{}] will match a right bracket, as well as left bracket, braces, and parentheses.

Support of nested sets and set operations as in Unicode Technical Standard #18 might be added in the future. This would change the syntax, so to facilitate this change a FutureWarning will be raised in ambiguous cases for the time being. That includes sets starting with a literal '[' or containing literal character sequences '--' , '&&' , '~~' , and '||' . To avoid a warning escape them with a backslash.

Changed in version 3.7: FutureWarning is raised if a character set contains constructs that will change semantically in the future.

A|B , where A and B can be arbitrary REs, creates a regular expression that will match either A or B . An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|' , use \| , or enclose it inside a character class, as in [|] .

Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')' , use \( or \) , or enclose them inside a character class: [(] , [)] .

This is an extension notation (a '?' following a '(' is not meaningful otherwise). The first character after the '?' determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule. Following are the currently supported extensions.

(One or more letters from the set 'a' , 'i' , 'L' , 'm' , 's' , 'u' , 'x' .) The group matches the empty string; the letters set the corresponding flags for the entire regular expression:

re.A (ASCII-only matching)

re.I (ignore case)

re.L (locale dependent)

re.M (multi-line)

re.S (dot matches all)

re.U (Unicode matching)

re.X (verbose)

(The flags are described in Module Contents .) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function. Flags should be used first in the expression string.

Changed in version 3.11: This construction can only be used at the start of the expression.

A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

(Zero or more letters from the set 'a' , 'i' , 'L' , 'm' , 's' , 'u' , 'x' , optionally followed by '-' followed by one or more letters from the 'i' , 'm' , 's' , 'x' .) The letters set or remove the corresponding flags for the part of the expression:

(The flags are described in Module Contents .)

The letters 'a' , 'L' and 'u' are mutually exclusive when used as inline flags, so they can’t be combined or follow '-' . Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns (?a:...) switches to ASCII-only matching, and (?u:...) switches to Unicode matching (default). In bytes patterns (?L:...) switches to locale dependent matching, and (?a:...) switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the original matching mode is restored outside of the group.

Added in version 3.6.

Changed in version 3.7: The letters 'a' , 'L' and 'u' also can be used in a group.

Attempts to match ... as if it was a separate regular expression, and if successful, continues to match the rest of the pattern following it. If the subsequent pattern fails to match, the stack can only be unwound to a point before the (?>...) because once exited, the expression, known as an atomic group , has thrown away all stack points within itself. Thus, (?>.*). would never match anything because first the .* would match all characters possible, then, having nothing left to match, the final . would fail to match. Since there are no stack points saved in the Atomic Group, and there is no stack point before it, the entire expression would thus fail to match.

Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name . Group names must be valid Python identifiers, and in bytes patterns they can only contain bytes in the ASCII range. Each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.

Named groups can be referenced in three contexts. If the pattern is (?P<quote>['"]).*?(?P=quote) (i.e. matching a string quoted with either single or double quotes):

Context of reference to group “quote”

Ways to reference it

in the same pattern itself

(as shown)

when processing match object

(etc.)

in a string passed to the argument of

Changed in version 3.12: In bytes patterns, group name can only contain bytes in the ASCII range ( b'\x00' - b'\x7f' ).

A backreference to a named group; it matches whatever text was matched by the earlier group named name .

A comment; the contents of the parentheses are simply ignored.

Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion . For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov' .

Matches if ... doesn’t match next. This is a negative lookahead assertion . For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov' .

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion . (?<=abc)def will find a match in 'abcdef' , since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function:

This example looks for a word following a hyphen:

Changed in version 3.5: Added support for group references of fixed length.

Matches if the current position in the string is not preceded by a match for ... . This is called a negative lookbehind assertion . Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern, which will match with '<user@host.com>' as well as 'user@host.com' , but not with '<user@host.com' nor 'user@host.com>' .

Changed in version 3.12: Group id can only contain ASCII digits. In bytes patterns, group name can only contain bytes in the ASCII range ( b'\x00' - b'\x7f' ).

The special sequences consist of '\' and a character from the list below. If the ordinary character is not an ASCII digit or an ASCII letter, then the resulting RE will match the second character. For example, \$ matches the character '$' .

Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55' , but not 'thethe' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number . Inside the '[' and ']' of a character class, all numeric escapes are treated as characters.

Matches only at the start of the string.

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning or end of the string. This means that r'\bat\b' matches 'at' , 'at.' , '(at)' , and 'as at ay' but not 'attempt' or 'atlas' .

The default word characters in Unicode (str) patterns are Unicode alphanumerics and the underscore, but this can be changed by using the ASCII flag. Word boundaries are determined by the current locale if the LOCALE flag is used.

Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

Matches the empty string, but only when it is not at the beginning or end of a word. This means that r'at\B' matches 'athens' , 'atom' , 'attorney' , but not 'at' , 'at.' , or 'at!' . \B is the opposite of \b , so word characters in Unicode (str) patterns are Unicode alphanumerics or the underscore, although this can be changed by using the ASCII flag. Word boundaries are determined by the current locale if the LOCALE flag is used.

Matches any Unicode decimal digit (that is, any character in Unicode character category [Nd] ). This includes [0-9] , and also many other digit characters.

Matches [0-9] if the ASCII flag is used.

Matches any decimal digit in the ASCII character set; this is equivalent to [0-9] .

Matches any character which is not a decimal digit. This is the opposite of \d .

Matches [^0-9] if the ASCII flag is used.

Matches Unicode whitespace characters (which includes [ \t\n\r\f\v] , and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages).

Matches [ \t\n\r\f\v] if the ASCII flag is used.

Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v] .

Matches any character which is not a whitespace character. This is the opposite of \s .

Matches [^ \t\n\r\f\v] if the ASCII flag is used.

Matches Unicode word characters; this includes all Unicode alphanumeric characters (as defined by str.isalnum() ), as well as the underscore ( _ ).

Matches [a-zA-Z0-9_] if the ASCII flag is used.

Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_] . If the LOCALE flag is used, matches characters considered alphanumeric in the current locale and the underscore.

Matches any character which is not a word character. This is the opposite of \w . By default, matches non-underscore ( _ ) characters for which str.isalnum() returns False .

Matches [^a-zA-Z0-9_] if the ASCII flag is used.

If the LOCALE flag is used, matches characters which are neither alphanumeric in the current locale nor the underscore.

Matches only at the end of the string.

Most of the escape sequences supported by Python string literals are also accepted by the regular expression parser:

(Note that \b is used to represent word boundaries, and means “backspace” only inside character classes.)

'\u' , '\U' , and '\N' escape sequences are only recognized in Unicode (str) patterns. In bytes patterns they are errors. Unknown escapes of ASCII letters are reserved for future use and treated as errors.

Octal escapes are included in a limited form. If the first digit is a 0, or if there are three octal digits, it is considered an octal escape. Otherwise, it is a group reference. As for string literals, octal escapes are always at most three digits in length.

Changed in version 3.3: The '\u' and '\U' escape sequences have been added.

Changed in version 3.6: Unknown escapes consisting of '\' and an ASCII letter now are errors.

Changed in version 3.8: The '\N{ name }' escape sequence has been added. As in string literals, it expands to the named Unicode character (e.g. '\N{EM DASH}' ).

Module Contents ¶

The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form.

Changed in version 3.6: Flag constants are now instances of RegexFlag , which is a subclass of enum.IntFlag .

An enum.IntFlag class containing the regex options listed below.

Added in version 3.11: - added to __all__

Make \w , \W , \b , \B , \d , \D , \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode (str) patterns, and is ignored for bytes patterns.

Corresponds to the inline flag (?a) .

The U flag still exists for backward compatibility, but is redundant in Python 3 since matches are Unicode by default for str patterns, and Unicode matching isn’t allowed for bytes patterns. UNICODE and the inline flag (?u) are similarly redundant.

Display debug information about compiled expression.

No corresponding inline flag.

Perform case-insensitive matching; expressions like [A-Z] will also match lowercase letters. Full Unicode matching (such as Ü matching ü ) also works unless the ASCII flag is used to disable non-ASCII matches. The current locale does not change the effect of this flag unless the LOCALE flag is also used.

Corresponds to the inline flag (?i) .

Note that when the Unicode patterns [a-z] or [A-Z] are used in combination with the IGNORECASE flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign). If the ASCII flag is used, only letters ‘a’ to ‘z’ and ‘A’ to ‘Z’ are matched.

Make \w , \W , \b , \B and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns.

Corresponds to the inline flag (?L) .

This flag is discouraged; consider Unicode matching instead. The locale mechanism is very unreliable as it only handles one “culture” at a time and only works with 8-bit locales. Unicode matching is enabled by default for Unicode (str) patterns and it is able to handle different locales and languages.

Changed in version 3.6: LOCALE can be used only with bytes patterns and is not compatible with ASCII .

Changed in version 3.7: Compiled regular expression objects with the LOCALE flag no longer depend on the locale at compile time. Only the locale at matching time affects the result of matching.

When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.

Corresponds to the inline flag (?m) .

Indicates no flag being applied, the value is 0 . This flag may be used as a default value for a function keyword argument or as a base value that will be conditionally ORed with other flags. Example of use as a default value:

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

Corresponds to the inline flag (?s) .

In Python 3, Unicode characters are matched by default for str patterns. This flag is therefore redundant with no effect and is only kept for backward compatibility.

See ASCII to restrict matching to ASCII characters instead.

This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *? , (?: or (?P<...> . For example, (? : and * ? are not allowed. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.

This means that the two following regular expression objects that match a decimal number are functionally equal:

Corresponds to the inline flag (?x) .

Functions ¶

Compile a regular expression pattern into a regular expression object , which can be used for matching using its match() , search() and other methods, described below.

The expression’s behaviour can be modified by specifying a flags value. Values can be any of the flags variables, combined using bitwise OR (the | operator).

The sequence

is equivalent to

but using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

The compiled versions of the most recent patterns passed to re.compile() and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding Match . Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

If zero or more characters at the beginning of string match the regular expression pattern , return a corresponding Match . Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in string , use search() instead (see also search() vs. match() ).

If the whole string matches the regular expression pattern , return a corresponding Match . Return None if the string does not match the pattern; note that this is different from a zero-length match.

Added in version 3.4.

Split string by the occurrences of pattern . If capturing parentheses are used in pattern , then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

That way, separator components are always found at the same relative indices within the result list.

Empty matches for the pattern split the string only when not adjacent to a previous empty match.

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.7: Added support of splitting on a pattern that could match an empty string.

Return all non-overlapping matches of pattern in string , as a list of strings or tuples. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

The result depends on the number of capturing groups in the pattern. If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result.

Changed in version 3.7: Non-empty matches can now start just after a previous empty match.

Return an iterator yielding Match objects over all non-overlapping matches for the RE pattern in string . The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl . If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \& are left alone. Backreferences, such as \6 , are replaced with the substring matched by group 6 in the pattern. For example:

If repl is a function, it is called for every non-overlapping occurrence of pattern . The function takes a single Match argument, and returns the replacement string. For example:

The pattern may be a string or a Pattern .

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous empty match, so sub('x*', '-', 'abxd') returns '-a-b--d-' .

In string-type repl arguments, in addition to the character escapes and backreferences described above, \g<name> will use the substring matched by the group named name , as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2 , but isn’t ambiguous in a replacement such as \g<2>0 . \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0' . The backreference \g<0> substitutes in the entire substring matched by the RE.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

Changed in version 3.6: Unknown escapes in pattern consisting of '\' and an ASCII letter now are errors.

Changed in version 3.7: Unknown escapes in repl consisting of '\' and an ASCII letter now are errors.

Changed in version 3.7: Empty matches for the pattern are replaced when adjacent to a previous non-empty match.

Changed in version 3.12: Group id can only contain ASCII digits. In bytes replacement strings, group name can only contain bytes in the ASCII range ( b'\x00' - b'\x7f' ).

Perform the same operation as sub() , but return a tuple (new_string, number_of_subs_made) .

Escape special characters in pattern . This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. For example:

This function must not be used for the replacement string in sub() and subn() , only backslashes should be escaped. For example:

Changed in version 3.3: The '_' character is no longer escaped.

Changed in version 3.7: Only characters that can have special meaning in a regular expression are escaped. As a result, '!' , '"' , '%' , "'" , ',' , '/' , ':' , ';' , '<' , '=' , '>' , '@' , and "`" are no longer escaped.

Clear the regular expression cache.

Exceptions ¶

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern. The error instance has the following additional attributes:

The unformatted error message.

The regular expression pattern.

The index in pattern where compilation failed (may be None ).

The line corresponding to pos (may be None ).

The column corresponding to pos (may be None ).

Changed in version 3.5: Added additional attributes.

Regular Expression Objects ¶

Compiled regular expression object returned by re.compile() .

Changed in version 3.9: re.Pattern supports [] to indicate a Unicode (str) or bytes pattern. See Generic Alias Type .

Scan through string looking for the first location where this regular expression produces a match, and return a corresponding Match . Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0 . This is not completely equivalent to slicing the string; the '^' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos , no match will be found; otherwise, if rx is a compiled regular expression object, rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0) .

If zero or more characters at the beginning of string match this regular expression, return a corresponding Match . Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos parameters have the same meaning as for the search() method.

If the whole string matches this regular expression, return a corresponding Match . Return None if the string does not match the pattern; note that this is different from a zero-length match.

Identical to the split() function, using the compiled pattern.

Similar to the findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search() .

Similar to the finditer() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search() .

Identical to the sub() function, using the compiled pattern.

Identical to the subn() function, using the compiled pattern.

The regex matching flags. This is a combination of the flags given to compile() , any (?...) inline flags in the pattern, and implicit flags such as UNICODE if the pattern is a Unicode string.

The number of capturing groups in the pattern.

A dictionary mapping any symbolic group names defined by (?P<id>) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.

The pattern string from which the pattern object was compiled.

Changed in version 3.7: Added support of copy.copy() and copy.deepcopy() . Compiled regular expression objects are considered atomic.

Match Objects ¶

Match objects always have a boolean value of True . Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement:

Match object returned by successful match es and search es.

Changed in version 3.9: re.Match supports [] to indicate a Unicode (str) or bytes match. See Generic Alias Type .

Return the string obtained by doing backslash substitution on the template string template , as done by the sub() method. Escapes such as \n are converted to the appropriate characters, and numeric backreferences ( \1 , \2 ) and named backreferences ( \g<1> , \g<name> ) are replaced by the contents of the corresponding group. The backreference \g<0> will be replaced by the entire match.

Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None . If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

If the regular expression uses the (?P<name>...) syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an IndexError exception is raised.

A moderately complicated example:

Named groups can also be referred to by their index:

If a group matches multiple times, only the last match is accessible:

This is identical to m.group(g) . This allows easier access to an individual group from a match:

Named groups are supported as well:

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None .

For example:

If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to None unless the default argument is given:

Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None . For example:

Return the indices of the start and end of the substring matched by group ; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match. For a match object m , and a group g that did contribute to the match, the substring matched by group g (equivalent to m.group(g) ) is

Note that m.start(group) will equal m.end(group) if group matched a null string. For example, after m = re.search('b(c?)', 'cba') , m.start(0) is 1, m.end(0) is 2, m.start(1) and m.end(1) are both 2, and m.start(2) raises an IndexError exception.

An example that will remove remove_this from email addresses:

For a match m , return the 2-tuple (m.start(group), m.end(group)) . Note that if group did not contribute to the match, this is (-1, -1) . group defaults to zero, the entire match.

The value of pos which was passed to the search() or match() method of a regex object . This is the index into the string at which the RE engine started looking for a match.

The value of endpos which was passed to the search() or match() method of a regex object . This is the index into the string beyond which the RE engine will not go.

The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b , ((a)(b)) , and ((ab)) will have lastindex == 1 if applied to the string 'ab' , while the expression (a)(b) will have lastindex == 2 , if applied to the same string.

The name of the last matched capturing group, or None if the group didn’t have a name, or if no group was matched at all.

The regular expression object whose match() or search() method produced this match instance.

The string passed to match() or search() .

Changed in version 3.7: Added support of copy.copy() and copy.deepcopy() . Match objects are considered atomic.

Regular Expression Examples ¶

Checking for a pair ¶.

In this example, we’ll use the following helper function to display match objects a little more gracefully:

Suppose you are writing a poker program where a player’s hand is represented as a 5-character string with each character representing a card, “a” for ace, “k” for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9” representing the card with that value.

To see if a given string is a valid hand, one could do the following:

That last hand, "727ak" , contained a pair, or two of the same valued cards. To match this with a regular expression, one could use backreferences as such:

To find out what card the pair consists of, one could use the group() method of the match object in the following manner:

Simulating scanf() ¶

Python does not currently have an equivalent to scanf() . Regular expressions are generally more powerful, though also more verbose, than scanf() format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.

Token

Regular Expression

, , ,

,

To extract the filename and numbers from a string like

you would use a scanf() format like

The equivalent regular expression would be

search() vs. match() ¶

Python offers different primitive operations based on regular expressions:

re.match() checks for a match only at the beginning of the string

re.search() checks for a match anywhere in the string (this is what Perl does by default)

re.fullmatch() checks for entire string to be a match

Regular expressions beginning with '^' can be used with search() to restrict the match at the beginning of the string:

Note however that in MULTILINE mode match() only matches at the beginning of the string, whereas using search() with a regular expression beginning with '^' will match at the beginning of each line.

Making a Phonebook ¶

split() splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook.

First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax

The entries are separated by one or more newlines. Now we convert the string into a list with each nonempty line having its own entry:

Finally, split each entry into a list with first name, last name, telephone number, and address. We use the maxsplit parameter of split() because the address has spaces, our splitting pattern, in it:

The :? pattern matches the colon after the last name, so that it does not occur in the result list. With a maxsplit of 4 , we could separate the house number from the street name:

Text Munging ¶

sub() replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using sub() with a function to “munge” text, or randomize the order of all the characters in each word of a sentence except for the first and last characters:

Finding all Adverbs ¶

findall() matches all occurrences of a pattern, not just the first one as search() does. For example, if a writer wanted to find all of the adverbs in some text, they might use findall() in the following manner:

Finding all Adverbs and their Positions ¶

If one wants more information about all matches of a pattern than the matched text, finditer() is useful as it provides Match objects instead of strings. Continuing with the previous example, if a writer wanted to find all of the adverbs and their positions in some text, they would use finditer() in the following manner:

Raw String Notation ¶

Raw string notation ( r"text" ) keeps regular expressions sane. Without it, every backslash ( '\' ) in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:

When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means r"\\" . Without raw string notation, one must use "\\\\" , making the following lines of code functionally identical:

Writing a Tokenizer ¶

A tokenizer or scanner analyzes a string to categorize groups of characters. This is a useful first step in writing a compiler or interpreter.

The text categories are specified with regular expressions. The technique is to combine those into a single master regular expression and to loop over successive matches:

The tokenizer produces the following output:

Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O’Reilly Media, 2009. The third edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.

Table of Contents

  • Regular Expression Syntax
  • Regular Expression Objects
  • Match Objects
  • Checking for a Pair
  • Simulating scanf()
  • search() vs. match()
  • Making a Phonebook
  • Text Munging
  • Finding all Adverbs
  • Finding all Adverbs and their Positions
  • Raw String Notation
  • Writing a Tokenizer

Previous topic

string — Common string operations

difflib — Helpers for computing deltas

  • Report a Bug
  • Show Source

Python Forum

  • View Active Threads
  • View Today's Posts
  • View New Posts
  • My Discussions
  • Unanswered Posts
  • Unread Posts
  • Active Threads
  • Mark all forums read
  • Member List
  • Interpreter

Python for Everybody 5.2 assignment

  • Python Forum
  • Python Coding
  • 2 Vote(s) - 4 Average

Unladen Swallow
Apr-07-2020, 07:10 AM
Unladen Swallow
Apr-16-2020, 06:51 AM Lux Wrote: Well, the line  seems to be why it's printing all the numbers- not sure if it's supposed to do that.
Minister of Silly Walks

Apr-16-2020, 12:09 PM (This post was last modified: Apr-25-2020, 04:38 PM by .) caseyfloyd6 Wrote: Removed spam contentIs this supposed to help with the question?
Need help on the forum? Visit
For learning more and more about python, visit
Unladen Swallow
Apr-18-2020, 04:40 AM vis1999 Wrote: please, solve my problem, when i put the term in output block(7,2,bob,10,2)again it ask enter a num and not show the resultBro plss help me for 3.3 assignment
Unladen Swallow
Apr-19-2020, 04:10 PM (This post was last modified: Apr-19-2020, 04:15 PM by .) baba04201 Wrote: Hey guys- I'm on my last assignment for Python and I need some expert assistance please.

This is the assignment:
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.

This is my code:

This is the Desired output:
Invalid input
Maximum is 10
Minimum is 2


This is my output:
7 ← Mismatch
2
bob
Please, enter only numbers.
10
4
Maximum 10
Minimum 2


I need help please.
Minister of Silly Walks

Apr-20-2020, 09:12 AM check out this code

largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try:
num = int(inp)
except:
print ("Invalid input")
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
elif num > largest:
largest = num

continue

print ("Maximum is", largest)
print ("Minimum is", smallest) First of all, this is the HOMEWORK SECTION, you aren't SUPPOSED TO WRITE CODE FOR OTHERS.
And, second, even if you write code, please use proper code tags
Need help on the forum? Visit
For learning more and more about python, visit
Unladen Swallow
Apr-25-2020, 04:04 PM baba04201 Wrote: Hey guys- I'm on my last assignment for Python and I need some expert assistance please.

This is the assignment:
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.

This is my code:

This is the Desired output:
Invalid input
Maximum is 10
Minimum is 2


This is my output:
7 ← Mismatch
2
bob
Please, enter only numbers.
10
4
Maximum 10
Minimum 2


I need help please.




TRY THIS CODE:
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
continue

print ("Maximum is", largest)
print ("Minimum is", smallest)
Minister of Silly Walks

May-31-2020, 06:11 AM vis1999 Wrote: please, solve my problem, when i put the term in output block(7,2,bob,10,2)again it ask enter a num and not show the resultTo ask another question, start a new thread , DON'T POST IN ANOTHER THREAD WRITTEN BY ANOTHER USER
gracePython3 Wrote: if smallest is None:
smallest = num
elif num < smallest:
smallest = num

if largest is None:
largest=num
elif num > largest:
largest = num

then it works.Please don't post you solution, this is the homework section. And also, if you post codes in future, please use proper code tags
Saikumar Wrote: vis1999 Wrote: please, solve my problem, when i put the term in output block(7,2,bob,10,2)again it ask enter a num and not show the resultBro plss help me for 3.3 assignmentYou need help in an assignment, post another thread, specifying all needs and requirements

Helious10 Wrote: baba04201 Wrote: Hey guys- I'm on my last assignment for Python and I need some expert assistance please.

This is the assignment:
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.

This is my code:

This is the Desired output:
Invalid input
Maximum is 10
Minimum is 2


This is my output:
7 ← Mismatch
2
bob
Please, enter only numbers.
10
4
Maximum 10
Minimum 2


I need help please.




TRY THIS CODE:
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
continue

print ("Maximum is", largest)
print ("Minimum is", smallest)Please don't post you solution, this is the homework section. And also, if you post codes in future, please use proper code tags
sanjaykumar11 Wrote: I have upload python assignment 5.2 full solution in the video


Please, start another thread for this. It would also be preferred if you didn't show this, as students need to solve assignments on their own
Need help on the forum? Visit
For learning more and more about python, visit
Unladen Swallow
.)
Minister of Silly Walks

Jun-29-2020, 02:17 AM (This post was last modified: Jun-29-2020, 02:18 AM by .) rafaelmoreno1 Wrote: hello cheakout man


That's very good, but please don't post unnecessary stuff on a thread when a person is asking a question. If you want to show this, post it probably in the board/bar section.
Need help on the forum? Visit
For learning more and more about python, visit
  45,947 Jan-23-2021, 06:27 AM
:
  13,167 Oct-22-2020, 11:57 AM
:
  12,205 Jul-15-2020, 04:54 PM
:
  5,161 Jun-06-2020, 08:59 AM
:
  6,297 May-02-2020, 01:34 AM
:
  31,981 Apr-08-2020, 06:49 AM
:
  8,662 Dec-23-2019, 08:41 PM
:
  8,647 Oct-22-2019, 08:08 AM
:
  16,099 Jan-17-2019, 07:34 AM
:
  • View a Printable Version

User Panel Messages

Announcements.

python assignment 5.2

Login to Python Forum

IMAGES

  1. python assignment 5 2

    python assignment 5.2

  2. [Coursera] Python for everybody 5.2 Assignment · GitHub

    python assignment 5.2

  3. [Coursera] Python for everybody 5.2 Assignment · GitHub

    python assignment 5.2

  4. [Solved] The fifth assignment involves writing a Python program to

    python assignment 5.2

  5. [Solved] The fifth assignment involves writing a Python program to

    python assignment 5.2

  6. GitHub

    python assignment 5.2

VIDEO

  1. INFYTQ Python Assignment-5 Day-1

  2. L-5.4 Assignment Operators

  3. Python

  4. The Joy of Computing using Python

  5. Python Assignment Operators And Comparison Operators

  6. python assignment operator

COMMENTS

  1. [Coursera] Python for everybody 5.2 Assignment · GitHub

    Fork 5 5. [Coursera] Python for everybody 5.2 Assignment. Raw. 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try,except and put out an appropriate ...

  2. Coursera Python: Programming for everybody assignment 5.2

    I have been taking Coursera's course, Programming for Everybody with Python. But one of the assignment 5.2 on week 7 got my attention. The objective is to make the user enter some numbers and enter done, when he entered all the numbers he wanted. After that, the output should be the biggest number and smallest number he entered. Here is the ...

  3. Coursera Python for Everybody EP-13

    Hi guys, in this video I solved the assignment 5.2 of Coursera Python for Everybody. Hope you find it useful.If you're new, Subscribe! https://www.youtube....

  4. python-for-everybody/wk5

    python-for-everybody. /. wk5 - assignment 5.2.py. Cannot retrieve latest commit at this time. History. Code. 32 lines (25 loc) · 831 Bytes. 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers.

  5. Week 7- Assignment 5.2

    this contains all the answers to the quizes and asssignments for "Programming for Everybody (Getting Started with Python)" on Coursera by the University of Michigan. - Coursera---Programming-for-Everybody-Getting-Started-with-Python-/Week 7- Assignment 5.2 at master · Ritik2703/Coursera---Programming-for-Everybody-Getting-Started-with-Python-

  6. Python For Everybody Assignment 5.2 solution

    Code link:https://drive.google.com/file/d/1HDYJ1BNgLPGk4P3sZRqcQvXuDNBuN1jK/view?usp=sharingCoursera: Python For Everybody Assignment 5.2 program solution | ...

  7. Coursera python for everybody assignment 5.2 solution

    Saved searches Use saved searches to filter your results more quickly

  8. Coursera Python Assignment 5.2 : r/learnpython

    The assignment is. 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

  9. Help with the assignment 5.2 in Python for everybody

    Help with the assignment 5.2 in Python for everybody. Community Support (Archived) — Edward Lundqvist asked a question. March 8, 2021 at 6:45 AM. Help with the assignment 5.2 in Python for everybody. I need help with the assignment 5.2 in Python for everybody. Somebody that could help me?

  10. Python for Everybody Answers

    The video is about the solution of the mentioned assignment of the python course named 'PYTHON FOR EVERYBODY' on coursera by Dr. Chuck

  11. 5.2. Built-in functions

    Activity: 5.2.3 The len function tells us how many items are in its argument. (functBuiltin_len) These functions can operate on any set of values, as we will see in later chapters. You should treat the names of built-in functions as reserved words (i.e., avoid using "max" as a variable name). 1. city_name = "Detroit".

  12. Assignment 5.2

    CourseraProgramming for Everybody (Getting Started with Python)Week 5 Assignment 5.2 Question: 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it…

  13. Python for Everybody 5.2 assignment

    Joined: Oct 2017. Reputation: 1. #1. Oct-07-2017, 03:58 PM. Hey guys- I'm on my last assignment for Python and I need some expert assistance please. This is the assignment: 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers.

  14. Coursera Programming for Everybody (Getting Started with Python) Week 7

    Subreddit for posting questions and asking for general advice about your python code. ... (Getting Started with Python) Week 7 Assignment 5.2 . Ques: Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters ...

  15. An issue with Assignment 5.2 [Coursera Programming for Everybody]

    An issue with Assignment 5.2 [Coursera Programming for Everybody] Even if my code matches desired output, it shows the code is incorrect. I spent all day trying to fix the issue but failed.

  16. [Coursera] Python for everybody 5.2 Assignment · GitHub

    Fork 0. [Coursera] Python for everybody 5.2 Assignment. Raw. 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try,except and put out an appropriate ...

  17. EngineerInd/Coursera-Python-for-everybody-solutions

    Hello friends, In this video we discussed about Coursera programming for everybody Assignment 5.2 answer other way it's known as Python for everybody Exercise 5.2 Complete program In this course Assignment (Exercise) are available in week 7 part.

  18. Case Study 5.2 Assignment

    Python Programming (COM 302) 17 Documents. Students shared 17 documents in this course. University Saint Leo University. Academic year: 2021/2022. ... COM 302 3.1 Case Study Assignment; COM 302 Case Study 2.1 Assignment; COM 302 Case Study 3.2 Assignment; Case Study 4.1 Assignment; Case Study 5.1 Assignment; Related documents.

  19. Python for everyone course assignment 5.2

    The assignment goal is to create a program that gets numbers as input from the user and i need to send back the largest number and the smallest number

  20. 3. An Informal Introduction to Python

    An Informal Introduction to Python — Python 3.12.4 documentation. 3. An Informal Introduction to Python ¶. In the following examples, input and output are distinguished by the presence or absence of prompts ( >>> and … ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with ...

  21. re

    search () vs. match () ¶. Python offers different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string. re.search() checks for a match anywhere in the string (this is what Perl does by default) re.fullmatch() checks for entire string to be a match.

  22. Python for Everybody 5.2 assignment

    The official dedicated python forum. (Oct-07-2017, 03:58 PM) baba04201 Wrote: Hey guys- I'm on my last assignment for Python and I need some expert assistance please. This is the assignment: 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers.