Python novice: Setting limits for multiple integers taken as input - python-3.x

I'm trying to write a program that would take an input of 3 numbers (i, j & k) in a single line separated by spaces, with limits for each number being from 1 to 1000 (inclusive). I need some advice regarding how to set the limit for all three numbers at once. Thanks in advance! My buggy code is below:
i, j, k = input("Please input 3 numbers between 1 and 1000:").split()
i, j, k = int(i), int(j), int(k)
if i, j, k >1000 or i, j, k <1:
print ("Please try again")
else:
print ("Thank you!")

Use Python's any() and all() functions for testing conditions on large number of values. In your case it should look like
if all([1<=x<=1000 for x in [i,j,k]]):
print ("Thank you!")
else:
print ("Please try again")

Related

Want to get input on same line for variables at different places in Python3. See the below code and text for clarification

I want to take input of how many inputs the user is going to give next and collect those inputs in a single line. For eg. if user enters '3' next he has to give 3 inputs like '4' '5' '6' on the same line.
N = int(input())
result = 0
randomlist = []
for number in range(N):
K = int(input())
for number2 in range(K):
a = int(input())
if number2 != K - 1:#Ignore these on below
result += a - 1
else:
result += a
randomlist.append(result)
result = 0
break
for num in range(N):
b = randomlist[num]
print(b)
Now I want the input for K and a (also looped inputs of a) to be on the same line. I have enclosed the whole code for the program here. Please give me a solution on how to get input in the same line with a space in between instead of hitting enter and giving inputs
Based on what I read from your question, you are trying to request input from the user and the desired format of the input is a series of numbers (both integers and floats) separated by spaces.
I see a couple of ways to accomplish this:
Use a single input statement to request the series of numbers including the count,
Just ask the user for a list of numbers separated by spaces and infer the count.
To perform these operations you can do one of the following:
#Request User to provide a count followed by the numbers
def getInputwithCount():
# Return a list Numbers entered by User
while True:
resp = input("Enter a count followed by a series of numbers: ").split(' ')
if len(resp) != int(resp[0]) + 1:
print("Your Input is incorrect, try again")
else:
break
rslt = []
for v in resp[1:]:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
or for the simpler solution just ask for the numbers as follows:
def getInput():
# Return the list of numbers entered by the user
resp = input("Enter a series of numbers: ").split(' ')
rslt = []
for v in resp:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt

Geometric mean-algorithm without package

I have a task to write a program which for a sequence number as a result give a geometric mean. I have to write this program without any package.
The introduction of the program end, when users give a 0.
The program should report an error if the first number is 0 and if the user gives a negative number.
def sequence():
prod=1
i=-1
x=1
n = int(input("Give a number: "))
while True:
if n == 0:
break
elif i==0:
print("Error")
else:
prod=prod*n
i=i+1
result=prod**(1/i)
print(" Średnia wartośc ciągu ", result)
return i, suma
sequence()
My program doesn't return anything.
I don't want to post the solution, I'd rather point out several problems with the code. Figuring them out on your own will make you a better coder. There are several problems with your algorithm:
You'd better start with i=0
elif i==0: won't work as you expect it has to be an if i==0: under if n==0:, so that you exit the loop when you get 0 from the user and you print Error when it is the first iteration.
n = int(input("Give a number: ")) has to be within the loop, so that it gets assigned on every iteration of your algorithm.
return i, suma should be outside the while loop.

Loop won't finish...Poor indentation?

I am new to python and Jupyter Notebook
The objective of the code I am writing is to request the user to introduce 10 different integers. The program is supposed to return the highest odd number introduced previously by the user.
My code is as followws:
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: '))
if c%2==0:
print('The number is even')
elif c> y
y=c
print('y')
i=i+1
My loop is running over and over again, and I don't get a solution.
I guess the code is well written. It must be a slight detail I am not seeing.
Any help would be much appreciated!
You have elif c > y, you should just need to add a colon there so it's elif c > y:
Yup.
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: ')) # This line was off
if c%2==0:
print('The number is even')
elif c> y: # Need also ':'
y=c
print('y')
i=i+1
You can right this in a much compact fashion like so.
Start by asking for 10 numbers in a single line, separated by a space. Then split the string by , into a list of numbers and exit the code if exactly 10 numbers are not provided.
numbers_str = input("Input 10 integers separated by a comma(,) >>> ")
numbers = [int(number.strip()) for number in numbers_str.split(',')]
if len(numbers) != 10:
print("You didn't enter 10 numbers! try again")
exit()
A bad run of the code above might be
Input 10 integers separated by a comma(,) >>> 1,2,3,4
You didn't enter 10 numbers! try again
Assuming 10 integers are provided, loop through the elements, considering only odd numbers and updating highest odd number as you go.
largest = None
for number in numbers:
if number % 2 != 0 and (not largest or number > largest):
largest = number
Finally, check if the largest number is None, which means we didn't have any odd numbers, so provide the user that information, otherwise display the largest odd number
if largest is None:
print("You didn't enter any odd numbers")
else:
print("Your largest odd number was:", largest)
Possible outputs are
Input 10 integers separated by a comma(,) >>> 1,2,3,4,5,6,7,8,9,10
Your largest odd number was: 9
Input 10 integers separated by a comma(,) >>> 2,4,6,8,2,4,6,8,2,4
You didn't enter any odd numbers

Option to save output printed on screen as a text file (Python)

Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break

Count iterations in a loop

New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.
import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the while loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).
Here's an example:
counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
The value printed will be the number of times the while loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.
You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:
print('The while loop ran {} times'.format(counter))
Calling the format function on a string allows you replace each instance of {} within the string with an argument.
Edit: Changed to reassignment operator

Resources