Is it possible to have a user input equal to a variable for tasks that involve chemical elements.
For example, Carbon has the molecular mass 12, but i do not want the use to input 12, They should input 'C'. but as the input turns this into a string, it is not possible to lik this to the variable C = 12.
Is there any way to input a variable istead of a string?
If not, could i set a string as a variable.
example:
C = 12
element = input('element symbol:')
multiplier = input('how many?')
print(element*multiplier)
This just returns an error stating that you can't multiply by a string.
You could change your code like this:
>>> masses = {'C': 12}
>>> element = input('element symbol:')
element symbol:C
>>> masses[element]
12
>>> multiplier = input('how many?')
how many?5
>>> multiplier
'5' # string
>>> masses[element] * int(multiplier)
60
input in Python 3.x is equivalent to raw_input in Python 2.x, i.e. it returns a string.
To evaluate that expression like Python 2.x's input, use eval, as shown in the doc for changes from 2.x to 3.0.
element = eval(input("element symbol: "))
....
However, eval allows execution of any Python code, so this could be very dangerous (and slow). Most of the time you don't need the power of eval, including this. Since you are just getting a global symbol, you could use the globals() dictionary, and to convert a string into an integer, use the int function.
element = globals()[input("element symbol: ")]
multiplier = int(input("how many? "))
but when a dictionary is needed anyway, why not restructure the program and store everything in a dictionary?
ELEMENTS = {'C': 12.0107, 'H': 1.00794, 'He': 4.002602, ...}
try:
element_symbol = input("element symbol: ")
element_mass = ELEMENTS[element_symbol]
multiplier_string = input("how many? ")
multiplier = int(multiplier_string)
print(element_mass * multiplier)
# optional error handling
except KeyError:
print("Unrecognized element: ", element_symbol)
except ValueError:
print("Not a number: ", multiplier_string)
Since input always return string type. Multiplication to the string is not allowed.
So after taking the input, you need to type cast if using int type in python .
Try this:
multiply_string = input("how many? ")
multiplier = int(multiplier_string) #type cast here as int
element = eval(input("element symbol: "))
would be the simplest, but not necessarily the safest. Plus, your symbol needs to be in the local scope
you might prefer to have a dictionary object
Related
I want to identify the variable g and h at the same line
g, h = eval(input("enter an integer: "))
print(g,h)
Hello leena and welcome to Stack Overflow,As many noted, your could go follow multiple paths to achieve what you are looking for, as the Zen of Python says:
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
The first suggestion is to split the the inputs as #arbyys says:
g = input("Enter an integer: ")
h = input("Enter an integer: ")
Altought it won't be the DRYest solution of the bunch.If you are going to prefer a more functional approach you can 'force' the user to insert two inputs like this:
def get_integers():
return [input("Enter an integer: ") for _ in range(2)]
g,h = get_integers()
As for your eval, that's a very unsafe practice and you must avoid it in your programming, if you use it to type-cast the input value, you know they HAVE TO BE integers, so you can cast an int, in the following way:
def get_integers():
return [int(input("Enter an integer: ")) for _ in range(2)]
g,h = get_integers()
Obviously this would throw an error if you insert a non-integer as your input.
Edit:
If you want to give the same value to different variables you can go this route:
g = h = int(input("Enter an integer: "))
If you want the user to enter more values, I suggest using list.
values = []
for x in range(2):
values.append(input("Enter value:"))
Then you can iterate over the list values.
If you want to avoid list, you can just give each variable its own input.
g = input("Enter first value:")
h = input("Enter second value:")
print(g,h)
Also, avoid using eval from user input, as it can cause some serious trouble in your code.
I will give you my python code (it's pretty basic and small) and if you can,tell me where i am wrong.I am noob at coding so your help will be valuable.thanks a lot and don't hate :)
lista=[]
for i in range(100):
a=input("give me a number")
if a%2==0:
a=0
else:
a=1
lista=lista+a
print lista
P.S: I code with python 2 because my school books are written with that in mind.
You need to use append method to add an item to the end of the list.
lista.append(a)
And you need to convert the str returned by input() to int.
The input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
a = int(input("give me a number"))
Try this:
lista=[]
for i in range(2): # Changed from 100 to 2 for my own testing
a = int(input("Give me a number: "))
a = 1 if a%2 else 0
lista.append(a)
print(lista)
Outputs:
[0,1]
EDITED:
So i cant use Lista=lista +a?I thought i could..my book says i can..thanks for your solution,it works!
You can use += operator (similar to extend()) but it requires a list operand. Not an int. So, you need to convert your int to a list. Try this:
lista += [a]
list.append(a) is faster, because it doesn't create a temporary list object. So, better to use append.
What's wrong with this program in Python?
I need to take an integer input(N) - accordingly, I need to create an array of (N)integers, taking integers also as input. Finally, I need to print the sum of all the integers in the array.
The input is in this format:
5
4 6 8 18 96
This is the code I wrote :
N = int(input().split())
i=0
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = int(input().split())
V.append(x)
i+=1
s+=x
print (s)
Its showing the following error.
Traceback (most recent call last):
File "main.py", line 1, in <module>
N = int(input().split())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
split() returns a list which you are trying to convert to an integer.
You probably wanted to convert everything in the list to an integer:
N = [int(i) for i in input().split()]
You can also use map:
N = list(map(int, input().split()))
You could use sys module to take the input when calling the program and a lambda function to convert the string items in list to integers. You could also make use of the built-in sum function. Something like that:
#!/usr/bin/env python
import sys
s = sum(i for i in map(lambda x: int(x), sys.argv[1].split(',')))
print s
Example:
python test.py 1,2,3,4
The output should be 10.
Modifying your code:
Now, if you want to modify your code to do what it intends to do, you could modify your code like that:
#!/usr/bin/env python
N = input()
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = input()
V.append(x)
s+=x
print (s)
Note 1: In python when you use range you don't have to manually increase the counter in the loop, it happens by default.
Note 2: the 'input()' function will maintain the type of the variable you will enter, so if you enter an integer you don't have to convert it to integer. (Have in mind that input() is not recommended to use as it can be dangerous in more complicated projects).
Note 3: You don't need to use '.split()' for your input.
You code fails because str.split() returns a list.
From the Python documentation
Return a list of the words in the string, using sep as the delimiter
string
If your input is a series of numbers as strings:
1 2 3 4
You'll want to iterate over the list returned by input.split() to do something with each integer.
in = input()
for num in in.split():
x.append(int(num))
The result of this will be:
x = [1,2,3,4]
I want to know how can I add these numbers in Python by using a loop? Thanks
num=input("Enter your number: ")
ansAdd= int(str(num)[7])+int(str(num)[5])+int(str(num)[3])+int(str(num)[1])
print....
you want to do it using a loop, here you go:
ansAdd = 0
for x in [7,5,3,1]:
ansAdd += int(str(num)[x])
However, using list comprehension is more pythonic
>>> s = '01234567'
>>> sum(map(int, s[1::2]))
16
Here is how it works:
s[1::2] takes a slice of the string starting at index 1 to the end of the string stepping by 2. For more information on slices see the Strings section of the Python Tutorial.
map takes a function and an iterable (strings are iterable) and applies the function to each item, returning a list of the results. Here we use map to convert each string-digit to an int.
sum takes an iterable and sums it.
If you want to do this without the sum and map builtins, without slices, and with an explicit for-loop:
>>> s = '01234567'
>>> total = 0
>>> for i in range(1, len(s), 2):
... total += int(s[i])
...
>>> total
16
>>> num=input()
12345678
>>> sum(map(int,num[:8][1::2]))
20
here num[:8][1::2] returns only the numbers required for sum(), num[:8] makes sure only the elemnets up to index 7 are used in calculation and [1::2] returns 1,3,5,7
>>> num[:8][1::2]
>>> '2468'
It seems you want to sum odd-numbered digits from user input. To do it with a loop:
num_str = raw_input("Enter your number: ")
ansAdd = 0
for digit in num_str[1::2]:
ansAdd += int(digit)
(The syntax [1::2] is python's string slicing -- three numbers separated by : that indicates start index, stop index and step. An omitted value tells python to grab as much as it can.)
There's a better way to do this without using a traditional loop:
num_str = raw_input("Enter your number: ")
ansAdd = sum(int(digit) for digit in num_str[1::2])
In python 2, input executes the entered text as python code and returns the result, which is why you had to turn the integer back into a string using str.
It is considered a security risk to use input in python 2, since the user of your script can enter any valid python code, and it will be executed, no questions asked. In python 3 raw_input has been renamed to input, and the old input was removed (use eval(input()) instead).
Is there a way to scan an unknown number of elements in Python (I mean scan numbers until the user writes at the standard input eof(end of file))?
raw_input (input in Python 3) throws EOFError once EOF is reached.
while 1:
try:
num = int(raw_input("enter a number: "))
except EOFError:
break
Do you need to process the first number before the second is entered? If not, then int(s) for s in sys.stdin.read().split() would probably do, either as a list comprehension (in []) or generator expression (in (), for example as a function argument).
This would break at any
Here is one primitive way to do it.
In [1]: while True:
...: try:
...: num = int(raw_input())
...: except EOFError:
...: break
...:
Example output for the input that I had given:
10
20
40
50
This would break not just for EOF but for any input which does not convert to number.
I found another way... sometimes, I use a different programming language called R.
There, you can enter:
my_variable = scan()
...and enter numbers as you wish. Even with copy & paste.
Then, you can dump the input:
dump(my_variable, "my_variable.Rdata")
my_variable.Rdata is a text file which contains an R list... which can be easily converted into a Python list:
# a list in R syntax:
my_variable <- c(1, 2, 3)
# a list in Python syntax:
my_variable = [1, 2, 3]