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])
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.
x={}
continueQ=input("would you like to continue?"))
if (continueQ=="yes"):
#if there is less than 4
if x<4:
variable=float(input("Input a float to append to the array:")
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
There are a few errors in this code, could someone help me how to create an if statement to check if there are minimum than 4 values inside an array .
Also how to append to an array from an input.
Create a list with x = [], Use len(x) to get the length of list, use while loop with condition if x<4
x=[]
continueQ=input("would you like to continue?")
if (continueQ=="yes"):
#if there is less than 4
while len(x)<4:
variable=float(input("Input a float to append to the array:"))
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
The first thing you'll want to do is change that x={} to an x=[]. What you've done is create a dictionary rather than an array, and consequently will run into an assortment of issues as you're dealing with the wrong data structure.
Once you've done that, we can move on to how to check if there are less than 4 values inside an array. In Python, arrays carry a length attribute, which can be accessed by writing len(arrayName), or in your case, len(x). For example, if your array x contained the following values: [1,2,3], then len(x) would return 3, seems simple enough.
Now to check that the length is less than 4, you need to replace your if x<4: with if len(x)<4:.
You already have the correct code to append to your array, it likely wasn't working before because you created a dictionary instead of an array.
There are several errors in your code. Here's a working version:
x = []
continueQ = input('Would you like to continue?')
if continueQ.lower() == 'yes':
while len(x) < 4:
variable=float(input('Input a float to append to the array:'))
x.append(variable)
print(x)
print("Goodbye!")
Explanation
[] represents an empty list, while {} is use for an empty set.
Make sure your bracketing is consistent; all open brackets must be closed.
Use len(x) to find the number of entries in a list x.
Use a while loop to repeat logic until a criterion is satisfied.
a,b = int(i) for i in input().split()
Can someone explain why the above code doesn't work?
I understand I can use this to make a list like:
a = [int(i) for i in input().split()]
But why doesn't it work for 2 values? If a runtime exception rises(passing more than 2 values), termination is totally legit. But the shows invalid syntax.
I just checked. These are called Generator Functions. And the code can be modified as:
a,b = (int(x) for x in input().split())
Also, a,b = [int(x) for x in input().split()] also does the same job, but instead it return a list. The list is then iterated and is assigned to the variables at python's end. (Correct me if I am wrong)
Thanks to everyone who answered! :D
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)