How to make variable accept strings - python-3.x

I want to make this code keep going? I tried put an x == to str, but I think that could not be the answer.
while True:
x = int(input("Please enter an integer:
"))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
x == str :
input("please enter a string")

The first line of your loop can have one of two effects: either x is guaranteed to be an int, or you'll raise a ValueError. Catch the error and restart the loop, or continue with the body knowing that x is an int
while True:
x_str = input("Please enter an integer: ")
try:
x = int(x)
except ValueError:
print("{} is not an integer; please try again".format(x))
continue
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')

I'll try to guess what you wanted. I think you wanted a function that is like input, but with a strange twist: if what is entered (x) can be interpreted as an integer, then it returns the integer itself, not x. For example, if the user enters -72, it returns -72, not '-72'. Of course, if the user enters something that cannot be interpreted as an integer, the function returns it without modification.
Of course, being strongly typed, Python doesn't provide such a function, but it's easy to write one. And you don't even need try if you just intend to accept "ordinary"-looking integers.
def intput(prompt=''):
entered = input(prompt)
if entered[entered.startswith('-'):].isdigit(): return int(entered)
else: return entered
while True:
x = intput('Please enter an integer: ')
if x < 0:
x = 0
print('Negative input changed to zero')
elif x == 0: print('Zero')
elif x == 1: print('Single')
elif isinstance(x, str): print('You have entered a string that cannot be '
'easily interpreted as an integer.')

Related

I'm trying to make a sequence calculator with python, and I would like to restart the code at a certain point but I don't know how to do that [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
I am fairly new to programming and I scrapped some code together to make a sequence calculator using python.
I'm trying to restart it at the "user_continue = input ("Would you like restart [y/n]? ")" part whenever the user would input an invalid answer, but I don't know how to do that, help?
import time
from time import sleep
while True:
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
???
import time
from time import sleep
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
def takeInputs():
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
takeInputs()
while True:
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
takeInputs()
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")

Python 3 for beginners Control Flow, While Loops and Break Statements

I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.

How to fix issue where python won't call a function from within a loop

At the yes/no loop, the program won't call the function to re-perform a calculation. Instead, it asks to compute another gcd repeatedly instead of calling the specified function.
I've tried re-inputting the whole function into the question loop if the user inputs yes, but that did not work either.
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
GCD = gcd(n,m)
print("The GCD of the two numbers you entered is:" ,GCD)
while True:
a = input("Compute another GCD? Enter y/n:").lower()
if a=="y":
gcd(n,m)
elif a=="n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
Expected results is that it calls the function gcd(n,m) and re-performs a calculation. Actual results is that it asks to perform another calculation without having actually completed a second calculation.
The function is called. The problem is that you don't do anything with its return value.
You will also need to ask the user for new input. In order to not repeat the same code again you can have a function that does that.
Then the whole code becomes:
def get_2_numbers():
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
return n, m
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
a, b = get_2_numbers()
while True:
answer = input("Compute another GCD? Enter y/n:").lower()
if answer == "y":
print(gcd(a, b))
a, b = get_2_numbers()
elif answer == "n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
A small downside is that the user will have to answer y even before the first calculation, but I'll leave that as an exercise to the reader.

"if elif" statement dependent on input won't run after placing my input

My problem is the script ends immediately after I enter an input.
def add(var1, var2):
print(var1 + var2)
def times(var1, var2):
print(var1*var2)
x = input("press 1 to add, press 2 to multiply: ")
if x == 1:
print("what two number do you want to add?")
a = input("input first number: ")
b = input("input second number: ")
add(a, b)
elif x == 2:
print("what two number do you want to multiply?")
a = input("input first number: ")
b = input("input second number: ")
times(a, b)
I want the script to run the if-elif statement which is dependent on the entered input.
The input function returns a string. You should therefore either compare its returning value to a string instead of an integer:
if x == '1':
...
if x == '2':
or convert the returning value to an integer first:
x = int(input("press 1 to add, press 2 to multiply: "))
The input will be a string not a number, and 2 != '2'. You need to convert the input to an integer before trying to use it.
input() will return str, you need to convert it to int before calculating.
x = input("press 1 to add, press 2 to multiply: ")

I cant make the program continue to loop if its invalid input is entered

I have this program:
number = int(input('Contact Number:'))
def validatePhoneNumber(number):
count = 0
while True:
while number > 0:
number = number//10
count = count+1
if (count == 10) :
break
elif (count > 10) :
print('Invalid phone number')
return -1
elif (count < 10):
print('Invalid phone number')
return -1
validatePhoneNumber(number)
it will appear like this:
Contact Number:1234
Invalid phone number
>>>
I want it to continue to loop until a 10 digit number is entered then it will stop.
Contact Number:1234567890
>>>
The condition is that If the number is missing or invalid, return ‐1.
Am I missing something inside the program?
Thanks
What about this:
number = input('Contact Number:') # it's a str now, so we can use len(number)
def validatePhoneNumber(number):
while len(number) != 10:
number = input("Please enter a 10-digit contact number: ")
return number
number = validatePhoneNumber(number)
It's a more pythonic approach and therefore easier to understand and debug. Also as other comments pointed out, leading 0s aren't stripped away now.

Resources