I'm very familiar with the random module but I always stumbled when it came to functions. How do I make a function only occur if it meets a certain condition? It gives me no output when im trying to validate my answer...
choice = input ("Which type of password would you like to generate? \n 1. Alphabetical \n")
if choice == 1:
characters = list(string.ascii_letters)
def generate_random_abc_password():
length = int(input("Enter password length: "))
random.shuffle(characters)
password = []
for i in range(length):
password.append(random.choice(characters))
random.shuffle(password)
print("".join(password))
generate_random_abc_password()
Seems like the most common mistake among beginners. When you use an input() function, it will return you some number/text/float or decimal number but in string type. For example
x = input("Enter your number")
# If i would input 2, my x variable would contain "2"
# 3 => "3"
# 550 => "550" and so on...
To avoid such a problem and to store your value in proper type, you need to wrap your input with int() function, as shown below
x = int(input(("Enter your number"))
# From now, whenever i prompt any number from my keyboard, it will
# be an integer number, which i can substract, add, multiply and divide.
As simple as it is. Happy learning!
You should convert the input to integer as by default the data type for input is string.
Alternatively rather than changing input data type you can compare it with the str(1) or change if choice == 1: to if choice == '1':
You can try using :
import string
import random
choice = int(input ("Which type of password would you like to generate? \n 1. Alphabetical \n"))
if choice == 1:
characters = list(string.ascii_letters)
def generate_random_abc_password():
length = int(input("Enter password length: "))
random.shuffle(characters)
password = []
for i in range(length):
password.append(random.choice(characters))
random.shuffle(password)
print("".join(password))
generate_random_abc_password()
The above code will result in :
Which type of password would you like to generate?
1. Alphabetical
1
Enter password length: 10
MEQyTcspdy
The problem here is that you've defined the characters variable in your if block. That is your function is not aware of of the variable that is why you should pass the characters variable as a input to the function the code should look like
choice = input ("Which type of password would you like to generate? \n 1. Alphabetical \n")
if choice == 1:
characters = list(string.ascii_letters)
def generate_random_abc_password(characters):
length = int(input("Enter password length: "))
random.shuffle(characters)
password = []
for i in range(length):
password.append(random.choice(characters))
random.shuffle(password)
print("".join(password))
generate_random_abc_password(characters)
A function works like an isolated piece of code it takes it's own inputs and returns it's own outputs or does it's stuff.
As well as the input isn't casted to an int as the above mentioned answer says...
Related
So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break
I'm new to programming. I searched for an answer but didn't seem to find one. Maybe I just can't Google properly.
I want to get something True, when the user inputs anything. Example:
another_number = input("Want to enter another number? ")
What I want:
if another_number = True
float(input("Enter another number: "))
Sure I can say if another_number = ("Yes", "yes", "Y", "y") but in my program I want to get True when entering really anything.
Strings that contain characters are 'truthy', so you can do something like:
if another_number:
x = float(input("Enter another number: "))
The empty string is 'falsy', so this produces nothing:
s = ""
if s:
print("s has characters")
This trick also works on other Python objects, like lists (empty lists are falsy), and numbers (0 is falsy). To read more about it, check out answers to this question.
In python, any non-empty string is evaluated to True.
So, you can simply do:
another_number = input("Want to enter another number? ")
if another_number: #==== Which means 'if True'
float(input("Enter another number: "))
And that will allow for any input.
Alternatively, you can also fo:
another_number = input("Want to enter another number? ")
if another_number!='': #=== if string is not blank as without entering anything, '' is returned. You can also use ```if len(another_number)!=0: where the length of the string is not 0
float(input("Enter another number: "))
I want to get input numbers from the user and sort it then print it. But it gives attribute error:
AttributeError: 'str' object has no attribute 'sort'
-- with the code--
lucky_numbers = input("Write your favourite numbers: ")
ans = (lucky_numbers)
ans.sort()
print(ans)
Using split():
lucky_numbers = input("Write your favourite numbers with a space: ")
numberList = lucky_numbers.split()
numberList.sort()
print(numberList)
OUTPUT:
Write your favourite numbers with a space: 50 40 -10
['-10', '40', '50']
EDIT:
If you want to have the values in int:
numberList = [int(x) for x in numberList]
This can be possible answer. You also need to convert str values to int
lucky_numbers = input("Write your favourite numbers: ")
ans = lucky_numbers.split()
ans_int = [int(i) for i in ans]
ans_int.sort()
print(ans_int)
You can't sort it because the input function returns the string that has been typed by the user so it will be a string not a list and you can't sort it. Your approach must change and you must store user input and numbers in a list.
Something like this may work:
lucky_numbers = []
while True:
user_input = input('enter your favourite number or to exit enter Q:')
if user_input == 'Q':
break
else:
lucky_numbers.append(int(user_input))
lucky_numbers.sort()
print(lucky_numbers)
This only works for integers and there is more stuff you can do for type checking and making sure that user input is a number or no or the list is empty or not. It was just a simple example to show the overall process.
I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)
Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list