I'm new to python and trying to code a simple script.
What I want the script to do is ask the user for the first number, then asks for the second number, then prints out both of these numbers including the numbers in between and add commas.
For example:
Lets say the user inputted the number 2 as the first number
then inputs 10 as the second number
the script will print out this: 2,3,4,5,6,7,8,9,10
This is my code:
number_1 = int(raw_input("Input first number:"));
number_2 = int(raw_input("Input second number:"));
print
number_1 = int(raw_input("Input first number:"))
number_2 = int(raw_input("Input second number:"))
You can use join with a generator to create a list of numbers
numbers = ','.join(str(i) for i in range(number_1, number_2 + 1))
print(numbers)
To understand what the above line is doing, here is a more step-by-step equivalent(ish).
numberList = []
for num in range(number_1, number_2 + 1):
numberList.append(str(num))
numbers = ','.join(numberList)
print(numbers)
Related
I created some code where I try to find elements in a list given by the user using the in operator.
productNums = []
nums = int(input("How many numbers should be in your list?"))
while nums > 0:
productNums.append(input("Add a number: "))
nums -= 1
numFind = int(input("What number are you trying to find? "))
if numFind in productNums:
print("This product number is in the list")
elif numFind not in productNums:
print("Ahh, sorry. This product number is NOT in this list!")
else:
print("Huh, you're confusing me now, check your numbers pal!")
When I run this, I get the outcome that the number is not in this list, even though it is in it. Can someone tell me what I am doing wrong?
As people said above, just small issue with you integers and strings.
This is your code working:
Be careful with the indentention, initially was a mess.
productNums = []
nums = int(input("How many numbers should be in your list?"))
while nums > 0:
productNums.append(int(input("Add a number: ")))
nums -= 1
numFind = int(input("What number are you trying to find? "))
if numFind in productNums:
print("This product number is in the list")
elif numFind not in productNums:
print("Ahh, sorry. This product number is NOT in this list!")
else:
print("Huh, you're confusing me now, check your numbers pal!")
I believe its a missing conversion when u append, its appended as a string and u search for an int
Because the productNums list contains string values, not integer, so you always compare int with str variable and obtain the same result. Set productNums elements to int and it will work properly.
productNums = []
nums = int(input("How many numbers should be in your list?"))
while nums > 0:
productNums.append(int(input("Add a number: ")))
nums -= 1
numFind = int(input("What number are you trying to find? "))
if numFind in productNums:
print("This product number is in the list")
elif numFind not in productNums:
print("Ahh, sorry. This product number is NOT in this list!")
else:
print("Huh, you're confusing me now, check your numbers pal!")
You correctly cast nums and numFind to int, but you didn't do so for the input values in the while loop — so productNums is a list of single-character strings.
This change will fix it:
productNums.append(int(input("Add a number: ")))
The problem is that you are trying to find an int in a list of strings.
When you wrote the code productNums.append(input("Add a number: ")), after the user enters the code, the number would be appended into the productNums list as a string.
Further on, the numFind = int(input("What number are you trying to find? ")) makes the user enter a number. this time, the input is converted into an int. So when the line of code if numFind in productNums: runs, it sees the if as the user trying to find an int in a list of strings.
In short, you should either change the productNums.append(input("Add a number: ")) code into productNums.append(int(input("Add a number: "))), or change the line of code numFind = int(input("What number are you trying to find? ")) into numFind = input("What number are you trying to find? ").
how can i print the sum of all the numbers between any two given numbers in python.
i am not allowed to use functions like sum(). i can only use while or for loop.
i have a code which does the job but the problem is it also prints result every time after adding two numbers but i only want it to print final sum of all the numbers.
Here's the code:
...
a = int(input("Please enter a number"))
b = int(input("Please enter a number"))
n = 0
for x in range(a+1,b):
n+=x
print(n)
...
thanks
There is an Indentation Error just check the line below the for loop and give the proper indentation. You can refer to my code
a = int(input("Please enter a number: "))
b = int(input("Please enter a number: "))
n = 0
for x in range(a+1,b):
n+=x
print(n)
I have an activity for some practice for a Python class. The aim is to have unlimited amount of input from the user and assuming user is inputting correct data. The input needs to end when a blank line is detected. (this is what seems to have me stumped, trying to avoid a Value Error when doing this.)
After input ends I need to sort numbers and find the total of numbers and average of numbers.
numbers = []
num_input = []
tot_numbers = []
while num_input != "":
try:
num_input = int((input("Input a number: ")))
numbers.append(num_input)
numbers.sort()
print(numbers)
except:
pass
print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")
break
This code above is what I have come to and it works but I am not too happy with it because of using 'except'. I know there is a better way and that it probably uses an if statement within the while loop, I have been playing around with something like:
if num_input.isnumeric():
but I get an AttributeError because I can't check if a list is numeric, any help would be greatly appreciated, thankyou!
Check that the input is digit then only cast it to int and store it into the list and perform operation as below:
numbers = []
num_input = []
tot_numbers = []
while num_input != "":
num_input = input("Input a number: ")
# Check if it input is digit then only append it to the list after casting it to int
if num_input.isdigit():
numbers.append(int(num_input))
numbers.sort()
print(numbers)
else:
# if user at first attemp entres blank line then there will not be any elements in the list
# so only if list has some elements then only these operations should be doen
if len(numbers)>0:
print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")
break
Check this out:
numbers = []
num_input = []
tot_numbers = []
num_input = input("Input a number: ")
while num_input != "":
numbers.append(int(num_input))
numbers.sort()
print(numbers)
num_input = input("Input a number: ")
print("Sorted numbers: ", numbers)
tot_numbers = sum(numbers)
print("Total of numbers: ", tot_numbers)
avg_numbers = tot_numbers / len(numbers)
print("Average of numbers: ", avg_numbers)
print("Finished.")
We can achieve your desired solution without the try except, as you said. I have revised some of your code and added an explanation to the changes in the comments.
numbers = []
# first user input prompt
num_input = input("Input a number: ")
# isnumeric() checks if strings contain only numbers, and will return True if so, False if not
while num_input.isnumeric():
# append to the 'numbers' list, converting it into an int (since we're sure that it's an int now)
numbers.append(int(num_input))
# prompt the user again
num_input = input("Input a number: ")
# we can sort the list after all the elements are added, so it's called just once
numbers.sort()
tot_numbers = sum(numbers)
print("Sorted numbers: ", numbers)
print("Total of numbers: ", tot_numbers)
print("Average of numbers: ", (tot_numbers / len(numbers)))
I'll throw my hat in the ring. ;^) The key, I think, is accepting that the user input will either be a valid number or nothing at all. If nothing, then you are done looping. If a valid number then convert it to an int and add it to a list until looping is done. Once done, if any numbers at all perform your operations and print your results.
Edit: Fixed the bug Hetal caught.
Example:
numbers = []
while True:
num_text = input("Input a number: ")
if not num_text:
break
numbers.append(int(num_text))
if numbers:
print(f"Sorted numbers: {sorted(numbers)}")
tot_numbers = sum(numbers)
print(f"Sum of numbers: {tot_numbers}")
avg_numbers = tot_numbers / len(numbers)
print(f"Avg of numbers: {avg_numbers:.2f}")
print("Finished.")
Output:
Input a number: 2
Input a number: 3
Input a number: 1
Input a number:
Sorted numbers: [1, 2, 3]
Sum of numbers: 6
Avg of numbers: 2.00
Finished.
There is a few things wrong with your code, first num_input is not an array, you put a singular value into it with the input() line. Next, you don't need a pass after except if there are lines of code after it.
Here is what you want to accomplish with the type() function:
num_input = input("Here: ")
if type(num_input) == int:
num_input = int(num_input)
#code
else:
#Its not an integer
The reason why you get the error is because that method doesn't exist, type() is the one you are looking for
I wish to create a Function in Python to calculate the sum of the individual digits of a given number
passed to it as a parameter.
My code is as follows:
number = int(input("Enter a number: "))
sum = 0
while(number > 0):
remainder = number % 10
sum = sum + remainder
number = number //10
print("The sum of the digits of the number ",number," is: ", sum)
This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).
How do I calculate this but also show the original number in the print command?
Keep another variable to store the original number.
number = int(input("Enter a number: "))
original = number
# rest of the code here
Another approach to solve it:
You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.
number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
You can do it completely without a conversion to int:
ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)
It will compute garbage, it someone enters not a number
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)
As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.
I want the user of my program to provide a number and then the user must input that number of numbers.
My input collection code
inp1 = int(raw_input("Insert number: "))
inp2 = raw_input("Insert your numbers: ")
Example:
If the user enters 3 at Insert number: then they have to input three numbers (with spaces between them) at Insert your numbers:.
How do I limit the number of values in the second response to the amount specified in the first response?
I assume, we should use a list to work with.
my_list = inp2.split()
I'm using Python 2.7
Use the len function to get the length of the list, then test if it is correct:
inp1 = int(raw_input("Insert number: "))
inp2 = raw_input("Insert your numbers: ").split()
while len(inp2) != inp1:
print "Invalid input"
inp2 = raw_input("Insert your numbers: ").split()
Another approach would be to get each input on a new line seperately, with a loop:
inp1 = int(raw_input("Insert number: "))
inp2 = []
for i in range(inp1):
inp2.append(raw_input("Enter input " + str(i) + ": "))
This way, there are no invalid inputs; the user has to enter the right amount of numbers. However, it isn't exactly what your question asked.