Is there a way to get input from a def function? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was wondering if it's possible to get the only input from a def function.
def choose():
while True:
try:
pick = float(input("Enter any number that isn't 0 "))
if pick != 0:
break
else:
pick = float(input("Try again! Enter any number that isn't 0 "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
choose()
I will try to be as clear as possible. Can you take the pick input from choose() and store it somewhere else. Say like when your done inputting the number you want.
Can you run:
print(pick + 15)
or you can't take the input from the choose() at all. I would just like to know. Cause if so I don't even know how to do so. So I would appreciate the advice.

You can't access local variables from outside the function. The function should return the value, and you can assign that to another variable.
def choose():
while True:
try:
pick = float(input("Enter any number that isn't 0 "))
if pick != 0:
return pick
else:
print("Try again. The number has to be non-zero!")
except ValueError:
print("Sorry, I didn't understand that.")
choice = choose()
print(choice + 15)
You also shouldn't ask for input in the else: block, because it's going to ask again when the loop repeats. Just print the error message there, without reading input.
You don't need the continue statement, since loops automatically continue unless the repetition condition becomes false (which can never happen with while True:) or you execute a break or return statement to leave the loop.

Related

Why is there a SyntaxError Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I wrote this code snippet:
lowestNumber = int(input("\nWhat would you like your lowest number to be?"))
highestNumber = int(input("What would you like your highest number to be?"))
number = random.randint(lowestNumber, highestNumber)
tries = 0
while tries < 10:
guess = int(input(f'\nEnter a number between', lowestNumber))
if guess == number:
print("You guessed correctly! The number was", number)
break
elif guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
tries += 1
SyntaxError: bad input on line 22 in main.py.
Line 22 was guess = int(input(f'\nEnter a number between', lowestNumber)).
I searched it up on google and got nothing, I pasted it into OpenAI's code fixing and it also didn't help.
How can I fix this error?
When you wrote
guess = int(input(f'\nEnter a number between', lowestNumber))
it passed both the string and lowestNumber into the input function. However, you probably wanted to write something like Enter a number between (lowestNumber) and (highestNumber). To do this, you would have to write
guess = int(input(f'\nEnter a number between {lowestNumber} and {highestNumber}. '))
In my example, it passes in one object, the string, which contains lowestNumber and highestNumber in it. In your example, it passes in two objects, the string and lowestNumber.
The formatting you did in the input functions works in print statements, so the print statements are correct, but the input function is not.

How to make the try except function easier to read - Python 3 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
import random
chars = list('abcdefghijklmnopqrstuvwxyz1234567890')
password_char_list = []
password = ''
while True:
try:
password_length = int(input('Give the length of the password: '))
except ValueError:
print("Please give an integer.")
else:
break
def random_char():
char = random.choice(chars)
password_char_list.append(char)
for n in range(password_length):
random_char()
for n in password_char_list:
password += '' + n
print('Your password is ' + password)
So this is some code which I have written, an extremely simple and basic password generator. I'm self taught, new to Python and also new to the Stack Overflow community.
As you can see from the code above, I'm not completely fluent in Python yet. I've tried to use the try except function, but my code is far from concise and is difficult to read. What I would like to know is whether there is a better and slicker way to make sure that the input is an integer?
Many thanks,
Simply
P.S. this is the code which I would like to shorten
while True:
try:
password_length = int(input('Give the length of the password: '))
except ValueError:
print("Please give an integer.")
else:
break
Your code is fine and you shouldn't expect to be able to write Python more concisely than this. You could wrap the code in a function to make the logic even clearer.
def input_password_length():
while True:
try:
return int(input('Give the length of the password: '))
except ValueError:
print("Please give an integer.")
Often you will end up writing a more reusable function to make the overall code more concise and readable:
def input_integer(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please give an integer.")
password_length = input_integer('Give the length of the password: ')
You can write your try-except expressions in one line. That prevents some smaller codes with less purpose going into few lines.
while True:
try: password_length= int(input("Give the length of the password:")); break
except: print("Please give an integer:"); continue
Remove continue if you don't need to run it again.

How to debug beginners code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have 2 questions about my code. Why the program doesn't go in the second if statement. How can I end the loop?
from random import *
SecretNumber=randint(1,5)
Guess=int(input("Please enter Guess: "))
NumberofGuesses=1
SecretNumber=0
while Guess != SecretNumber:
NumberofGuesses=NumberofGuesses+1
if Guess>SecretNumber:
print("Please insert a smaller number")
else:
print("Please insert a bigger number")
if Guess==SecretNumber:
print("Number of Guesses: {0}".format(NumberofGuesses))
Your second if is outside the while loop, so it won't get hit until you guesss the secret number. The loop never ends because you never read another guess.
You also have a problem that you are overriding your random secret number with zero.
You need something like:
import random
SecretNumber=random.randint(1,5)
NumberofGuesses=0
while true:
Guess=int(input("Please enter Guess: "))
NumberofGuesses += 1
if Guess == SecretNumber:
break # Got it!
elif Guess>SecretNumber:
print("Please insert a smaller number")
else:
print("Please insert a bigger number")
print("Number of Guesses: {0}".format(NumberofGuesses))
It's because you're setting SecretNumber to 0. Remove it and it should work.

Python functions issue [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I wrote two functions. First one, when called checks if the number is three-digit, and second one is checking if the number is even or odd:
def even(n):
if n%2==0:
print('number {} is even'.format(n))
else:
print('number {} is not even'.format(n))
return
def main(n):
kraj=True
while(kraj):
a=int(input('three-digit number pls: '))
if (a>99 and a<1000):
kraj=False
return True
else:
print('I said three-digit number!! ::')
return False
main(0)
What my problem is, when I call function even like even(a), it gives me an error saying a is not defined.
You must return a in the main() function and pass it to the even function.
def main(n):
kraj=True
while(kraj):
a=int(input('three-digit number pls: '))
if (a>99 and a<1000):
kraj=False
return a
else:
print('I said three-digit number!! ::')
return False
a = main(0)
even(a)
You have to return the value of a so you can use it somewhere else
Also you have a while and return in if and else.
Therefore you do not need your while loop. Or you want the user to reenter on error you then have to get rid of the return in else
You should give your function a more meaningfull name like read_threedigit_number
You normally don't put paranthesis around if and while
Improved Code
def read_threedigit_number(n):
while True:
a=int(input('three-digit number pls: '))
if a>99 and a<1000:
return a
else:
print('I said three-digit number!')
a = read_threedigit_number(0)
even(a)

A number from Multiple Numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an assignment. It was suppose to do the following:
--> Take an integer input(say 100)
--> Add the digits till the sum is a single digit number(1)
My program till now is:
goodvalue1=False
goodvalue2=False
while (goodvalue1==False):
try:
num=input("Please enter a number: ")
except ValueError:
print ("Wrong input. Try again.")
else:
goodvalue1=True
if (goodvalue1==True):
ListOfDigits=list(map(int,str(num)))
sum=10
while(sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
Those booleans are not needed. You can factor the code down to:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
I don't see why you called list(map(int, str(num))); but I think you were intending to put int() around your input. So I added one in above. Now it can catch an error :).
Now, to get one digit, you can use another while loop here:
while num > 9:
num = sum(map(int, str(num)))
Pretty much this creates [1, 0, 0] which sum() then calls on. This repeats until it is no longer a two digit number (or three, four, etc)
So altogether:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
while num > 9: # While it is a two digit number
num = sum(map(int, str(num)))
Just note that for conditional statements, it's never pythonic to do a == True or b == False.
From the PEP:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
My take on this:
inp = None
while inp is None:
try:
inp = int(input('Enter number here: '))
except ValueError:
print('Invalid Input, try again')
summed = sum(map(int, str(inp)))
while summed > 9:
summed = sum(map(int, str(summed)))
print('The result is {}'.format(summed))
For an explanation #Haidro did a good job: https://stackoverflow.com/a/17787707/969534
You're very close. Here's what you need to change:
Sum=sum(ListOfDigits)
while(Sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
In this code, you have a while loop that executes when sum is bigger than 9. So why use another variable Sum (also, it makes for really difficult-to-read code)? Do this instead:
while(sum>9):
sum=sum(ListOfDigits)
ListOfDigits=list(map(int,str(sum)))
This is only to show you what went wrong with your code. I wouldn't recommend using it (look below for what I would do). First, you mix variable-naming conventions, which is a very bad idea, especially when you work in a team (even otherwise, can you imagine looking at your code a month or six months from now?).
Second, you don't ever use goodvalue2; what's it there for?
Third, if goodvalue1 is only ever going to be a bool, then why check if (goodvalue1==True)? if goodvalue1 is clearer and more pythonic.
Please, for the love of all that is good, use some spaces in your code. Eyes get very strained after looking at expressions like ListOfDigits=list(map(int,str(num))) for a while. Try ListOfDigits = list(map(int, str(num))) instead.
Personally, I would do this:
num = None
while num is None:
try:
num = int(raw_input("Enter a number: "))
except ValueError:
num = None
num = sum(int(i) for i in str(num))
while num > 9:
num = sum(int(i) for i in str(num)) # this uses a list comprehension. Look it up, they're very useful and powerful!
RECURSION !
Calculate the sum of the digits. Check if the sum has one digit or multiple digit. If one digit, that is your answer, else, call the function on the sum again.
def oneDigitSum(n):
if n < 10:
return n
else:
return oneDigitSum(sum([int(i) for i in str(n)]))
# [f(elem) for elem in li] = [f(a), f(b), .... ] where li = [a, b, ... ]
# sum returns the total of the numbers in list
while True: # continue this loop for eternity, until it gets break
try:
num=int(input("Please enter a number: "))
print(oneDigitSum(num))
break # printed the sum, now I can break the loop peace fully
except ValueError:
print ("Wrong input. Try again.")
continue # oops, looks like wrong input, lets continue the loop

Categories