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.
Related
I have just learned the index and slicing in python. After I learned, I got a good idea to make. The idea briefly is that instead of writing the sequence in the code, I want the user to choose a start and an end and print the result. I have written the code and it showed no problems, but when I ran it, it didn't work :(
So I need help to make it run as I imagined.
`
mystring = "Omar Marouf Zaki"
print("Choose First Number")
x = input()
print("Choose Second Number")
y = input()
print(mystring[x:y])
Convert the Strings to Int.
input() return string so you need to do print(mystring[int(x):int(y)]) to make x and y ints
If you want cleaner code, you could convert your input to an int before assigning it to x and y, like this:
x = int(input())
# ...
y = int(input())
# Now you can use [x:y] without problems becuase both x and y are integers
print(mystring[x:y])
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.
I'm required to write a function that computes and returns the sum of the digits in an integer.
Here's my code:
def main():
number1=input("Enter a number: ")
number=list(number1)
i=0
while len(number)!=i:
numbers=[]
x=int(number[i])
numbers.append(x)
number.remove(number[i])
print(numbers)
x=float(sum(numbers))
print(x)
main()
The output looks like:
Enter a number: 123
[3]
3.0
I'm not sure why 1 and 2 aren't in the list, and aren't used to compute the sum... any suggestions?
You reinitialize numbers inside the loop. Don't do that, move that outside of the loop instead:
numbers=[]
while len(number)!=i:
# ...
otherwise you end up resetting the list for each and every digit.
It's good for you to learn the basics before you try advanced stuff, but just for fun, here is the way an experienced Python coder would solve this problem:
def main():
number1=input("Enter a number: ") # for Python 2.x, need to use raw_input()
return float(sum(int(ch) for ch in number1))
x = main()
print(x)
We can use the builtin function sum() to sum the digit numbers, and we get the digit numbers with a "generator expression" that loops over the string directly while calling int().
This is just a taste of the fun stuff you will be learning soon in Python. :-)
You can also do it in a more functional way, if you are interested in this kind of programming. It would then look like this:
def main():
number1=input("Enter a number: ") # for Python 2.x, need to use raw_input()
return float(sum(map(int, number1))
x = main()
print(x)
I am teaching myself Python and am running into a strange problem. What I am trying to do is pass a list to a function, and have the function return a list where elements are the sum of the numbers around it, but what I thought would work produced some strange results, so I made a debug version of the code that still exhibts the behavior, which is as follows:
When I make an integer array, and pass it to an function which then uses a for loop print the individual values of the list, the numbers following the first one in each int are truncated.
For example, the following input and output:
Please enter a number: 101
Please enter a number: 202
Please enter a number: 303
Please enter a number: .
1
2
3
This happens no matter the input, if its 10, 101, or 13453 - the same behavior happens.
I know I am probably missing something simple, but for the sake of me, no amount of googling yields me a solution to this issue. Attached below is the code I am using to execute this. It is interesting to note: when printing the entire list outside of the for loop at any point, it returns the full and proper list (ie ['101', '202', '303'])
Thanks!
temp = list()
def sum(list):
print list
for i in range(1, len(list)+1):
print i
return temp
L = list()
while True:
input = raw_input("Please enter a number: ");
if input.strip() == ".":
break
L.append(input);
print L
L2 = sum(L)
print L2
The loop
for i in range(1, len(my_list)+1):
print i
iterates over the numbers from 1 to len(my_list), not over the items of the list. To do the latter, use
for x in my_list:
print x
(I've renamed list to my_list to save you another headache.)
You are printing the counter, not the list item. This is what you want:
for i in list:
print i
list is itself iterable and you don't need a counter to loop it.
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