The while conditional loop doesn't save itself - python

First, I just want to say I recently started with programming, so I'm not very good. This is my problem:
x = int(input("Write a number between 1-100: "))
while x > 100:
x = int(input("The number must be less than 101: "))
while x < 1:
x = int(input("The number must be higher than 0: "))
else:
print ("The number is:",x)
There's a way to cheat the code by doing this:
Write a number between 1-100: 101
The number must be less than 101: 0
The number must be higher than 0: 101
The number is: 101
I basically don't want the user to be able to write a number higher than 100 or lower than 1.
I'm sorry for the bad explanation but I tried my best and, one again, i recently started programming.

I would just do it like this:
x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
x = int(input("That number isn't in the range [1, 100]!: "))
else:
print ("The number is:",x)
You can of course, use nested if statements to make your prompt more informative of the error as follows:
x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
if x > 100:
x = int(input("The number must be less than 101: "))
else:
x = int(input("The number must be greater than 0: "))
else:
print ("The number is:",x)
Remember that you can test multiple conditions at once!

Use logical or to test both the condition in a single while:
while not 1 <= x <= 100:
x = int(input("The number must be in range [1, 100]: "))
This will iterate the while loop till the user enters the input less than 1 or greater than 100. You can also notice that, this will lead you to an infinite loop, if user keeps on entering invalid input. I'll let you figure out how to solve this issue.

In Python, unlike other programming languages, expressions like a < b < c have the interpretation that is conventional in mathematics. This means that you can write your while-loop just like this:
x = int(input("Write a number between 1-100: "))
while not 1 <= x <= 100:
x = int(input("The number must be in the range 1-100: "))
else:
print ("The number is:", x)

Related

Ask a user for 10 integers one at a time and store in list- python

score = int(input("Please enter a bowling score between 0 and 300: "))
while score >= 1 and score <= 300:
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
I want the user to enter 10 integers one at a time in a loop and store all ten in a list called scores.
You could do something like this, if you do not need the number entered to be restricted within an interval:
scores = []
for i in range(10):
scores.append(int(input())
This will repeatedly wait for a user input, and store each value in the scores list.
If you want the number to be between 1 and 300, simply place the code you already have in a for loop, or create a counter. You could end up with something like this:
scores = []
for i in range(10):
score = 0
while score >= 1 and score <= 300:
score = int(input("Please enter a bowling score between 0 and 300: "))
scores.append(score)
print(scores)
If you're okay assuming that all of the input will be valid, you can simply do:
scores = [int(input("Please enter a bowling score between 0 and 300: ")) for _ in range(10)]
This will raise a ValueError if the input isn't convertable to an int, though, and it also won't check for it being in the range. If you want to re-prompt them on invalid inputs until you have 10 valid inputs, you could make "get a valid score" its own function and then build the list with 10 calls to that:
def get_score() -> int:
while True:
try:
score = int(input("Please enter a bowling score between 0 and 300: "))
if not (0 <= score <= 300):
raise ValueError(f"{score} isn't between 0 and 300")
return score
except ValueError as e:
print(f"Error: {e}. Please try again.")
scores = [get_score() for _ in range(10)]
If you want for the user to input in different lines then this should work:
inputList = []
for i in range(10):
inputList.append(input("Enter: "))
But if you want the user to input all values in same line then use:
inputList = map(int, input("Enter: ").split())
Let's do a different approach than "try this" as it looks like you're a beginner.
To ask a user for an input you can use the input() function. It'll give you a string. To convert a string to a number you can utilize int(), float() or other functions depending on the properties the number should have (decimal numbers, precision, etc).
To repeat a certain action you need to use a loop. You know while as seen in your code. The loop keyword can be nested i.e. you can have a loop within a loop and you can arrange it so that it's checking for the amount of numbers outside of the number limit condition e.g.:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
or you can utilize for loop that will execute the block of code only N-times e.g. with range(10):
mylist = []
for _ in range(10):
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
With a while loop you need to watch out for cases when it might just infinitely loop because the condition is always true - like in your case:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
which will exit in case you enter a number out of the interval but does not guarantee the N-times (10-times) you want. For that to happen you might want to adjust the loop a bit with break to stop the execution after 10 values are present:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
if len(scores) >= 10:
break # stop the while loop and continue to "print(scores)"
print(scores)
However that doesn't handle cases such as inputting 0 or 1000 let's say as once you choose the number out of the interval, it'll stop the while loop even if the amount of scores is less than 10.
And then there's the obvious ValueError when you simply press Enter / Return without entering a number or supply a non-numeric value such as two which is still a number, but will only crash instead converting to 2 with int().
For the first you'd need to encapsulate the number check in other loop or refactor it into something like this:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
if num >= 1 and num <= 300:
mylist.append(num)
which handles even wrong numeric input e.g. 1000 and will ask for another number.
To handle non-numeric input there are at least two ways - you either let it fail or you check the value first:
With fail first you pass the invalid value to int() automatically and Python interpreter will generate and raise an Exception.
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError as error:
# do something with the error e.g. print(error)
# or let it silently skip to the next attempt with "continue"
continue
if num >= 1 and num <= 300:
mylist.append(num)
With value validating you can use isnumeric() method which is present on any string instance (which for your case is the return value of input() function):
mylist = []
while len(mylist) < 10:
num = input("some text")
if not num.isnumeric():
continue
if num >= 1 and num <= 300:
mylist.append(num)
And to make it more compact, you can chain the comparison, though with one unnecessary int() call when the value is correct assuming most of the values are incorrect. In that case num.isnumeric() evaluates to False first and prevents all int() calls while if the input is numberic you end up calling isnumeric() and 2x int():
mylist = []
while len(mylist) < 10:
num = input("some text")
if num.isnumeric() and 1 <= int(num) <= 300:
mylist.append(int(num))
or the other way around, assuming most of the values are correct you can go for the edge-case of incorrect value with try which would be slower afaik but should be faster than always asking whether a string isnumeric().
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError:
continue
if 1 <= num <= 300:
mylist.append(num)
Each of the approaches has its own trade off. You can strive for readability, performance, compactness or any other trait and depending on the trait there will be a way to measure it e.g. for performance you might want to use time.time and for readability a linter such as pylint.
A minor extra, in case you are creating a CLI tool, you might want to handle Ctrl + C (interrupt/kill program, will raise KeyboardInterrupt) and Ctrl + D (end input, will raise EOFError). Both can be handled with try/except.
First, you have to define the list 'scores'.
while score >= 1 and score <= 300: means that if the input value does not between 0 and 300, the loop will be over. Therefore, you may not be able to complete the list of 10 integers. You can check this condition by using if instead of while.
The while loop need to check if the scores list has 10 elements or not.
scores = []
while len(scores) < 10:
score = int(input("Please enter a bowling score between 0 and 300:"))
if (1 <= score <= 300):
scores.append(score)
else:
print("Score must be between 0 and 300")
print(scores)

Function only returning first input of a list and not continuing in the input is outside a range

I'm really new to coding (as in about 3 weeks in), and I'm writing a code where the user is asked to input a number between 0 and 100 and then this number is added to a list. Once the list reaches a length of 10 numbers, it should print the list. I'm using a function to this.
I can get it so it prints a list, but it's only printing the first number that is input. For example if I enter 5, it'll still ask for the other numbers, but it prints the list as [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]. Also if I enter a number outside the range of 0-100 it does ask you to input a different number, but then it stops and prints the list as 'None'.
Below is my code:
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
I'm guessing its to do with the while/else loop but as I said I'm new to this and it all feels so overwhelming, and trying to google this just seems to bring about super complicated things that I don't understand!! Thanks
First : Why you get [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] :
int(input("Please enter a number between 0 and 100: "))
You should give this to n first :
n=int(input("Please enter a number between 0 and 100: "))
Then, it gets out of the loops because you go in the else, and then you don't go back in the while. Then your function ended, without return, so none
To be honest, I don't understand why your code gets out of the while loop if you give a number out of the range, as the value is not given to n. If someone could explain in comment, that would be great !
I would do it like that :
def getUser():
mylist = []
while len(mylist) < 10:
n = int(input("Please enter a number between 0 and 100: "))
if (0 < n < 100):
mylist.append(n)
else:
print('This is not between 0 and 100 !')
return mylist
print("The numbers you have entered are: ", getUser())
Then you will be asked number from 0 to 100 (excluded) until you get a size of 10.
So here's what you were doing wrong
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
n = int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
You notice any difference in the edited code?
You were never re-assigning the value of the variable n
So you would just add whatever value you passed to getUser every time (and it would be the same value every time)
Don't be afraid to ask for help if you're stuck!
P.S.
You can also move a line somewhere to somewhere else to make it behave a bit better if you're up to the challenge ;)
def getUser(n):
mylist = []
t = True
while t:
n =int(input("Please enter a number between 0 and 100: "))
if n >0 and n<=100:
mylist.append(n)
if len(mylist) == 10:
return(mylist)
t = False
elif n < 0 or n >100:
print('This number is not in the range of 0-100, please input a different number:')
Ok, you are trying to use while instead of if.
Here is what I would do - I will explain it soon:
def get_user():
mylist = []
for i in range(5):
n = int(input("Please enter a number between 0 and 100: "))
if n <= 100 and 0 <= n:
mylist.append(n)
else:
print("This is not between 0 and 100 !")
i = i - 1
return mylist
Going through the code
for i in range(5)
Here we use the for to iterate through a range
of numbers (0 - 5). for will assign i to the smallest
number in the range and constantly add 1 to i every iteration until
i is out of the range. See this for more info on range
if n <= 100 and 0 <= n:
Here and checks if 2 expressions are true.
In this case, if n is less than or equal to hundred and more than or equal to 0.
You could use and any number of times you want like this:
if 1 < 100 and 100 > 200 and 20 < 40:
print("foo!")
Now look at the else :
else:
i = i - 1
Here, we subtract 1 from i and thus, decreasing our progress by one.
Also note that my function is called get_user() and not getUser().
In python, we use snake case and not camel case.
I hope this answer helps. I have given small hints in my answer.
You should google them! I also am not directly giving you the logic.
Try to figure it out! That way you would have a good understanding of what I did.

python for loop wont change value

So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code
for c in range(0,20):
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
c -=1
so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there
First, do not use range(0,20) but range(20) instead.
Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.
You probably want something of this sort:
c = 0
while c < 20:
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
continue
c += 1
an alternative and simple solution to this would be:
i=20
while(i!=0):
number = input("Enter number:\n")
number = int(number)
if (number <1 or number >9):
print("Invalid no try within 0-9 ")
else
print(number)
i-=1

Python: Simplify a Counting Program

I'm very new to Python and I've made a program which asks a user to select 2 numbers. The first must be between 1 and 10 and the second must be between 100 and 200. The program then asks the user to select a 3rd number between 1 and 5. Call these 3 numbers X, Y, and Z respectively The program then counts from X to Y in steps of Z.
Expected behaviour: If the user chose 10, 105, and 5, then Python should print 15, 20, 25, and so on, up to 105. Also, if the user tries to enter a value outside of those specified by the program, it will reject the input and ask the user to try again.
The program works but, like I said, I'm very new to Python so I would be very surprised if I've done it in the most optimal way. Do you think there's anyway to simplify the below code to make it more efficient?
Here's the code:
x = int(input("Please enter any number between 1 and 10: ").strip())
while x > 10 or x < 1:
print("No! I need a number between 1 and 10.")
x = int(input("Please enter any number between 1 and 10: ").strip())
y = int(input("Now enter a second number between 100 and 200: ").strip())
while y > 200 or y < 100:
print("No! I need a number between 100 and 200.")
y = int(input("Please enter any number between 100 and 200: ").strip())
print("Now we're going to count up from the first to the second number.")
print("You can count every number, every second number, and so on. It's up to you.")
z = int(input("Enter a number between 1 and 5: ").strip())
while z > 5 or z < 1:
print("No. I need a number between 1 and 5!")
z = int(input("Enter a number between 1 and 5: ").strip())
print("You have chosen to count from {} to {} in steps of {}.".format(x, y, z))
input("\nPress Enter to begin")
for q in range(x,y):
if q == x + z:
print(q)
x = x + z
The program works, but my gut instinct is telling me there must be a cleaner way to do this. Any suggestions you may have would be massively appreciated.
Cheers!
You can replace the loop with:
for q in range(x,y,z):
print(q)
Adding the third parameter to the range expression causes it to count up in steps.
ok, i love compacting code and i love challenges sooooooooo,
BAM
CODE:
x, y, z = None, None, None
while x == None or x > 10 or x < 1: x = int(input("Please enter any number between 1 and 10: "))
while y == None or y > 200 or y < 100: y = int(input("Please enter any number between 100 and 200: "))
print("Now we're going to count up from the first to the second number."+'\n'+"You can count every number, every second number, and so on. It's up to you.")
while z == None or z > 5 or z < 1: z = int(input("Enter a number between 1 and 5: "))
tmp=raw_input(str("You have chosen to count from {} to {} in steps of {}.".format(x, y, z))+'\n'+"Press Enter to begin")
x = x-1
for q in range(x,y,z): print(q)
print x+z
as compact as i can make it.

Python, largest odd integer

I am new to coding and have been learning a few days now. I wrote this program in Python while following along in some MIT OpenCourseware lectures and a few books. Are there anyways to more easily express the program?
Finger exercise: Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.
a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))
if a%2 ==0:
a = 0
else:
a = a
if b%2 ==0:
b = 0
else:
b = b
if c%2 ==0:
c = 0
else:
c = c
if d%2 ==0:
d = 0
else:
d = d
if e%2 ==0:
e = 0
else:
e = e
if f%2 ==0:
f = 0
else:
f = f
if g%2 ==0:
g = 0
else:
g = g
if h%2 ==0:
h = 0
else:
h = h
if i%2 ==0:
i = 0
else:
i = i
if j%2 ==0:
j = 0
else:
j = j
value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
print 'There are no odd numbers.'
else:
print max, 'is the largest odd integer.'
A more compact form would be:
from __future__ import print_function
try: # Python 2
raw_input
except NameError: # Python 3 compatibility
raw_input = input
largest = None
for i in range(1, 11):
number = int(raw_input('Enter integer #%d: ' % i))
if number % 2 != 0 and (not largest or number > largest):
largest = number
if largest is None:
print("You didn't enter any odd numbers")
else:
print("Your largest odd number was:", largest)
This uses a simple loop to track how many integers were entered, but only stores the largest odd number encountered so far.
numbers = [input('Enter a number: ') for i in range(10)]
odds = [x for x in numbers if x % 2 == 1]
if odds:
print max(odds)
else:
print 'No odd numbers input'
Explanation:
numbers = [input('Enter a number: ') for i in range(10)]
This line is using a list comprehension to ask a user for 10 numbers. These numbers will be in the list object numbers
odds = [x for x in numbers if x % 2 == 1]
Next we are using another list comprehension to filter out all numbers in numbers that are not odd. Since odd numbers modulo 2 always equal 1, we are given a new list (odd) that only contains odd numbers.
if odds:
This is using python's truthy way of testing. Particularly, if a list is empty, this is False. If the list is not empty, it is True.
print max(odds)
Finally, if the above was True, we print the max value in the odds list
else:
print 'No odd numbers input'
If the if statement was False (there are no odds) we tell the user
A running copy looks like this:
Enter a number: 10
Enter a number: 12
Enter a number: 14
Enter a number: 15
Enter a number: 16
Enter a number: 17
Enter a number: 1
Enter a number: 2
Enter a number: 19
Enter a number: 2
19
Python has objects called list and tuple which represent a sequence of numbers—they serve many of the same purposes as "arrays" in other programming languages. An example of a list is [1,2,3,4,5]
Like most popular programming languages, Python also has the concept of a for loop.
myList = [1,2,3,4,5]
for x in myList:
print(x)
Python also has a somewhat unusual but very useful construct called a "list comprehension" which combines for loop, list, and an optional conditional in one neat syntax—check out these examples and see if you can understand how the result relates to the code
myNewList = [x+1 for x in myList]
myNewSelectiveList = [x+1 for x in myList if x >= 3]
and here's an example that's particularly useful in your exercise:
userInputs = [int(raw_input('Enter a number:')) for i in range(10)]
Finally, there's a function max which can take a list as its argument and which returns the largest item in the list. Once you have your 10 inputs in a list, you should be able to use these ingredients to find the highest odd number in one pretty short line (max over a list comprehension with an if conditional in it) .
I'm also studying Guttag's book from scratch. I came with the following solution:
list = []
odds = False
print('You will be asked to enter 10 integer numbers, one at a time.')
for i in range(1,11):
i = int(input('Number: '))
list.append(i)
list = sorted(list, reverse = True)
for j in list:
if j%2 == 1:
print('The largest odd number is', j, 'from', list)
odds = True
break
if odds == False:
print('There is no odd number from', list)
I went through a long(er) version similar to the OP, but since the reading list for MIT 6.00x explicitly suggested studying topic 3.2 alongside chapter 2, I thought that lists would be an acceptable answer.
The code above should allow for negatives and zero.
I'm also working through Guttag's book, this solution uses some of the above code but might have a different spin on things. I filtered out the user input right away to include only odd integer input. If all of the input is even, then the list is empty, the code checks for an empty list, then sorts whatever is left (odd integers) and returns the last one. Please let me know if there are any hidden problems in this (I'm rather new to writing algorithms as well).
arr = []
max = 0
while max < 10:
userNum = int(input('enter an int: '))
if userNum %2 != 0:
arr.append(userNum)
max = max + 1
if len(arr) == 0:
print('all are even')
oddArr = sorted(arr)
print(oddArr[-1])
I just find this question while looking for alternative answers here is my code :
Note:I changed the code a bit so I can decide how many numbers I want to enter
alist=[]
olist=[]
num=int(input("how many numbers ? : "))
for n in range(num):
numbers=int(input())
alist.append(numbers)
for n in range(len(alist)):
while alist[n]%2 != 0 :
olist.append(alist[n])
break
else:
n +=1
olist.sort()
if len(olist) != 0:
print("biggest odd number: ",olist[-1])
else:
print("there is no odd number ")
The question is very early in the book and assumes no knowledge of lists, or indeed the Nonetype (it has mentioned it but not explained how it is used). Also, some solutions here will not work if the highest odd is negative because they initialise largest = 0 before the loop.
This works:
iters = 10
largest = "spam"
while iters != 0:
user_num = int(input("Enter an integer: "))
if user_num % 2 != 0:
if largest == "spam" or user_num > largest:
largest = user_num
iters -= 1
if largest == "spam":
print("You did not enter an odd integer")
else:
print("The largest odd integer was", largest)
itersLeft = 10 #define number of integers
x=0 #creating a variable for storing values
max=0 #creating a variable for defining max
while itersLeft!=0:
x=int(input())
itersLeft = itersLeft-1
if x%2!=0 and x>max:
max=x
if max!=0:
print(max)
elif max==0:
print("No odd number was entered")
*Note: works only for non-negative numbers
The other answers and comments suggesting lists and loops are much nicer, but they're not the only way to change and shorten your code.
In your tests, the else: a = a sections are doing nothing, assigning a to itself is no change, so they can all be removed, and the if tests brought onto one line each:
a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))
if a%2 == 0: a = 0
if b%2 == 0: b = 0
if c%2 == 0: c = 0
if d%2 == 0: d = 0
if e%2 == 0: e = 0
if f%2 == 0: f = 0
if g%2 == 0: g = 0
if h%2 == 0: h = 0
if i%2 == 0: i = 0
if j%2 == 0: j = 0
value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
print 'There are no odd numbers.'
That's the most obvious change that makes it easier to follow, without fundamentally changing the pattern of what you are doing.
After that, there are ways you could rewrite it - for example, staying with math only, even numbers divide by 2 with remainder 0 and odd numbers have remainder 1. So doing (x % 2) * x will change even numbers into 0, but keep odd numbers the same.
So you could replace all the if tests, with no test, just an assignment:
a = (a % 2) * a
b = (b % 2) * b
c = (c % 2) * c
...
if e%2 == 0: e = 0
if f%2 == 0: f = 0
The lines get slightly shorter, and if you're OK with how that works, you could merge those into the value line, and put that straight into max to get:
a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))
largest = max(a%2*a, b%2*b, c%2*c, d%2*d, e%2*e, f%2*f, g%2*g, h%2*h, i%2*i, j%2*j)
if largest == 0:
print 'There are no odd numbers.'
else:
print largest, 'is the largest odd integer.'
There isn't really a way to shorten assigning ten variables without some kind of loop, and it's arguable whether any of this is 'more easily expressing the program', but it does take 58 lines down to 17, remove 10 conditional tests, 10 else/no-op assignments and 1 variable while keeping approximately the same structure / workings.
PS. I changed max = max() because calling your variable by the same name as the function is a bad idea - you can't use the function again, and it's confusing to other Python programmers reading your code who already know what 'max' does, if you've reused that name for something else.
Edit: A commentor suggests negative numbers matter. The above writing answers "here's my code, how could I express it more easily?" without introducing any new Python or changing the behaviour, but it cannot handle negative odd numbers; max() will always choose a zero over a negative odd number, and the program will wrongly answer that "there are no odd numbers".
I don't think that's fixable without introducing any new concepts at all. And if introducing new concepts is happening, use lists and loops. Andy's suggestion to build a list that includes only the odd numbers, and then take the max value of that, for example.
But, doing something to handle them without lists -- there is another approach that hardly changes the shape of the code at all, introducing the boolean OR operation, which compares two true/false values and returns false if they are both false, otherwise true.
Python does a lot of automagic behind-the-scenes conversion to true/false to make logical operators work well. Variables with no value (zero, empty containers, empty strings) are all "false" and variables with some value are all "true".
From earlier, we have one bit that knocks even numbers to zero (a%2*a) and now we want to knock zero off the numberline completely:
-3 or None -> -3
-1 or None -> -1
0 or None -> None
1 or None -> 1
3 or None -> 3
5 or None -> 5
Introducing: a%2*a or None. It's magical, ugly, hard to follow, but valid Python -- and I'm chuffed because it's like solving a puzzle and it works, you know? Change the max line and the test to:
largest = max(a%2*a or None, b%2*b or None, c%2*c or None, d%2*d or None, e%2*e or None,
f%2*f or None, g%2*g or None, h%2*h or None, i%2*i or None, j%2*j or None)
if largest == None:
Evens get squished to zeros, zeros get squished to nothing, odds come through unchanged. Max now only has odd numbers to work with so it can now pick a negative odd number as the answer. Case closed. btw. use lists.
Compare 10 inputs and print the highest odd number
y = 0
for counter in range(10):
x = int(input("Enter a number: "))
if (x%2 == 1 and x > y):
y = x
if (y == 0):
print("All are even")
else:
print(y, "is the largest odd number")
Try the following -
def largest_odd():
q = int(input('Please enter a number: '))
w = int(input('Please enter a number: '))
e = int(input('Please enter a number: '))
lis = []
if q%2 != 0:
lis.insert (q,q)
if w%2 != 0:
lis.insert (w,w)
if e%2 != 0:
lis.insert (e,e)
Great = max(lis)
print(Great)
I am on the same exercise just now, and came up with the following solution, which seems to work just fine and is in line with the topics taught in the book so far(variable assignments, conditionals, and while loop):
EXERCISE:
Write a program that asks the user to input 10 integers, and
then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.
from __future__ import print_function
try: # Python 2
raw_input
except NameError: # Python 3 compatibility
raw_input = input
numbers_count = 0
next_input = 0
max_odd_number = None
while numbers_count < 10:
numbers_count += 1
next_input = raw_input("Please enter a number: " + str(numbers_count) +
" of 10\n")
if int(next_input)%2 != 0:
# on the entry of first number, we check max_odd_number - if it is of
# type None, it means no value has been assigned to it so far thus the
# first odd number entry becomes the first maximum odd number, be it
# positive or negative.
if max_odd_number == None:
max_odd_number = int(next_input)
if int(next_input) > max_odd_number:
max_odd_number = int(next_input)
if max_odd_number == None:
print ("None of the numbers entered were odd!")
else:
print ("Maximum odd number you entered is: " + str(max_odd_number))
Any comments would be appreciated.
Thanks,
A
A simple answer is :
x = 0
result = None;
while(x < 10):
inputx = raw_input('Enter integer #%d: ' % x)
inputx = int(inputx)
if (inputx % 2 == 1):
if(inputx > result):
result = inputx
x += 1
if result is None:
print 'no odd number was entered'
else:
print result
Note: if enter a String like '3f',it will throw a ValueError:
invalid literal for int() with base 10: '3f'
So finally ,the best anwser is
result = None
x = 0
while(x < 10):
inputx = raw_input('Enter integer #%d: ' % x)
try:
inputx = int(inputx)
except ValueError:
print'you enter value ',inputx,' is not a Integer. please try again!'
continue
if (inputx % 2 == 1):
if(inputx > result):
result = inputx
x+=1
if result is None:
print 'no odd number was entered'
else:
print 'the largest odd number is: ',result
The question if introduced in the book just after giving knowledge to if condition and while iteration statement.
Though there are lot many datatypes that could be used in python to get easy solution, we need to use only primitives that too the very basics.
The code below takes 10 user inputs(only odd) and outputs the largest of the 10 numbers.
Answer to the question:(Code)
a1= int(input("Enter the number1: "))
while a1%2 ==0:
print("Entered number is not an odd number.")
a1= int(input("Enter the number1: "))
a2= int(input("Enter the number2: "))
while a2%2 ==0:
print("Entered number is not an odd number.")
a2= int(input("Enter the number2: "))
a3= int(input("Enter the number3: "))
while a3%2 ==0:
print("Entered number is not an odd number.")
a3= int(input("Enter the number3: "))
a4= int(input("Enter the number4: "))
while a4%2 ==0:
print("Entered number is not an odd number.")
a4= int(input("Enter the number4: "))
a5= int(input("Enter the number5: "))
while a5%2 ==0:
print("Entered number is not an odd number.")
a5= int(input("Enter the number5: "))
a6= int(input("Enter the number6: "))
while a6%2 ==0:
print("Entered number is not an odd number.")
a6= int(input("Enter the number6: "))
a7= int(input("Enter the number7: "))
while a7%2 ==0:
print("Entered number is not an odd number.")
a7= int(input("Enter the number7: "))
a8= int(input("Enter the number8: "))
while a8%2 ==0:
print("Entered number is not an odd number.")
a8= int(input("Enter the number8: "))
a9= int(input("Enter the number9: "))
while a9%2 ==0:
print("Entered number is not an odd number.")
a9= int(input("Enter the number9: "))
a10= int(input("Enter the number10: "))
while a10%2 ==0:
print("Entered number is not an odd number.")
a10= int(input("Enter the number10: "))
if a1>a2 and a1>a3 and a1>a4 and a1>a5 and a1>a6 and a1>a7 and a1>a8 and a1>a9 and a1>a10:
print(str(a1) +" is the largest odd number.")
elif a2>a1 and a2>a3 and a2>a4 and a2>a5 and a2>a6 and a2>a7 and a2>a8 and a2>a9 and a2>a10:
print(str(a2) +" is the largest odd number.")
elif a3>a1 and a3>a2 and a3>a4 and a3>a5 and a3>a6 and a3>a7 and a3>a8 and a3>a9 and a3>a10:
print(str(a3) +" is the largest odd number.")
elif a4>a1 and a4>a2 and a4>a3 and a4>a5 and a4>a6 and a4>a7 and a4>a8 and a4>a9 and a4>a10:
print(str(a4) +" is the largest odd number.")
elif a5>a1 and a5>a2 and a5>a3 and a5>a4 and a5>a6 and a5>a7 and a5>a8 and a5>a9 and a5>a10:
print(str(a5) +" is the largest odd number.")
elif a6>a1 and a6>a2 and a6>a3 and a6>a4 and a6>a5 and a6>a7 and a6>a8 and a6>a9 and a6>a10:
print(str(a6) +" is the largest odd number.")
elif a7>a1 and a7>a2 and a7>a3 and a7>a4 and a7>a5 and a7>a6 and a7>a8 and a7>a9 and a7>a10:
print(str(a7) +" is the largest odd number.")
elif a8>a1 and a8>a2 and a8>a3 and a8>a4 and a8>a5 and a8>a6 and a8>a7 and a8>a9 and a8>a10:
print(str(a8) +" is the largest odd number.")
elif a9>a1 and a9>a2 and a9>a3 and a9>a4 and a9>a5 and a9>a6 and a9>a7 and a9>a8 and a9>a10:
print(str(a9) +" is the largest odd number.")
else:
print(str(a10) +" is the largest odd number.")
Hope this helps.
In my experience the way to more easily express the program is with a function.
This would have been my answer in Syntax tested for Python 3.7.6:
'''
Finger exercise:
Write a program that asks the user to input 10 integers,
and then prints the largest odd number that was entered.
If no odd number was entered, it should print a message to that effect.
'''
def LargestOdd(numbers=[]):
'''
Parameters
----------
numbers : list, whcih should contain 10 integers.
DESCRIPTION. The default is [].
Returns
-------
The largest odd integer in the list number.
'''
odd_numbers=[]
if len(numbers)==10:
for n in numbers:
if n%2 != 0:
odd_numbers.append(n)
max_numb=max(odd_numbers)
print('The largest odd number is '+str(max_numb))
else:
print('Please, enter 10 numbers')
LargestOdd([1,2,3,7,45,8,9,10,30,33])
Output: The largest odd number is 45
n = int(input("Enter the no of integers:"))
lst = []
count = 1
while count <=n:
no = int(input("Enter an integer:"))
count = count +1
if (no%2!=0):
lst.append(no)
print ("The list of odd numbers",lst)
print("The maximum number from the list of odd number is:",max(lst))
Here is my solution:
def max_odd():
"""Returns largest odd number from given 10 numbers by the use.
if the input is not valid, the message is displayed to enter valid numbers"""
x = [input('Enter a value: ') for i in range(10)]
x = [int(i) for i in x if i]
if x:
try:
x = [i for i in x if i%2 != 0]
return(max(x))
except:
return('All even numbers provided.')
else:
return('Please enter a valid input')
I started learning coding from Guttag's book. And since this is in the 2nd chapter, the solution follows only basic if condition and while loop
#input 10 integers
n1 = int(input('Enter 1st integer: '))
n2 = int(input('Enter 2nd integer: '))
n3 = int(input('Enter 3rd integer: '))
n4 = int(input('Enter 4th integer: '))
n5 = int(input('Enter 5th integer: '))
n6 = int(input('Enter 6th integer: '))
n7 = int(input('Enter 7th integer: '))
n8 = int(input('Enter 8th integer: '))
n9 = int(input('Enter 9th integer: '))
n10 = int(input('Enter 10th integer: '))
#create list from input
list = [n1,n2,n3,n4,n5,n6,n7,n8,n9,n10]
largest = list[0] #Assign largest to the first integer
x = 1 #index starts at 1
while x < len(list):
if list[x]%2 != 0:
if list[x] > largest:
largest = list[x]
x += 1
if largest%2 == 0:
print('All numbers are even')
else:
print('Largest odd number is', largest)
#This is the simplest program for this question
a=[input('Enter a number: ') for i in range(10)]
#This gets 10 inputs from the user and stores it as a string in a list
b=[int(a[i]) for i in range(10)]
#Here the string values were converted into integer values
for i in range(10):
if max(b)%2==0:
b.remove(max(b))
#Now the loop checks for the max number and if it's even it deletes it.
c=max((b),default='Nil')
if c=="Nil":
print("Please enter an odd number")
else:
print(c,"Is the Largest Odd Number")
#Now the largest number left is an odd number and we finally print it!!!!
This code should work work as well. Syntax tested for python 2.7
def tenX(): #define function
ten = [] #empty list for user input
odds = [] #empty list for odd numbers only
counter = 10
ui = 0
while counter > 0 :
ui = raw_input('Enter a number: ')
ten.append(int(ui)) #add every user input to list after int conversion
counter -= 1
for i in ten:
if i % 2 != 0:
odds.append(i)
print "The highest number is", max(odds) #max() returns highest value in a list
>>> tenX() #call function

Categories