Get True when getting any input (Python) - python

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: "))

Related

Trying to validate a text input, so it allows characters in the alphabet only as the input but I'm having problems. (Python)

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

Confused about if statements and functions

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...

Why i am unable to use (or) operator on the code given below in python 3.7 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
try:
x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.
While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn't work in this case because trying to convert into int a string which represents a float value doesn't return a falsy value, it raises an Exception, which is why you go into your except clause
A logically sound way to write your code would be
x = input("Enter Your Number first = ")
try:
num = int(x)
except:
num = float(x)
Not the best way to do it, but it works
Another example:
x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value
Generally, we use or case to check some conditions. For example if x<3 or x>5: This if block works of both cases. However, in your situation you are trying to get some input from user and using x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = ")). So, when I enter a value it gets number as string and when you write int(input()) it convert it to integer and assign to x. So OR is not logically suitable for here. What will computer work it this situation? What you want to achieve? If you want take argument as float just write float(input()) because when you enter integer it can be taken as float also.
try:
x = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
y = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
operators = input("Choose operations (*, -, +, /)")
if operators == "*":
print(float(x*y)) or print(int(x*y))
elif operators == "-":
print(float(x-y)) or print(int(x-y))
elif operators == "+":
print(float(x+y)) or print(int(x+y))
elif operators == "/":
print(float(x/y)) or print(int(x/y))
well, i just figured it out,

Why isn't my code not looping with the Y/N condition, correctly?

Why isn't my code not looping with the Y/N condition, correctly?
Write a Python program to do the following:
(a) Ask the user to enter as many integers from 1 to 10 as he/she wants. Store the integers entered by the user in a list. Every time after the user has entered an integer, use a yes/no type question to ask whether he/she wants to enter another one.
(b) Display the list.
(c) Calculate and display the average of the integers in the list.
(d) If the average is higher than 7, subtract 1 from every number in the list. Display the modified list.
person = []
integer_pushed = float(input("Enter as many integers from 1 to 10"))
person.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
person.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
person.append(integer_pushed)
again = input("Enter another integer? [y/n]")
If you're using Python 2.7 input() attempts to evaluates the input as a Python expression. You want to use raw_input() instead.
In Python3, input() has the desired behavior.

creating a code that use .isdigit

I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.
You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")
Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")

Categories

Resources