Related
I tried to use input (Py3) /raw_input() (Py2) to get a list of numbers, however with the code
numbers = input()
print(len(numbers))
the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.
In Python 3.x, use this.
a = [int(x) for x in input().split()]
Example
>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>
It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:
Python 3:
s = input()
numbers = list(map(int, s.split()))
Python 2:
s = raw_input()
numbers = map(int, s.split())
Using Python-like syntax
The standard library provides ast.literal_eval, which can evaluate certain strings as though they were Python code. This does not create a security risk, but it can still result in crashes and a wide variety of exceptions.
For example: on my machine ast.literal_eval('['*1000 + ']'*1000) will raise MemoryError, even though the input is only two kilobytes of text.
As explained in the documentation:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.
(The documentation is slightly inaccurate. ast.literal_eval also supports addition and subtraction of numbers - but not any other operators - so that it can support complex numbers.)
This is sufficient for reading and parsing a list of integers formatted like Python code (e.g. if the input is [1, 2, 3]. For example:
>>> import ast
>>> ast.literal_eval(input("Give me a list: "))
Give me a list: [1,2,3]
[1, 2, 3]
Do not ever use eval for input that could possibly ever come, in whole or in part, from outside the program. It is a critical security risk that enables the creator of that input to run arbitrary code.
It cannot be properly sandboxed without significant expertise and massive restrictions - at which point it is obviously much easier to just use ast.literal_eval. This is increasingly important in our Web-connected world.
In Python 2.x, raw_input is equivalent to Python 3.x input; 2.x input() is equivalent to eval(raw_input()). Python 2.x thus exposed a critical security risk in its built-in, designed-to-be-beginner-friedly functionality, and did so for many years. It also has not been officially supported since Jan 1, 2020. It is approximately as outdated as Windows 7.
Do not use Python 2.x unless you absolutely have to; if you do, do not use the built-in input.
Using your own syntax
Of course, it is clearly possible to parse the input according to custom rules. For example, if we want to read a list of integers, one simple format is to expect the integer values separated by whitespace.
To interpret that, we need to:
Split the string at the whitespace, which will give us a list
Convert strings into integers, and apply that logic to each string in the list.
All of those tasks are covered by the common linked duplicates; the resulting code is shown in the top answer here.
Using other syntaxes
Rather than inventing a format for the input, we could expect input in some other existing, standard format - such as JSON, CSV etc. The standard library includes tools to parse those two. However, it's generally not very user-friendly to expect people to type such input by hand at a prompt. Normally this kind of input will be read from a file instead.
Verifying input
ast.literal_eval will also read and parse many things that aren't a list of integers; so subsequent code that expects a list of integers will still need to verify the input.
Aside from that, if the input isn't formatted as expected, generally some kind of exception will be thrown. Generally you will want to check for this, in order to repeat the prompt. Please see Asking the user for input until they give a valid response.
You can use .split()
numbers = raw_input().split(",")
print len(numbers)
This will still give you strings, but it will be a list of strings.
If you need to map them to a type, use list comprehension:
numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)
If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval
Another way could be to use the for-loop for this one.
Let's say you want user to input 10 numbers into a list named "memo"
memo=[]
for i in range (10):
x=int(input("enter no. \n"))
memo.insert(i,x)
i+=1
print(memo)
you can pass a string representation of the list to json:
import json
str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)
user enters in the list as you would in python: [2, 34, 5.6, 90]
Answer is trivial. try this.
x=input()
Suppose that [1,3,5,'aA','8as'] are given as the inputs
print len(x)
this gives an answer of 5
print x[3]
this gives 'aA'
a=[]
b=int(input())
for i in range(b):
c=int(input())
a.append(c)
The above code snippets is easy method to get values from the user.
Get a list of number as input from the user.
This can be done by using list in python.
L=list(map(int,input(),split()))
Here L indicates list, map is used to map input with the position, int specifies the datatype of the user input which is in integer datatype, and split() is used to split the number based on space.
.
I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.
a = [int(x) for x in input()]
a
Here is my ouput:
11111
[1, 1, 1, 1, 1]
try this one ,
n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
a=raw_input()
if(a.isdigit()):
l1.insert(i,float(a)) #statement1
else:
l1.insert(i,a) #statement2
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.
I tried to use input (Py3) /raw_input() (Py2) to get a list of numbers, however with the code
numbers = input()
print(len(numbers))
the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.
In Python 3.x, use this.
a = [int(x) for x in input().split()]
Example
>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>
It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:
Python 3:
s = input()
numbers = list(map(int, s.split()))
Python 2:
s = raw_input()
numbers = map(int, s.split())
Using Python-like syntax
The standard library provides ast.literal_eval, which can evaluate certain strings as though they were Python code. This does not create a security risk, but it can still result in crashes and a wide variety of exceptions.
For example: on my machine ast.literal_eval('['*1000 + ']'*1000) will raise MemoryError, even though the input is only two kilobytes of text.
As explained in the documentation:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.
(The documentation is slightly inaccurate. ast.literal_eval also supports addition and subtraction of numbers - but not any other operators - so that it can support complex numbers.)
This is sufficient for reading and parsing a list of integers formatted like Python code (e.g. if the input is [1, 2, 3]. For example:
>>> import ast
>>> ast.literal_eval(input("Give me a list: "))
Give me a list: [1,2,3]
[1, 2, 3]
Do not ever use eval for input that could possibly ever come, in whole or in part, from outside the program. It is a critical security risk that enables the creator of that input to run arbitrary code.
It cannot be properly sandboxed without significant expertise and massive restrictions - at which point it is obviously much easier to just use ast.literal_eval. This is increasingly important in our Web-connected world.
In Python 2.x, raw_input is equivalent to Python 3.x input; 2.x input() is equivalent to eval(raw_input()). Python 2.x thus exposed a critical security risk in its built-in, designed-to-be-beginner-friedly functionality, and did so for many years. It also has not been officially supported since Jan 1, 2020. It is approximately as outdated as Windows 7.
Do not use Python 2.x unless you absolutely have to; if you do, do not use the built-in input.
Using your own syntax
Of course, it is clearly possible to parse the input according to custom rules. For example, if we want to read a list of integers, one simple format is to expect the integer values separated by whitespace.
To interpret that, we need to:
Split the string at the whitespace, which will give us a list
Convert strings into integers, and apply that logic to each string in the list.
All of those tasks are covered by the common linked duplicates; the resulting code is shown in the top answer here.
Using other syntaxes
Rather than inventing a format for the input, we could expect input in some other existing, standard format - such as JSON, CSV etc. The standard library includes tools to parse those two. However, it's generally not very user-friendly to expect people to type such input by hand at a prompt. Normally this kind of input will be read from a file instead.
Verifying input
ast.literal_eval will also read and parse many things that aren't a list of integers; so subsequent code that expects a list of integers will still need to verify the input.
Aside from that, if the input isn't formatted as expected, generally some kind of exception will be thrown. Generally you will want to check for this, in order to repeat the prompt. Please see Asking the user for input until they give a valid response.
You can use .split()
numbers = raw_input().split(",")
print len(numbers)
This will still give you strings, but it will be a list of strings.
If you need to map them to a type, use list comprehension:
numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)
If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval
Another way could be to use the for-loop for this one.
Let's say you want user to input 10 numbers into a list named "memo"
memo=[]
for i in range (10):
x=int(input("enter no. \n"))
memo.insert(i,x)
i+=1
print(memo)
you can pass a string representation of the list to json:
import json
str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)
user enters in the list as you would in python: [2, 34, 5.6, 90]
Answer is trivial. try this.
x=input()
Suppose that [1,3,5,'aA','8as'] are given as the inputs
print len(x)
this gives an answer of 5
print x[3]
this gives 'aA'
a=[]
b=int(input())
for i in range(b):
c=int(input())
a.append(c)
The above code snippets is easy method to get values from the user.
Get a list of number as input from the user.
This can be done by using list in python.
L=list(map(int,input(),split()))
Here L indicates list, map is used to map input with the position, int specifies the datatype of the user input which is in integer datatype, and split() is used to split the number based on space.
.
I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.
a = [int(x) for x in input()]
a
Here is my ouput:
11111
[1, 1, 1, 1, 1]
try this one ,
n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
a=raw_input()
if(a.isdigit()):
l1.insert(i,float(a)) #statement1
else:
l1.insert(i,a) #statement2
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.
I'm brand new to python and my teacher showed me an example on how to write multiple variables in a print function but I am getting a syntax error. Did I write it wrong? How can I fix this?
def fahrenheit_to_celcius(num):
celciusTemp=(num-32)*0.556
print("When you convert %s to celcius the result is %s",%(num,
celciusTemp))
Above is just a simple function I'm writing as part of some beginner exercise. But when I run the code it says my print function has invalid syntax.
Use this code.
def fahrenheit_to_celcius(num):
celciusTemp=(num-32)*0.556
print("When you convert %s to celcius the result is %s" % (num,
celciusTemp))
Because you seem to be working in Python 3, there is a really cool way to format strings that I absolutely love. With this method, your print() would look like
print(F"When you convert {num} to Celsius, the result is
{celsiusTemp}.")
With this method, you can write pretty much any python in between {} and python automatically puts the returned output of that code in your string.
Here I fixed your code. I also added a few lines of extra code so that it is a bit more readable for your prof. It should be easy enough for you to understand. Here's the code:
def fahrenheit_to_celcius(num):
celciusTemp=(num-32)*0.556
print("When you convert {} fahrenheit to celcius the result is {:f}".format(num,celciusTemp))
num = int(input("Input the degrees of fahrenheit you want to convert to celcius:"))
fahrenheit_to_celcius(num)
Hope it helps :)
You can use Format. In your case. :f (Displays fixed point number (Default: 6))
string = "when you convert {} to celcius the result is {:f}".format(num,celciusTemp)
print(string)
More information please check this link https://www.programiz.com/python-programming/methods/string/format
Remove the comma before the percent sign.
So I'm pretty new to programming and I don't understand how to do this problem.
Egg cartons each hold exactly 12 eggs. Write a program which reads an integer number of eggs from input(), then prints out two numbers: how many cartons can be filled by these eggs, and how many eggs will be left over. I would really appreciate the help!
At first, what you are looking for is the modulo operator and the function math.floor()
Modulo
from wikipedia:
In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).
for example:
12%12=0
24%12=0
25%12=1
this does fit your needs for the eggs that are leftover.
Math.floor()
returns the largest following integer.
eg.:
Math.floor(13/2)
would be the same as
Math.floor(6.5)
and result in 6.
This function should solve your problem with the fully filled egg cartons.
Hint
remember to import floor() properly.
from math import floor
First, try to figure the rest out on your own.
You shouldn't look at this until your code is done.
Either way I'm not your mom, if you wanna die dumb I tried to prevent it.
https://github.com/AiyionPrime/EggCartons
One last thing.
It does not matter wether your attempts to solve a problem were stupid or failed hard.
But if you ever expect an answer to one of your problems you should explain what you tried.
We're not here to solve your problems, but to help you understand to do it.
I remember that text. It comes from a site for exercising with Python coding.
Its name is Computer Science Circles, if I remember correctly.
Anyway, the correct answer at that specific exercise is:
eggs = input() #Reads imput, assigning it to the "eggs" variable
eggs = int(eggs) #Converts the "eggs" variable into an int
print(eggs // 12) #Performs a division, showing the result and ignoring the remainder, giving you the exact number of cartons that can be filled by the "eggs" variable
print(eggs % 12) #Performs a second division, this time showing only the remainder, giving you the exact number of eggs that will be left over
I just started learning Python and I need help on creating this pattern:
******
*****
****
***
**
*
I currently have this code:
base = 6
for row in range (base):
for col in range (row+1):
print('*', end='')
print()
which becomes:
*
**
***
****
*****
******
What you need here is to track how many spaces you need—and you pretty much already have code for that—and how many '*'s you need. Then for each line, you need to print the appropriate number of ' 's, and the appropriate number of '*'s. Since my guess is that you want the total width to stay constant, you'll want x number of ' 's, and n-x number of '*'s, where n is the number of lines / total width you want.
So for example
n=6; print('\n'.join(' '*x+'*'*(n-x) for x in range(0,n)))
will work.
If this is a homework problem, I'd advise against turning in the above solution, however. It would be better to write it out in a standard way.
Since this might be some homework or something as specified above by #cge as well, I just hope that a difference of two years is enough and I am writing the answer to tell about something which lot many aren't well aware of in Python.
See the pattern you are trying to make is one of the most common things asked to form in any programming language and quite easy to make in Java or C++. But this same thing came to my mind while thinking of how will I make such pattern in Python because while using Python, the print() function changes the line whenever used. So there is no feature like we have in Java where print and println are two different things.
Now here's an interesting thing to know about. In Python 3, with the introduction of print as a method, some other things also came with it which also had this thing called end="\n" attached to it as default. This is the reason why when being called, the print function ends up on the next line. So all we need to do is not let the default work.
Here's how the code works:
for i in range(6):
for x in range(6):
if i!=0:
print(" ",end="")
i-=1
else:
print("*",end="")
print()
So we see that using the above additional features of the print function, we can make use of and create such patterns as you have asked.
I think you're making it too complicated
base = 6
for i in range(base, 0, -1):
print "*"*i
and you get:
******
*****
****
***
**
*
Think about how your ranges are being set up. If you want to print "******" before you print "*****" you need to let python know to print 6 before 5. Do that by counting down your range.
I've done that here:
for i in range(base, 0, -1):
It starts the range at base (which you set to 6) and counts down by -1, all the way to zero.