How to use raw_input with no input - python

I want to use raw_input() function in Python.
I want to receive a number from user about the size of the storage
i wrote this down :
number=raw_input()
if the user doesn't provide an input then number = 10 so
if number is None:
number = 10
when i print number, i get nothing i even tried:
if number==-1:
number=10
print"the storage size was set to:",number
The output was:
>
the storage size was set to -1
and not 10
So how should I solve this ?

If you don't care to distinguish between "no input" and "invalid input" (like a non-integer literal), set the default, then attempt to replace it with the user input.
number = 10
try:
number = int(raw_input())
except (EOFError, ValueError):
pass
ValueError will be raised on invalid inputs, including the empty string. EOFError is raised if the user does something like type Control-d in a terminal that interprets that as closing standard input.

First of all you have to convert the input (default for raw_input is a string) into an int using int() function. But be sure that you first check if user typed something. Otherwise you can't convert an empty string. For example:
num_input = raw_input()
if num_input:
number = int(num_input)
Then already the second part of your question should work:
if number == -1:
number = 10
print "the storage size was set to:", number
The second point is that an empty string is not equal to None. None is the only value of NoneType and "" is a string.
So you can compare the input with an empty string, but you can do better (an empty string is evaluated as False):
if not num_input:
number = 10
and to be even more efficient you can simply add an else statement to my first piece of code:
num_input = raw_input()
if num_input:
number = int(num_input)
else:
number = 10

compare number with empty string; not with None .
if number == '':
number = 10

In Python when the variable is empty then it's have inside empty '',
so if you want to check if your variable is unset you need to compare it to '' and not to None.
if number=='':
number=10

You should just compare number and empty.:
if number=="":
number==10

Related

Same input gives different output for a program

Novice programmer here. I am trying to write a program wherein it will take UIDs from user and validate them based on certain rules. The rules are:
It must contain at least 2 uppercase English alphabet characters.
It must contain at least 3 digits ( 0-9 ).
3.It should only contain alphanumeric characters (A -Z ,a -z & 0 -9 ).
No character should repeat.
There must be exactly characters in a valid UID.
I am putting in the code. Also apologies for this big code (I am a newbie)
# UID Validation
n=int(input()) #for iterations
uid=[]
# char=[]
valid=1
upper=0
numeric=0
# take input first of everycase
for x in range (0,n):
num=input()
uid.append(num)
# print (uid)
for i in uid:
# print (i)
# to count each word and number
count={}
for char in i:
count[char]=count.get(char,0)+1
for j in i:
if j.isupper():
upper=upper+1
elif j.isnumeric():
numeric=numeric+1
# print('numeric =', numeric)
# print('upper =', upper)
# Check conditions
while valid==1:
if len(i)!= 10:
valid= 0
# print('invalid for word count')
elif i.isalnum()== False: #alphanumeric
valid=0
# print('invalid for alnum')
elif upper<2: #minimum alphabet and numbers
valid=0
# print('invalid for min alphabet')
elif numeric<3:
valid=0
# print('invalid for min numeric')
else:
for k,v in count.items(): #no repitation
if v>1:
valid=0
# to check if given UID is valid or not
if valid==1:
print ('Valid')
elif valid==0:
print('Invalid')
valid=1
break
I have written the code but it seems that I am facing problem on one input only that is to check UID tag: 2TB1YVIGNM
It is an invalid tag. My program shows the same when is I run it alone or first in a batch of many. But, Lets say I run the program and input 2 tags, with "2TB1YVIGNM" being second one, it will show is as "Valid". Mind you, this is only happening in this particular tag
There are several other tags which run fine. Some of them are mentioned here:
77yS77UXtS
d72MJ4Rerf
OA778K96P2
2TB1YVIGNM "EXCEPT THIS TAG"
9JC86fM1L7
3w2F84OSw5
GOeGU49JDw
8428COZZ9C
WOPOX413H2
1h5dS6K3X8
Fq6FN44C6P
The output should be:
Invalid
Valid
Invalid
Invalid
Valid
Invalid
Invalid
Invalid
Invalid
Valid
Invalid
My output is this:
Invalid
Valid
Invalid
Valid
Valid
Invalid
Invalid
Invalid
Invalid
Valid
Invalid
To solve your problem you need to set upper and numeric back to 0 for each uid:
for i in uid:
upper = 0
numeric = 0
count={}
P.S: As for you newbie I would suggest you to read PEP 8 it will make your code more readable and prettier
P.S.S: There is no need to count manually how many times each character meet in string, such operation already implemented in Python look at the Counter for more details
And I agree with comment that for such type of tasks it is better to use regex
You could extract pieces of logic into functions and call them:
#It must contain at least 2 uppercase English alphabet characters.
def has_at_least_two_uppercase(potential_uid):
return sum([char.upper() == char for char in potential_uid])>= 2
#No character should repeat.
def has_unique_chars(potential_uid):
return len(set(potential_uid)) == len(potential_uid)
#There must be exactly characters in a valid UID.
def is_proper_length(potential_uid:str, proper_length:int = 10)-> bool:
return len(potential_uid) == proper_length
#It must contain at least 3 digits ( 0-9 ).
def has_three_digits(potential_uid):
return sum([char.isnumeric() for char in potential_uid])>=3
#It should only contain alphanumeric characters (A -Z ,a -z & 0 -9 )
# Defining a function for this may be an overkill to be honest
def is_alphanumeric(potential_uid):
return potential_uid.isalnum()
def is_valid_uid(potential_uid):
if has_at_least_two_uppercase(potential_uid) is False:
return False
if has_unique_chars(potential_uid) is False:
return False
if is_proper_length(potential_uid) is False:
return False
if has_three_digits(potential_uid) is False:
return False
if is_alphanumeric(potential_uid) is False:
return False
return True
Side notes:
use is to check for True/False
use True/False and not 1/0 for boolean conditions (like valid variable)
[OPTIONAL / homework]
use docstrings instead of comments
add add type hints (see is_proper_length as an example)
you can use all() and pass all the calls into it, but the ifs will short circuit from the function without checking all the conditions (all depends on a problem, like number of conditions, length of the UID, number of UIDs to be checked etc.) and you can play around with order of the checks e.g. if the length is not right there's no need to check the rest (but it's a pre-optimization in a way, which is discouraged in general)
parametrize your functions further if need be, define params for number of upper to check, numeric and so on

Can't read empty input, which should set refresh to 60, gettin error instead

refresh = int(input('REFRESH (secs/enter=60s): '))
if refresh == '':
refresh = 60
ValueError: invalid literal for int() with base 10: ''
When I enter int value Iam not getting error, however I thought this should work when I enter 'nothing'
Its because you are mixing your variable types. Instead of converting the text input refresh to an int, leave it as a string so you can check against an empty string. Then after you have done your checking convert to an int (Python does this kind of conversion for you in some cases & other times you have to explcitly do it yourself, I've include both in the code below).
refresh = input('REFRESH (secs/enter=60s): ')
print(type(refresh))
if refresh == '': # here you are comparing a string with an empty string
refresh = 60 # here Python does the conversion for you
else:
refresh = int(refresh) # here you explicitly change the string to an int
print(refresh)
print(type(refresh))
The issue is in your first line.
By using int(var) you tell the program that var is for sure a valid int which it is not.
For positive integers you can use
>>> '16'.isdigit()
True

Program asks twice for number if wrong data is input first

I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.

get the list and input from one function and run them in different function

i have a programm that generate the list and then i ask them to tell me what they want to do from the menu and this is where my problem start i was able to get the input form the user to different function but when i try to use the if else condition it doesn't check, below are my code
def menu(x,l):
print (x)
if x == 1:
return make_table(l)
if x == 2:
y= input("enter a row (as a number) or a column (as an uppercase letter")
if y in [ "1",'2','3']:
print("Minmum is:",minimum(y,l))
if x== 3:
print ('bye')
def main():
bad_filename = True
l =[]
while bad_filename == True:
try:
filename = input("Enter the filename: ")
fp = open(filename, "r")
for f_line in fp:
f_str=f_line.strip()
f_str=f_str.split(',')
for unit_str in f_str:
unit=float(unit_str)
l.append(unit)
bad_filename = False
except IOError:
print("Error: The file was not found: ", filename)
#print(l)
condition=True
while condition==True:
print('1- open\n','2- maximum')
x=input("Enter the choice")
menu(x,l)
main()
from the bottom function i can get list and i can get the user input and i can get the data and move it in second function but it wont work after that.thank you
I think your problem is simple, and has nothing to do with how you're passing values between functions.
In main, you're reading a value from the user like this:
x=input("Enter the choice")
The input function:
… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, if the user types 1 at the prompt, you get back the string "1".
Now, you pass that value—perfectly correctly—to menu.
In menu, you then try to compare it to various numbers, like this:
if x == 1:
But this will never be true. A string, like "1", is never equal to a number, like 1. They're not even the same kind of value, much less the same value.
So, you need to do one of two things:
Convert the input to an number. For example, change menu(x,l) to menu(int(x), l). OR…
Write menu to expect strings. For example, change if x == 1: to if x == "1":.
You may be wondering why that print (x) didn't help you debug the problem.
print(x) prints out the end-user-friendly string representation of whatever you give it. That is, it automatically calls the str function for you. For debugging purposes, you often want to use repr instead of str, to get the programmer-friendly string representation instead of the end-user-friendly string representation.
For example, print(str("10")) will print out 10—just like print(str(10)), so you can't tell them apart. But print(repr("10")) will print out '10', unlike print(repr(10)), while prints 10, so you can tell them apart. repr can also help you spot things like strings with invisible characters in them, having special "node" objects from a parser instead of just strings, etc.

Python - display different output if the input is a letter or a number

I want to print the result of the equation in my if statement if the input is a digit and print "any thing" if it is a letter.
I tried this code, but it's not working well. What is wrong here?
while 1:
print '\tConvert ciliuse to fehrenhit\n'
temp = input('\nEnter the temp in C \n\t')
f = ((9/5)*temp +32)
if temp.isdigit():
print f
elif temp == "quit" or temp == "q" :
break
elif temp.isalpha() :
print ' hhhhhhh '
You need to go through your code line by line and think about what type you expect each value to be. Python does not automatically convert between, for example, strings and integers, like some languages do, so it's important to keep types in mind.
Let's start with this line:
temp = input('\nEnter the temp in C \n\t')
If you look at the documentation for input(), input() actually calls eval() on what you type in in Python 2.x (which it looks like you're using). That means that it treats what you type in there as code to be evaluated, just the same as if you were typing it in the shell. So if you type 123, it will return an int; if you type 'abc', it will return a str; and if you type abc (and you haven't defined a variable abc), it will give you an error.
If you want to get what the user types in as a string, you should use raw_input() instead.
In the next line:
f = ((9/5)*temp +32)
it looks like you're expecting temp to be a number. But this doesn't make sense. This line gets executed no matter what temp is, and you're expecting both strings containing digits and strings containing letters as input. This line shouldn't go here.
Continuing on:
if temp.isdigit():
isdigit() is a string method, so here you're expecting temp to be a string. This is actually what it should be.
This branch of the if statement is where your equation should go, but for it to work, you will first have to convert temp to an integer, like this:
c = int(temp)
Also, to get your calculation to work out right, you should make the fraction you're multiplying by a floating-point number:
f = ((9/5.0)*c +32)
The rest of your code should be okay if you make the changes above.
A couple of things first - always use raw_input for user input instead of input. input will evaluate code, which is potentially dangerous.
while 1:
print "\tConvert ciliuse to fehrenhit\n"
temp = raw_input("\nEnter the temp in C \n\t")
if temp in ("quit", "q"):
break
try:
f = ((9.0 / 5.0) * float(temp) + 32)
except ValueError:
print "anything"
Instead of using isalpha to check if input is invalid, use a catch clause for ValueError, which is thrown when a non-numerical value is used.
Why isn't it working? Are you getting an error of any kind?
Straight away I can see one problem though. You are doing the calculation before you verify it as a number. Move the calculation to inside the if temp.isdigit().
Take a look at this for some examples:
http://wiki.python.org/moin/Powerful%20Python%20One-Liners
OK, this works. Only problem is when you quit, you get dumped out of the interpreter.
while 1: import sys; temp=raw_input('\nEnter the temp in C \n\t'); temp.isdigit() and sys.stdout.write('%lf' %((9./5)*float(temp)+32)) or temp=='q' and sys.exit(0) or sys.stdout.write(temp)

Categories