Python not too hard, just struggling with variable - python

Code:
loop = 0
def main():
while loop == 0:
Num = input("Please Enter The Number Of People That Need The Cocktails ")
print()
print(" Type END if you want to end the program ")
print()
for count in range (Num):
with open("Cocktails.txt",mode="w",encoding="utf-8") as myFile:
print()
User = input("Please Enter What Cocktails You Would Like ")
if User == "END":
print(Num, "Has Been Written To The File ")
exit()
else:
myFile.write(User+"/n")
myFile.write(Num+"/n")
print()
print(User, "Has Been Written To The File ")
Error:
line 9, in main for count in range (Num): TypeError: 'str' object
cannot be interpreted as an integer
I'm trying to set the variable as the number of times it will repeat how many cocktails they would like.
Example:
How many cocktails ? 6
The script should then ask the user to enter what cocktails he wants six times.

In Python, input() returns a string by default. Change Num to:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
Also
MyFile.write(Num + "\n")
should read:
MyFile.write(str(Num) + "\n")
And just for the record, you can replace:
loop = 0
while (loop == 0):
with:
while True:

Cast int() on your input to make Num a workable integer. This has to be done because in Python 3, input always returns a string:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
With your code in it's current state, you are trying to construct a range from a string, which will not work at all as range() requires an integer.
EDIT:
Now you must replace:
myFile.write(Num+"/n")
with:
myFile.write(str(Num)+"/n")
Num is an integer at this point, so you must explicitly make a string to concatenate it with a newline character.

Related

Getting " 'NoneType' Object has no attribute 'isdigit' " error on my code

with the code I'm trying to accomplish is that I'm asking the user to for a number between 1 and 12 and then display the times table for that number.
The while loop checks if it's not a number or if its less than 1 or more than 12 then it will loop until it input is correct. However I get the error (written on the title)
Any ideas how to fix this?
user_input = print('Input number between 1-12: ')
#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input < 1) or int(user_input > 12)):
print("Please input a number between 1-12")
user_input = print("Input selection >> ")
#Now convert user_input into an int
user_input = int(user_input)
print('------------------------------------------')
print()
print(f'This is the {user_input} times table')
print()
for i in range(1,13):
print(f'{i} x {user_input} = {i*user_input}')
user_input = input('Input number between 1-12: ')
#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input)< 1 or int(user_input) > 12):
list of issues:
you printed instead of input to receive input from the user
you attempted to use < on instances of str and int, instead you should check this outside the int conversion to make sure that you trying to use < which both operands are int
user_input = print('Input number between 1-12:')
The above line only print out Input number between 1-12: to the console, it does not ask for the user to input anything. Since the print() function displays the string inside it and returns None, you get the error that you're getting.
If you want to take user input, then use the input() function like,
user_input = input("Input number between 1-12: ")
The above line will prompt the user to input something while also displaying the text

'int' object is not iterable in python 3

got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)

Checking user input to see if it satisfies two conditions

As part of a larger menu-driven program, I'd like to test user input to see if that input:
is an integer AND
if it is an integer, if it is within the range 1 to 12, inclusive.
number = 0
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invlaid input, please try again >>> ")
continue
else:
if not (1<= number <=12):
print("Need a whole number in range 1-12 >>> ")
continue
else:
print("You selected:",number)
break
I'm using Python 3.4.3, and wanted to know if there's a more succinct (fewer lines, better performance, more "Pythonic", e.g.) way to achieve this? Thanks in advance.
You don't need anything bar one if in the try:
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
if 1 <= number <= 12:
print("You selected:", number)
break
print("Need a whole number in range 1-12 >>> ")
except ValueError:
print("Invlaid input, please try again >>> ")
Bad input will mean you go straight to the except, if the input is good and is in your accepted range, the print("You selected:", number) and will be executed then we break or else print("Need a whole number in range 1-12 >>> ") will be executed if is outside the range.
Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary continues):
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invalid input, please try again >>> ")
else:
if 1 <= number <= 12:
print("You selected: {}".format(number))
break
else:
print("Need a whole number in range 1-12 >>> ")
Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one if and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits.
while True:
num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
if num_str.isdigit() and int(num_str) in range(1,13):
print("You selected:",int(num_str))
break
else:
print("Need a whole number in range 1-12 >>> ")
I don't think you need a whole try/except block. Everything can be fit into a single condition:
number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories