I have a problem with a simple program; my aim is to add tuples to a list, put in input by the user. The while-loop should break when the user puts 0.
this is my code:
sList=[]
x=tuple(input("insert tuple (0 to stop): "))
while x!=int(0):
sList.append(x)
x=tuple(input("insert tuple (0 to stop): "))
print (sList)
The problem is that the while loop never stops, even if I put 0, where is the mistake?
Please read the following lines in order to understand how to fix the error in your code:
sList=[]
x=tuple(input("insert tuple (0 to stop): "))
print("x contains: " + str(x))
print("x type is: " + str(type(x)))
while int(x[0])!=int(0):
print("x contains: " + str(x))
print("x type is: " + str(type(x)))
sList.append(x)
x=tuple(input("insert tuple (0 to stop): "))
print (sList)
You are comparing the string (0,) to the int value 0.
This is why your version doesn't work as expected.
I've also added two more prints to better understand what the code is doing.
Once we understood the nature of the error and how to fix it I would like to ask you why using a tuple in this case.
Could using an int directly be a good idea?
We could also reduce the number of lines and remove duplicated code, here's another iteration:
sList=[]
x = None
while x != 0:
print("x contains: " + str(x))
print("x type is: " + str(type(x)))
x = input("Insert 0 to stop: ")
if (x != None) and x.isdigit():
x = int(x)
if x != 0:
sList.append(x)
print (sList)
There are two problems in your code (as far as I have understand your issues):
a. You need to first convert the input from user (which will be string) to tuple. You can use:
t = tuple(int(x.strip()) for x in input("insert tuple (0 to stop): ").split(','))
b. You need to modify your while loop test expression to:
while len(t):
Assumptions that I have made:
You want the user to type comma separated values (Because having a single value tuple in your list doesn't make sense to me. Correct me if I have missed something)
You want to end your while loop if user hasn't entered any value (,i.e., has pressed the Enter key).
If my assumptions are correct, try this:
def check_int(s):
if len(s) == 0:
return False
if s[0] in ('-', '+'):
return len(s) > 0 and s[1:].isdigit()
return s.isdigit()
sList=[]
x=tuple(int(x.strip()) for x in input("insert tuple (0 to stop): ").split(',') if check_int(x.strip()))
while len(x):
sList.append(x)
x=tuple(int(x.strip()) for x in input("insert tuple (0 to stop): ").split(',') if check_int(x.strip()))
print(sList)
Related
my code and the error
I am trying to make a program that will create a randomized password. Along with that, it is supposed to alternate between
print(chr(letter), end="")
print(chr(number), end="")
as it makes it so that the password looks something like "A2h8l" where it alternates between numbers and letters.
import random
number = random.randint(48,57)
letter = random.randint(65,122)
print(input("How many characters do you want in your password?"))
x = input
y = int(letter + number)
while int(x > y):
print(chr(letter), end="")
print(chr(number), end="")
For some reason, however,
while int(x > y):
shows up with an error, and I'm not sure what to do about it. No clue what I'm doing or doing wrong, and any help is appreciated.
int(1 > 2) is syntactically incorrect.
You cannot pass a comparison like this to the int() function. The correct way to do this would be
if int(1) > int(2):
Although, you still do not need the int() if you are passing an integer to begin with.
Even when resolving this issue your code continues to have problems.
Your loop will run indefinitely or not at all, dependant on the values of x and y, and will also print the same two chars constantly.
A better way to handle this is to:
Define password length
Loop over range(length)
Generate random integers and append them to a string
import random
length = int(input('Password Length'))
password = ''
for i in range(length):
password = password + chr(random.randint(65,122)) + chr(random.randint(48,57))
password
#'Q5I4D8p8i9l1p7j0I6l9'
The reason you're running into that specific error is that you are setting x to the input function itself. Something like this would be closer to what you want:
x = int(input("How many characters do you want in your password?"))
Something like this: (your code get error just because x=input, so x is a function which can not be compare with int type)
import random
x = int(input("How many characters do you want in your password? ").strip())
count = 0
while x > count:
number = random.randint(ord("0"), ord("9"))
upper = random.randint(ord("A"), ord("Z"))
lower = random.randint(ord("a"), ord("z"))
y = random.choice([number, upper, lower])
print(chr(y), end="")
count += 1
print()
Or more pythonic
import random
import string
CHARS = string.digits + string.ascii_letters
x = int(input("How many characters do you want in your password? ").strip())
print(''.join(random.choice(CHARS) for _ in range(x)))
Maybe you could do something like this
import random
number = random.randint(48,57)
letter = random.randint(65,122)
x = input("How many characters do you want in your password?")
x = int(x)
y = letter + number
while x > y:
print(chr(letter), end="")
print(chr(number), end="")
I am trying to shorten the process of making lists through the use of a defined function where the variable is the list name. When run, the code skips the user input.
When I run my code, the section of user input seems to be completely skipped over and as such it just prints an empty list. I've tried messing around with the variable names and defining things at different points in the code. Am I missing a general rule of Python or is there an obvious error in my code I'm missing?
def list_creation(list_name):
list_name = []
num = 0
while num != "end":
return(list_name)
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
list_creation(list_Alpha)
print("This is the first list: " + str(list_Alpha))
list_creation(list_Beta)
print("This is the second list: " + str(list_Beta))
I want the two seperate lists to print out the numbers that the user has input. Currently it just prints out two empty lists.
You need to move the return statement to the end of the function, because return always stops function execution.
Also, what you're trying to do (to my knowledge) is not possible or practical. You can't assign a variable by making it an argument in a function, you instead should remove the parameter list_name altogether since you immediately reassign it anyway, and call it like list_alpha = list_creation()
As a side note, the user probably wants to see the whole "To end, type end as number input" bit before they start giving input.
Dynamically defining your variable names is ill advised. With that being said, the following code should do the trick. The problem consisted of a misplaced return statement and confusion of variable name with the variable itself.
def list_creation(list_name):
g[list_name] = []
num = 0
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
g[list_name].append(num)
g = globals()
list_creation('list_Alpha')
print("This is the first list: " + str(list_Alpha))
list_creation('list_Beta')
print("This is the second list: " + str(list_Beta))
There are a couple of fundamental flaws in your code.
You redefine list_name which is what Alpha and Beta lists are using as the return.(list_name = [] disassociates it with Alpha and Beta so your function becomes useless.)
You return from the function right after starting your while loop(so you will never reach the input)
In your function:
list_Alpha = []
list_Beta = []
def list_creation(list_name):
# list_name = [] <-- is no longer Alpha or Beta, get rid of this!
num = 0
...
The return should go at the end of the while loop in order to reach your input:
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
return(list_name)
I want to write 2 functions. One function that takes input from a user and adds it to a list. The 2nd function takes the list returned from the 1st function and prints out each element separated by a space. I think I am close, but something isn't right. Typing -999 doesn't stop the loop, and I can't tell if I am calling the functions correctly...
Any ideas?
def listFunc():
num = 0
list1 = []
while num != -999:
x = int(input('Enter a number, -999 to quit: '))
list1.append(x)
return list1
def formatFunc(y):
final = str(y)
' '.join(final)
print(final)
formatFunc(listFunc())
It should be the same variable used in while loop.
num = int(input('Enter a number, -999 to quit: '))
if num != -999:
list1.append(num)
and
# final = str(y) This is not required, why cast list as str
final = ' '.join(final)
x = int(input('Enter a number, -999 to quit: '))
list1.append(x)
num=x
will work!
You are calling the functions correctly if you intend on printing the inputs of listfunc. However the inputs will not be saved to a variable in global scope and will thus be locked out from any future use.
Additionally, listfunc currently does no input validation. It is possible to input any strings in the input. The while loop doesn't end because the condition in the while is never met.
Rewriting it according to your conditions yields:
def listfunc():
someList = []
while True:
x = input("Enter a number, exit to quit")
if 'exit' in x.lower():
break
elif x.isdigit():
someList.append(x)
else:
print("Input not recognized try again")
return someList
def formatFunc(v):
print(''.join(str(i) + ' ' for i in v)
Do you see why this works?
print ("please enter values as check([x,y,z])to find min and max")
def check(iterable):
try:
(iterable) = int(iterable)
except:
print("please Enter number")
else:
print("************************")
it = iter(iterable)
first = next(it) # Raises an exception if the input is empty
minimum = maximum = cumsum = first
n = 1
for x in it:
n += 1
cumsum += x
if x < minimum:
minimum = x
if x > maximum:
maximum = x
return "min:" + str(minimum), "max:" + str(maximum)
From what I can break down from what you wrote, the first thing you should be doing is prompting the user to input a list as such:
1,2,3,4
So your code should be written like this to accept this input:
user_input = input("please enter values as #,#,# to find min and max ")
From there, what you want to do is then call your check method with user_input:
check(user_input)
Inside your try/except for your check method, you must now determine how to convert your string which now looks like this:
# pure string
"1,2,3,4"
In to this:
# list of ints
[1, 2, 3, 4]
So, if you simply do this:
# Convert to a list of strings by splitting on comma
iterable = iterable.split(',')
# Iterate over array and convert each element to an int
for i, v in enumerate(iterable):
iterable[i] = int(iterable[i])
To simplify the above, you use what is called a list comprehension, and do this all in one line as such:
iterable = [int(x) for x in iterable.split(",")]
You will end up getting your list of ints. Now, if you end up providing an input like this:
1,a,5
The logic to convert to a list of ints will fail because 'a' is not a int and it will enter your except.
After that, you should be able to continue with the rest of your logic to determine how to get the max and the min.
So, your code should look something like this:
def check_user(user_input):
# code stuff
user_input = input("blah blah")
check_user(user_input)
Below I have a script that I have done while trying to complete for a assignment I have.
What the script is suppose to do is ask the user for 2 inputs and then return the greater of the inputs. (This I havent figured out completely yet)
The point of this assignment is too see what happens if I instead of entering 2 numbers, enter two words "Hej" and "Hå".
What I need some advice on is how to enable this script to accept 2 user inputs and return the greater of them two.
def maximum(x, y):
i = 0
maxnra = 0
maxnrb = 0
while i < len(x) :
if x[i] > maxnra:
maxnra = x[i]
i = i + 1
else:
i = i + 1
print "I första ordet är maximum: ", maxnra
i = 0
while i < len(y) :
if y[i] > maxnrb:
maxnrb = y[i]
i = i + 1
else:
i = i + 1
print "I andra ordet är maximum: ", maxnrb
maximum("hej", "hå")
EDIT:
I tried working this out another way, is this a way to solving this?
print "First"
x = input()
print "Second"
y = input()
def printMax(x, y):
if x > y:
print(x, 'is maximum')
elif a == b:
print(x, 'is equal to', y)
else:
print(y, 'is maximum')
right now im missing something cause it's not returning anything when I enter the 2 values.
Read documention on the command raw_input to see how you can get input from the user.
If you just want a simple way to get user input from the terminal window, have a look at the raw_input function.
Your first code would simply takes two lists and prints the maximum value of each individual list. So, this is not that you want.
In the second code, although the approach is right, you made some minor mistakes.
print "First"
x = input() # use raw_input() for python 2.7
print "Second"
y = input()
def printMax(x, y):
if x > y:
print(x, 'is maximum')
elif x == y:
# not a==b
print(x, 'is equal to', y)
else:
print(y, 'is maximum')
Actually, when you enter input in this code, though you enter numbers they are still considered as strings. So, there would be no big difference if you enter a string.
These strings are compared lexicographically using (ASCII value order). As your input isn't from ASCII, it will show error.
So, you need to replace input() or raw_input() with the following
import sys # do this at the top of program.
x = raw_input().decode(sys.stdin.encoding)
# similarly do it for y
Please read the following stackoverflow question to know more on this link