I've been searching for quite a while, and I can't seem to find the answer to this. I want to know if you can use variables when using the range() function. For example, I can't get this to work:
l=raw_input('Enter Length.')
#Let's say I enter 9.
l=9
for i in range (0,l):
#Do something (like append to a list)
Python tells me I cannot use variables when using the range function. Can anybody help me?
Since the user inputs is a string and you need integer values to define the range, you can typecast the input to be a integer value using int method.
>> l=int(raw_input('Enter Length: ')) # python 3: int(input('Enter Length: '))
>> for i in range (0,l):
>> #Do something (like append to a list)
You ask user to input a number
l = raw_input('Enter Length: ')
But the problem is that entered number will be presented as a string instead of int. So you have to convert string 2 int
l = int(raw_input('Enter Length: '))
If you use Python 2.X you also can optimize your code - instead of range you might use xrange. It works much faster.
for i in xrange (l):
#Do something (like append to a list)
In Python 3.X xrange was implemented by default
Try this code:
x = int(input("the number you want"))
for i in range(x):
Related
I am currently a beginner in Python. This is my problem: First, the program asks that you input a number.
For example, if I put 1, I get 1 out. If i put 2, i get 12 out. If I put 3, I get 123. If I put 4, I get 1234. That is the gist of this set of problem. However, I developed a mathematical equation that works if I put it through a loop:
if __name__ == '__main__': # ignore this part
n = int(input())
s = 1
while s > n:
z = s*10**(n-s)
s += 1
answer = z
if s == n:
print(z)
When I tried to run this code, I got nothing, even though I added print at the end. What is it that I am doing wrong here? For anyone answering the problem, introduce any concepts that you know that may help me; I want to learn it.
Please enlighten me. Don't exactly give me the answer....but try to lead me in the right direction. If I made a mistake in the code (which I am 100% sure I did), please explain to me what's wrong.
It's because your while loop condition is backwards. It never enters the loop because s is not bigger than n. It should be while s < n
Use a for loop using range() as in
for i in range(1, n+1):
where n is the input so that the numbers from 1 till n can be obtained.
Now use a print() to print the value of i during each iteration.
print() by default will add a newline at the end. To avoid this, use end argument like
print(var, end='')
Once you are familiar with this, you can also use list comprehension and join() to get the output with a single statement like
print( ''.join([str(i) for i in range(1, n+1)]) )
Take the input as you've done using input() and int() although you might want to include exception handling in case the input is not an integer.
See Error handling using integers as input.
Here is the solution:
Using string
a = int(input())
# taking the input from the user
res=''
# using empty string easy to append
for i in range(1,a+1):
# taking the range from 1 (as user haven't said he want 0, go up to
# a+1 number (because range function work inclusively and will iterate over
# a-1 number, but we also need a in final output ))
res+=str(i)
# ^ appending the value of I to the string variable so for watch iteration
# number come append to it.
# Example : 1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
# so after each iteration number added to it ,in example i have taken a=9
sol = int(res) #converting the res value(string) to int value (as we desire)
print(sol)
In one line, the solution is
a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))
Try this,
n = int(input('Please enter an integer'))
s = 1
do:
print(s)
s+=1
while s == n
this works.
(Simple and Short)
I'm really new to Python, and I'm trying to write a python program that asks the user how many pieces of data they have, and then the user inputs that data which goes into an array. The problem I'm running into is that I must define the length of the array for the program to work, but I want the user to define that as "x". That way, the user can put a specific amount of data into the array.
Here's what I have
i = 0
x = int(input("How many iterations"))
odds = [] #This is where I do not know how to define the array as whatever amount of pieces of data the user wants.
while i < x:
odds[i] = input("Enter number ")
i = i+1
The error message says
IndexError: list assignment index out of range
I'm pretty new to programming, so any help would be much appreciated. I totally understand that I may be going about this problem TOTALLY the wrong way, so please let me know how you would do it. Thanks!
odds is empty so odds[i] is not going to work. try odds.append(input("...")) instead, which will append the new element to the end of odds
In the command
odds[i] = input("Enter number ")
you wanted to change the i-th member of the odds list - but such member yet doesn't exist.
Use
odds.append(input("Enter number "))
instead.
Note: And, instead of the construction
while i < x:
...
i = i + 1
you may use more Pythonic way
for __ in range(x):
...
without the need of using the variable i. (__ - two underline characters - is a correct Python name used for for never used variables).
So your full code will change to
x = int(input("How many iterations: "))
odds = []
for __ in range(x):
odds.append(input("Enter number: ")) # Note: you will append strings, not numbers
The script tries to reference an entry in the list that doesn't exist. Use append to append. Also you don't need a while loop for this. Corrected code:
x = int(input("How many iterations"))
odds =[]
for i in range(x):
odds.append(float(input("Enter number: ")))
So I'm trying to create a program in Python that:
A) Prompts a user to enter a number a certain amount of times
B) Then stores those numbers in a list and prints them in reverse order.
This is my code:
for numbers in range (1,4):
print("Please enter a number.")
numbers = input()
numbersList = list(reversed(str(numbers)))
print(numbersList)
When I run it, it just prints <list_reverseiterator object at 0x105447da0>. And even when I tried it without adding 'reversed' in the code, instead of printing a list of ALL the numbers entered in reverse order like I want it to, it spits out the most recent number entered in list format. So if I enter '4' for a number, it just prints: ['4']. No idea why it's doing that. Any help would be appreciated. Thanks.
If I understood correctly, this is what you're looking for:
numbers = []
for i in range (1,4):
print("Please enter a number.")
numbers.append(input())
numbersList = str(numbers)
numbersList.reverse()
print (numbersList)
As commented, i is an iterator generated by range command. One way to collect 3 numbers from the user is to append them into a list, numbers in this case.
After that you can process your list outside the loop. It also seems more viable to reverse the list once it is fully created which again points to outside the loop. I use Python 2.7 so the solution is a bit different than your initial one, but the result is as intended - first it converts all the numbers to strings using map and then it reverses the list in place using reverse.
Try something like this:
numbersList = []
for numbers in range (1,4):
print("Please enter a number.")
numbersList.append(input())
numbersList.reverse()
print(numbersList)
First, you have to define numbersList. Then, you append values to in while in the loop and finally print it out.
Your issue was that you were defining the list each time you ran the for loop (3 times in the above example) and so it only had the last value. (Also, you were tying to print it out each iteration as well).
Also, a 'point of interest' - you can use input("User prompt here: ") to avoid using print() the line before.
l=[]
for _ in range(1,5):
l.append(int(input("enter the number: ")))
print(l[::-1])
I'm currently learning python so I apologize in advance for the messiness of my code. My function is meant to take in a single string and add the string numbers together. i.e. A string argument of 123 will become 1 + 2 + 3 and return 6.
My issue is when I iterate through my list - python keeps indicating that the variable has been referenced before any value has been assigned. However when I print out the values being calculated they are correct. Even more confusing is that when I return them - they are incorrect. I can't seem to work out where I'm going wrong. Could anyone tell me what the issue may be?
Thank you!
listy = []
global total
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy.append(i)
print listy
#listy is printing [5,3,4]
for i in listy:
total += int(i)
return total
print digit_sum(x)
I'm not really sure what's going on in your code there, especially with the messed up indentation, but your problem is easily sovled:
sum(map(int, str(534)))
It makes the number a string, then converts each digit to an int with map, then just sums it all.
If your concern is only about summing a string of numbers, then list comprehension itself would do or as #Maltysen suggested you could use map
sum([int(x) for x in "534"])
pretty simple:
You can use a map or a list comprehension. They are pretty much equivalent. Other people gave an answer using map but I decided to use a list comprehension.
s = "1234567"
sum([int(character) for character in s])
I believe I have worked out what was wrong with my code. As I am still new to Python, I made some very novice mistakes such as not realizing declaring a variable outside the local function would result in the solution not being what I had expected.
Due to my returns being placed incorrectly as well as my listy [] variable being instantiated outside my function, instead of reading each number once, it would read it three times.
This has now been corrected in the code below.
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
total = 0
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy = []
listy.append(i)
# print listy
#listy is printing [5,3,4]
for i in listy:
print i
total+= int(i)
print total
break
return total
print digit_sum(111)
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 20 days ago.
I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?
I'm looking for the equivalent of:
scanf("%d%d", &i, &j); // accepts "10 20\n"
One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?
This is not for live use. Just for learning..
No, the usual way is raw_input().split()
In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings
Don't use input() for that. Consider what happens if the user enters
import os;os.system('do something bad')
You can also read from sys.stdin
import sys
a,b = map(int,sys.stdin.readline().split())
I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:
i,j = raw_input("Enter two values: ").split()
i = int(i)
j = int(j)
Granted, the code is not as elegant as the one-liners using C's scanf or C++'s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.
In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .
In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. str values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python's built-in int or float function.
I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.
Firstly read the complete line into a string like
string = raw_input()
Then use a for loop like this
prev = 0
lst = []
index = 0
for letter in string :
if item == ' ' or item == '\n' :
lst.append(int(string[prev:index])
prev = index + 1
This loop takes a full line as input to the string and processes the parts in it individually and then appends the numbers to the list - lst after converting them to integers .
you can read 2 int values by using this in python 3.6.1
n,m = map(int,input().strip().split(" "))
You can also use this method for any number of inputs. Consider the following for three inputs separated by whitespace:
import sys
S = sys.stdin.read()
S = S.split()
S = [int(i) for i in S]
l = S[0]
r = S[1]
k = S[2]
or you can do this
input_user=map(int,raw_input().strip().split(" "))
You can use this method for taking inputs in one line
a, b = map(int,input().split())
Keep in mind you can any number of variables in the LHS of this statement.
To take the inputs as string, use str instead of int
And to take list as input
a = list(map(int,input.split()))
in python 3.9 , use a, b = map(int,input().split())
because you will get raw_input() not defined