Sort function in Python is bugged? - python-3.x

I know this doubt looks quite easy but i just cant get my head to wrap around it.
I was just fooling around with python sorting, when i noticed this.
If I gave in the input as 21 ,8, 4. The output i would receive would be 21, 4,8. Not 4,8,21. What i am assuming is that python is only taking the first digit and comparing, but that is not what i want. How do i fix this problem?
lst=list()
i=0
while i < 3:
number=input("Give me a number: \n")
lst.append(number)
i=i+1
print("\n")
lst.sort()
print("The list of ordered numbers are:")
for j in lst:
print(j)
Terminal output

The only mistake you are making is by taking input as string,
The line number=input("Give me a number: \n") should be number=int(input("Give me a number: \n"))
If you use input() only then it takes every input as string, you need to convert that to int in your case, using int()

The sort function works on both integers and strings.
But if you want it to be implemented for the integers, you need to accept the input as integers for which you can use something like this.
lst=list()
i=0
while i < 3:
number=int(input("Give me a number: \n"))
lst.append(number)
i=i+1
print("\n")
lst.sort()
print("The list of ordered numbers are:")
for j in lst:
print(j)

Related

Loop won't finish...Poor indentation?

I am new to python and Jupyter Notebook
The objective of the code I am writing is to request the user to introduce 10 different integers. The program is supposed to return the highest odd number introduced previously by the user.
My code is as followws:
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: '))
if c%2==0:
print('The number is even')
elif c> y
y=c
print('y')
i=i+1
My loop is running over and over again, and I don't get a solution.
I guess the code is well written. It must be a slight detail I am not seeing.
Any help would be much appreciated!
You have elif c > y, you should just need to add a colon there so it's elif c > y:
Yup.
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: ')) # This line was off
if c%2==0:
print('The number is even')
elif c> y: # Need also ':'
y=c
print('y')
i=i+1
You can right this in a much compact fashion like so.
Start by asking for 10 numbers in a single line, separated by a space. Then split the string by , into a list of numbers and exit the code if exactly 10 numbers are not provided.
numbers_str = input("Input 10 integers separated by a comma(,) >>> ")
numbers = [int(number.strip()) for number in numbers_str.split(',')]
if len(numbers) != 10:
print("You didn't enter 10 numbers! try again")
exit()
A bad run of the code above might be
Input 10 integers separated by a comma(,) >>> 1,2,3,4
You didn't enter 10 numbers! try again
Assuming 10 integers are provided, loop through the elements, considering only odd numbers and updating highest odd number as you go.
largest = None
for number in numbers:
if number % 2 != 0 and (not largest or number > largest):
largest = number
Finally, check if the largest number is None, which means we didn't have any odd numbers, so provide the user that information, otherwise display the largest odd number
if largest is None:
print("You didn't enter any odd numbers")
else:
print("Your largest odd number was:", largest)
Possible outputs are
Input 10 integers separated by a comma(,) >>> 1,2,3,4,5,6,7,8,9,10
Your largest odd number was: 9
Input 10 integers separated by a comma(,) >>> 2,4,6,8,2,4,6,8,2,4
You didn't enter any odd numbers

"Invalid Syntax" on while-if-elif?

I recently got into python3.x and want to have a script where a random number is generated and stored in a variable, the user has to input a number and the script then checks if the number is greater or smaller (or the same) than the generated number and answers accordingly.
So far I got
import random
n = random.randint(1, 101)
a = input("Please enter your number: ")
while not(int(a) == n):
if(int(a) > n)
print("Your number is smaller."):
elif(int(a) < n)
print("Your number is greater."):
But in this code I get "Invalid Syntax in line 5", the first if. How do I get rid of that? Also, how do I loop the whole while-block until the number is correct?
You are missing a colon on line 5 and you have colons on like 6 and 8.
You should read up on a python tutorial somewhere on how the python syntax works, but in general colons are used to denote a new indented block, so whenever you write indented code, it should be preceeded by a colon
Try this: Actually you left colon in if and elif at last.
import random
n = random.randint(1, 101)
a = input("Please enter your number: ")
while not(int(a) == n):
if(int(a) > n):
print("Your number is smaller.")
elif(int(a) < n):
print("Your number is greater.")

for some input in python3 in increasing order of list not come right

my code is:
n=int(input())
list_1 = []
for i in range(n):
list_1.append(input())
list_2=[]
#print(list_1)
while list_1:
minimum = list_1[0]
for x in list_1:
if x < minimum:
minimum = x
list_2.append(minimum)
list_1.remove(minimum)
print (' '.join(map(str, list_2)))
all output come correct but incorrect come in some input like
4
10
3
7
6
please help
Your list 'list_1' is a list of strings, and for strings minimums work in a different manner. For example, '10' < '3' is True.
Change the line:
list_1.append(input())
To:
list_1.append(int(input()))
The first thing you should do when posting questions here is properly explain your problem, and what the code does.
Now for your question, Mono found the issue in your code, but you should know that you do not need all this to sort a list of numbers. It already exists in the language. Use the sort() function on the list, like this:
print("This script will ask you for numbers and print them back to you in order.")
print("Enter how many numbers you will input: ", end="")
n=int(input())
list_1 = []
print("Please type each number.")
for i in range(n):
print(" Number", i, ": ", end='')
list_1.append(int(input()))
list_1.sort()
print("These are your numbers, in order:")
print (' '.join(map(str, list_1)))
The output is:
This script will ask you for numbers and print them back to you in order.
Enter how many numbers you will input: 4
Please type each number.
Number 0 : 10
Number 1 : 2
Number 2 : 8
Number 3 : 3
These are your numbers, in order:
2 3 8 10

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to 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.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

How to do a backspace in python

I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
print(e)
if e != times:
print("+")
else:
pass
Out:
Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5
How do I make the equation in just one single line like this:
1+2+3+4+5
I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
equation_string = ""
for e in range(1,times+1):
equation_string += str(e)
if e != times:
equation_string += "+"
else:
pass
print(equation_string)
Basically, what happens is you store the temporary equation in equation_str so it's built like this:
1
1+
1+2
1+2+
...
And then you print equation_str once it's completely built. The output of the modified program is this
Enter a number: 5
5
*
**
***
****
*****
Total stars:
15
Equation:
1+2+3+4+5
Feel free to post a comment if anything is unclear.
Instead of your original for loop to print each number, try this:
output = '+'.join([str(i) for i in range(1, times + 1)])
print(output)
Explanation:
[str(i) for i in range(1, times + 1)] is a list comprehension that returns a list of all your numbers, converted to strings so that we can print them.
'+'.join(...) joins each element of your list, with a + in between each element.
Alternatively:
If you want a simple modification to your original code, you can simply suppress the newline from each print statement with the keyword paramater end, and set this to an empty string:
print(e, end='')
(Note that I am addressed the implied question, not the 'how do I do a backspace' question)
Too long for a comment, so I will post here.
The formatting options of python can come into good use, if you have a sequence you wish to format and print.
Consider the following...
>>> num = 5 # number of numbers to generate
>>> n = num-1 # one less used in generating format string
>>> times = [i for i in range(1,num+1)] # generate your numbers
>>> ("{}+"*n + "{}=").format(*times) # format your outputs
'1+2+3+4+5='
So although this doesn't answer your question, you can see that list comprehensions can be brought into play to generate your list of values, which can then be used in the format generation. The format string can also be produced with a l.c. but it gets pretty messy when you want to incorporate string elements like the + and = as shown in the above example.
I think you are looking for the end parameter for the print function - i.e. print(e, end='') which prints each value of e as it arrives followed by no space or newline.

Resources