Python is there a way to hide a programm - python

program, info = input ("->") .split ()
if program == 'search':
print (info)
elif program == 'hello':
print ("do")
else:
print ("Error")
In this example, the input is split.
E.g.
search youtube.com
Output:
youtube.com
But now I would also like to manage that you can only enter 1 word and it still works.
Such as.
elif program == 'hello':
that means I only type in hello and it works too.
then the output should be:
do
but only one word doesn't work at the moment, how do I get that?

You could add an asterisk to the info variable:
program, *info = input("->").split()
if program == 'search':
print(info[0])
elif program == 'hello':
print("do")
else:
print("Error")
This result in info being a list of everything after the first element of the split input. If you enter search youtube.com, the variable info will contain ['youtube.com']. If you enter hello, the variable info will contain nothing, i.e. [].
Note that I also added a list access to the info variable in line 4, where it is printed.
More information on how to solve this and/or why this works can be found here, where default values in unpacking are discussed.
Edit: As #Steve pointed out, this becomes problematic if only search is entered, because you'd try to access the first element of an empty list. To prevent this, you can add an extra check to your code:
program, *info = input("->").split()
if program == 'search':
if not info:
print("Error, nothing to search for")
else:
print(info[0])
elif program == 'hello':
print("do")
else:
print("Error")

Simply check the size of the input before assigning the variables:
data = input("->").split()
if len(data) == 2:
program = data[0]
info = data[1]
elif len(data) == 1:
program = data[0]
else:
print("invalid number of arguments")

Related

Default output of input

I'm trying to make a sample code that extracts first name from a full name.
If my input is not string or simply press just enter, it will print out enter valid name.
But no matter what I type, it just prints out normal outcome.
Also if I type nothing, it just makes an error.
How can I solve this?
name = input("Enter your full name (end to stop): ")
def print_first_name():
if type(name) == str:
name.split()
first = name.split()[0]
last = name.split()[-1]
print('Your first name is: ', first)
elif name == 'end':
break
else:
print('You must enter at least your first name!')
print_first_name()
name = input("Enter your full name: ")
def print_first_name():
if len(name) > 0:
first = name.split()[0]
if first.isalpha():
print('Your first name is: ', first)
else:
print("Enter a valid name")
last = name.split()[-1]
else:
print('You must enter at least your first name!')
print_first_name()
The condition you wrote (type(name)==str) will always be true
we cant use break outside a loop. (in your case, there was no loop at all, so u cant use break)
if you enter nothing, it gives an error because the line
name.split()[0]
if name="", (which means an empty string), name.split() gives an empty list
In a empty list, there will be no element at index 0, so it gives an error.
When you say if type(name) == str:, then even when you type end as input, this condition is satisfied and the if block is executed and hence code flow never goes to the elif block.
You can put your else condition first and then the if condition:
if name == 'end':
#do whatever
elif type(name) == str:
#do whatever
else:
print('Invalid input')
Your code has a few problems, marked with comments below:
name = input("Enter your full name (end to stop): ")
# Generally you should pass a variable to a function
# or define the variable inside the function, rather
# than using a global variable (name). It's not clear
# which part of the code you want to isolate in a
# function in this example, so it's probably simplest
# not to use a function at all.
def print_first_name():
# The next test will always be True, so the else
# and elif parts will never run.
# You probably want a test for non-empty
# strings with only alphabetic characters instead
if type(name) == str:
# the next line creates a list of the parts of
# name (if possible) but doesn't store it
# anywhere, so it has no effect.
name.split()
# the next two lines will fail if name is
# an empty string
first = name.split()[0]
last = name.split()[-1]
print('Your first name is: ', first)
# the next block needs to be moved earlier to
# make sure it is tested before you try to extract
# the names
elif name == 'end':
# break cannot be used inside a function
# even if the function is called in a loop
break
else:
print('You must enter at least your first name!')
print_first_name()
Here's a version that fixes these problems:
while True:
name = input("Enter your full name (end to stop): ")
# check this first, to avoid treating as a name
if name == 'end':
break
# check whether name contains any digits or is empty
elif name.isalpha() and name != "":
name_parts = name.split()
first = name_parts[0]
last = name_parts[-1]
print('Your first name is: ', first)
else:
print('You must enter at least your first name!')
input() defaults to returning a string type. It looks like you're trying to sanitize the input by making sure the input is a string of letters, and also has a length > 0 before running.
You would probably be served by flipping out
if type(name) == str:
with something that checks both for a non-zero AND alpha only. so something like
if name.isalpha() and len(name) > 0:
{conditional code here...}
The input is always string, so you can use a array or list to store 0 -> 9 numbers (The str one). If there is a number in input, it'll print something.
You can use '' to describe that input is empty

Storing User Input in a List and writing a loop to find a valid value from that list

New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.
I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.
I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?
Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.
while True:
if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)
Here's some code that does what you described in the comments.
We use two while loops. The first one gets lines of input, one by one, and adds them to the list_of_inputs. If a line consisting of the string "done" is read we break out of the loop, and we don't add "done" to the list.
The second loop gets lines of input and tests whether or not they are present in list_of_inputs, printing an appropriate message. If the user inputs a line that is present in list_of_inputs we break out of the loop and the program ends.
print('Please enter values for the list, one value per line')
print('Enter "done" (without the quotes) to end the list')
list_of_inputs = []
while True:
s = input('value: ')
if s == 'done':
break
list_of_inputs.append(s)
print('Here is the list:')
print(list_of_inputs)
while True:
s = input('Please enter a test value: ')
if s in list_of_inputs:
print('Yes!', repr(s), 'is in the list')
break
else:
print('No', repr(s), 'is NOT in the list')
test run
Please enter values for the list, one value per line
Enter "done" (without the quotes) to end the list
value: abc def
value: ghi
value: jkl
value: done
Here is the list:
['abc def', 'ghi', 'jkl']
Please enter a test value: def
No 'def' is NOT in the list
Please enter a test value: ghij
No 'ghij' is NOT in the list
Please enter a test value: jkl
Yes! 'jkl' is in the list
Python 3.x
list_of_inputs = list()
while True:
var = input("Enter Number or type 'done' to exit :")
if var.lower() == 'done':
print(" Your inputs are: ",list_of_inputs)
exit()
else:
list_of_inputs.append(int(var))
Make sure indentation is proper in python codes.

Having issues with a program to input multiple numbers from the user, till the user types “Done". To compute their average and print the results

So here is how the program is supposed to work. The user would input something like this and the output would give them the answer.
Input:
1
2
2
1
Done
Output:
1.5
So far I was able to come up with the input question and got it to loop until you put Done.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
else:
nums.append(int(num))
I don't know how to make the program perform the calculation to print out the average. I am very new to programming in python and I would appreciate any help I can get on fixing this program. Thanks in advance!
Break while loop when 'Done' is the input, else save the number as float. This throws an error if you try to enter 'finish'. Finally calculate and print the Average.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done": # This has to be tested inside the while loop
break
# Only append after testing for 'Done'
nums.append(float(num)) # Ensure valid input by convert it into the desired type.
print('average: %s' % (sum(nums) / len(nums)))
It is a good practice to give the user useful error messages, when some input is not as the program needs it. It can save the user lots of trouble. If you just want to tell the user what the problem was when an invalid input is given, you can do it with a try statement as below:
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
try:
nums.append(float(num))
except Exception:
print('Please enter a number. Input "%s" will be ignored.' % num)
print('average: %s' % (sum(nums) / len(nums)))

For loop with If and elif or else in python

Question 1:
Just tried to execute the program but i am getting syntax error
i=input('Enter the value of i')
for j in range(10):
if i==j:
print'The value of i is %d'%(i)
elif i!=j:
print'Please enter a valid value'
else:
print 'This is not a number'
The difference between the below two codes is that code one will ask for input once and then loop trying to compare, while code two will ask for input each loop (10x)...
If your code is really indented as you put it here, the reason you are getting a syntax error is that your elif and else blocks are indented too far. Another problem with your code is that i can be either equal or not equal to j. There is no third option. Another problem is that the first time it comes across a number that is not equal to the number typed, it will say that it is not a valid value. Also, just saying "Please enter a valid value" will not make it so. Here is a better version of your code:
i = None
while True:
i = input("Enter the value of i")
if i.isdigit():
if int(i) in range(10):
print "The value of i is %d" % i
else:
print "Please enter a valid value"
else:
print "This is not a number"
As for question 2, the difference between the two is that in the first, i=input('Enter the value of i') will be executed before the loop, and in the second it will be executed for each iteration of the loop. (That is, one time for each time the loop is executed. Because range(10) returns ten items, it runs ten times.) More about for loops here, here, and here
You appear to be having a syntax error because of inconsistent levels of indentation in your code. Please try the following instead and adjust the program to suit whatever your needs might be.
#! /usr/bin/env python3
import sys
def main():
loop = True
while loop:
try:
i = int(input('Enter of the value of i: '))
except EOFError:
sys.exit()
except ValueError:
print('This is not a number')
else:
if 0 <= i <= 9:
print('The value of i is', i)
loop = False
else:
print('Please enter a valid value')
if __name__ == '__main__':
main()

Loop keeps going after being carried out

def Help(string):
while True:
if string == 'Manifest':
return Manifest()
break
elif string == 'Intent':
return Intent()
break
else:
print('The options available are: \n')
for i in andHelp:
print(i)
print('Type Q to Quit \n')
x = input('What option do you choose: ')
print('\n')
if x == 'Q':
break
else:
Help(x)
How come if it goes into the else statement it will keep looping?
for example:
"The options available are:
Intent
Manifest
Type Q to Quit
What option do you choose: " <-- this will keep coming up aswell as the function I choose.
You don't even need a while loop for what you are checking. Use this instead:
def Help(string):
if string == 'Manifest':
return Manifest()
elif string == 'Intent':
return Intent()
else:
print('The options available are:\n%s\nType Q to Quit\n' % '\n'.join(andHelp))
x = input('What option do you choose: ')
print('\n')
if x != 'Q':
Help(x)
note: I modified your prints a bit to reduce extra lines that really, didn't need to be there.
note2: As you may see in the comments, it may be dangerous to do this recursively without a limitation because you may reach a maximum depth level.
Your actual problem is due to your recursion not actually returning the inner frame's value, but eliminating the recursion seems a more straightforward solution.
What's goofy about this is doing a recursion inside a loop. Both the recursion and the loop serve the same purpose: To make the option choice keep happening until a valid option is given. So you can definitely eliminate one:
def Help(string):
while True:
if string == 'Manifest':
return Manifest()
break
elif string == 'Intent':
return Intent()
break
else:
print('The options available are: \n')
for i in andHelp:
print(i)
print('Type Q to Quit \n')
string = input('What option do you choose: ') # Change `x` to `string` so next iteration will change behavior
print('\n')
if string == 'Q':
break
As Inbar Rose's answer points out, you can shorten this quite a bit with recursion, but since Python requires a recursion limit, you can make the program crash by forcing it to recur beyond that limit. So perhaps sticking with the loop is better. Anyway, you can clean it up further by having the validation of string be the condition of the loop itself:
def Help(string):
validOptions = ('Manifest', 'Intent', 'Q')
while string not in validOptions:
print('The options available are: \n')
for i in andHelp:
print(i)
print('Type Q to Quit \n')
string = input('What option do you choose: ')
print('\n')
# Now you have a guaranteed-valid string, so you don't need this part in the loop.
if string == 'Manifest':
return Manifest() # No need for a 'break' after a return. It's [dead code](http://en.wikipedia.org/wiki/Dead_code)
elif string == 'Intent':
return Intent()
elif string == 'Q':
return

Categories

Resources