Pyhon didn't show on console a function - python

I have this function in python:
def Alex():
print ("Numele si prenumele: Alex Popescu.")
print ("Varsta: 27 ani.")
print ("Salariu: €1750 ")
print ("Post: Tirist.")
if __name__ == '__main__':
Alex()
When I'm calling the function, python doesn't print the function CODE AND COMMAND LINE

Value returned by input is always string even if someone type only digits like '1'.
actiune = input('Ce actiune doriti sa faceti?(1-4): ')
if actiune == '1':
def Alex():
print ("Numele si prenumele: Alex Popescu.")
print ("Varsta: 27 ani.")
print ("Salariu: €1750 ")
print ("Post: Tirist.")
if __name__ == '__main__':
Alex()

The problem is that input returns a string, and you compare that string with an integer in the code in the picture. actinue = int(actinue) should fix it. Alternatively you might compare it with "1" instead of 1.

Related

User input for gender not functioning

I am attempting to make a game that I made via Rpg Maker MV in python but I've hit a road block in the if statement or rather the gender input. The code is meant to have the user input either "Boy" or "Girl" and depending on that the variable "gender" will be set for pronouns. How ever the console is saying This
This is the code
import time
print ("Elvoria")
print ("Start")
input = input()
if input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if input == ("Boy"):
gender = 1
elif input == ("Girl"):
gender = 2
else:
print ("Error")
You need to check the input using the variable name genderin that you defined, instead of input == ("Boy").
EDIT: Also, you are mirroring the built-in method input() with the variable name input and you should not do that. Rename your variable to e.g. start_input.
import time
print ("Elvoria")
print ("Start")
start_input = input()
if start_input == "Start":
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print ("Error")
You're defining the variable "input" on line 4 to be a string, given from the "input" function. This overrides the keyword. Then, on line 9, you're calling "input" again. Since you've replaced the built-in function with a string, an error is thrown (the error "not callable" means that you're trying to treat a non-function like a function).
Here's your code sample, without overriding built-in methods:
import time
print ("Elvoria")
print ("Start")
user_input = input()
if user_input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == ("Boy"):
gender = 1
elif genderin == ("Girl"):
gender = 2
else:
print ("Error")
You should avoid using input as a varible name, since a built-in function with that name already exists, input(). So just change it's name to something else. Secondly, you're storing the gender input (boy/girl) in genderin, but then checking input, when you should be checking genderin. So the code after fixing these would look something like this:
import time
print ("Elvoria")
print ("Start")
choice = input()
if choice == "Start":
print("Always Great To See New People")
time.sleep(1)
print("Now Are You A Boy Or Girl?")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print("Error")
I have used choice for demonstration purposes, you can use a different name if you want, just remember to make sure that a python built-in with that name doesn't exist. Also, no need to put ("Start") in the if statement, use "Start" instead (same goes for other if/elif statements)
You have also used print ("example") (space between print and brackets), i've rarely ever seen someone using this, most people use print("example") instead.
Finally a tip -> You can make the string lowercase, genderin = genderin.lower() to manage case sensitivity, i.e, both boy and Boy will be valid inputs, etc.

I have trouble with Python outputting "None" with every line of output

I am trying to make python cipher and decipher text with the Playfair method. But I hit a roadblock because it seems to output "None" with every line out output.
I'd be grateful if anyone tells me why it's doing so.
(This is my first post, so please bear with any mistakes I might have made).
My code:
def cip():
key=input(print("Please Enter Keyword: "))
return key
def inp():
c = int(input(print("1.Cipher text \n2.Exit\n\t>>")))
if c==1:
cip()
else:
exit
inp()
Output:
C:\Users\XYZ\Desktop\Code\Py programs>python -u "c:\Users\XYZ\Desktop\Code\Py programs\Playfair.py"
1.Cipher text
2.Exit
>>
None1
Please Enter Keyword:
NoneTron
The problem is your use of print() in the input() call.
c = int(input(print("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>")))
^^^^^
print() prints its argument, and returns None. input() uses the value of its argument as the prompt, so it's printing None as the prompt.
Just pass a prompt string to input(), don't call print()
c = int(input("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>"))
The problem is when you use input with print in it. Print should be outside.
def cip():
print("Please Enter Keyword: ")
key=input()
return key
def inp():
print("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>")
c = int(input())
if c==1:
cip()
elif c==2:
decip()
else:
exit
inp()
You could also put the string in input(), like this:
c = int(input("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>"))

Check if Python list contains a specific element

I wrote a sample program to generate a hash code from input (it's not done yet so you don't see the part where it actually generates the hash):
import hashlib
def isInputValid(input, validInput=[]):
for i in validInput:
if validInput[i] == input: # error generated here
return True
pass
i = i + 1
return False
pass
sha1hash = hashlib.sha1()
choiceValidInputs = ["1", "2"]
print ("Welcome to hash generator!\n")
print ("[1] -- generate hash from input")
print ("[2] -- quit")
choice = input("\nWhat do you want to do? ")
if not isInputValid(choice, choiceValidInputs):
print ("Invalid option; try again")
choice = input("What do you want to do? ")
if choice == "1":
print ("\n[1] SHA1/SHA256")
print ("[2] SHA512")
hashType = input("\nWhat hash type do you want? ")
...
elif choice == "2":
print ("Goodbye!")
quit()
My Terminal window:
kali#kali:~$ python3 /home/bin/hashgenerator.py
Welcome to hash generator!
[1] -- generate hash from input
[2] -- quit
What do you want to do? 1
Traceback (most recent call last):
File "/home/bin/hashgenerator.py", line 19, in <module>
if isInputValid(choice, choiceInput)==False:
File "/home/bin/hashgenerator.py", line 5, in isInputValid
if validInput[i] == input:
TypeError: list indices must be integers or slices, not str
kali#kali:~$
I want to check if the input is present in choiceValidInputs. I actually don't really know how to work with lists etc. in Python.
Thanks for helping
you're looping through elements not indexes
If you want to use indexes:
def isInputValid(input, validInput=[]):
for i in range(len(validInput)):
if validInput[i] == input: # error generated here
return True
If you want to use elements you can do
def isInputValid(input, validInput=[]):
for i in validInput:
if i == input: # error generated here
return True
But you can do it more easily. And more correctly :)
def isInputValid(input, validInput=[]):
return input in validInput
for i in validInput:
if validInput[i] == input:
i here is not an index of an item in validInput, it is the item itself. What you want to do is:
for i in validInput:
if i == input:
Besides, you don't need pass and i = i+1 below. And I would suggest renaming variable input to something else to avoid confusion with input() function.

Return string from Python to Shell script

I have Python code like:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
Write your error messages to standard error, to avoid them being captured as well.
Use raw_input, not input, in Python 2.
)
Then your shell
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason not to, always quote parameter expansions.
Just use print instead of return - you bash snippet expects result on STDOUT.

Why if-then statement isn't working?

This is the code that I made when I tried making an if-then statement but, it always defaults to else. Also i just started trying to code from online tutorials today.
print('yes or no?')
if sys.stdin.readline() == 'yes' :
print('Yay')
else :
print('Aww')
This is what happens:
Console:yes or no?
Me:yes
Console:Aww
I've been looking stuff up for half an hour and can't figure out how to fix this please help
sys.stdin.readline() reads a line which ends with '\n' (when you hit "enter").
So you need to remove this '\n' from the captured input using strip().
print('yes or no?')
if sys.stdin.readline().strip() == 'yes' :
print('Yay')
else :
print('Aww')
I tried to explain and solve your specific problem but you could of course use raw_input() or input() (PY3) as mentioned in the other answer.
In python, getting the input of a user's string can be done via input() (or in python 2.7, use raw_input()).
If you include the code:
user_input = raw_input("yes or no?")
This will first print the string "yes or no?", then wait for user input (through stdin), then save it as a string named user_input.
So, you change your code to be:
user_input = raw_input("yes or no?")
if user_input == "yes":
print("Yay")
else:
print("Aww")
this should have the desired effect.
Ok I used user_input and input instead of sys.stdin.readline() on strings and i used it in a basic calculator here it is :
import random
import sys
import os
user_input = input("Would you like to add or subtract?")
if user_input == 'add' :
print('What would you like to add?')
plus1 = float(sys.stdin.readline())
print('Ok so %.1f plus what?' % (float(plus1)))
plus2 = float(sys.stdin.readline())
print('%.1f plus %.1f equals %.1f' % (float(plus1),float(plus2), float(plus1+plus2)))
elif user_input == 'subtract' :
print('What would you like to subtract?')
minus1 = float(sys.stdin.readline())
print('Ok so %.1f minus what?' % (float(minus1)))
minus2 = float(sys.stdin.readline())
print('%.1f minus %.1f equals %.1f' % (float(minus1), float(minus2), float(minus1 - minus2)))
else :
print('That is not one of the above options')
Thanks alot guys!

Categories

Resources