Getting an NameError but my variable is defined - python

I do not know why I am getting this error
NameError: name 'len_num' is not defined
def is_armstrong_number(num):
#Convert number to string
num_str = str(num)
#Get length of number
len_num = len(num_str)
#Select each number in string and store it in list
for x in range(1,len_num):
num_list.insert(x,num_str[x])
#Convert back to int
int(num_list)
#Compare armstrong number and list
for x in range(1,len_num):
if num == num_list(x) ** len_num:
print("It is an armstrong number")
else: print("It is not an armstrong number")
pass
len_num is local to the function so I do not see the issue with the name since it is defined before it is used.

Your issues could be with identation. Compare with my code:
def is_armstrong_number(num):
#Convert number to string
num_str = str(num)
#Get length of number
len_num = len(num_str)
#Select each number in string and store it in list
for x in range(1,len_num):
num_list.insert(x,num_str[x])
#Convert back to int
int(num_list)
#Compare armstrong number and list
for x in range(1,len_num):
if num == num_list(x) ** len_num:
print("It is an armstrong number")
else: print("It is not an armstrong number")
pass
is_armstrong_number(2)
# Output
# It is not an armstrong number
~
I don't get the error after running.

Related

Determining the two largest numbers from user input

I've been working on a small program to learn more about Python, but I'm stuck on something.
Basically, the user has to input a sequence of positive integers. When a negative number is entered, the program stops and tells the user the two largest integers the user previously inputted. Here is my code:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while (number > 0):
number = int(input())
if number < 0:
break
largestInteger = max(numbers)
print(largestInteger)
integers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
There are two issues with your code:
You need to update the list with the user input for every iteration of the while loop using .append().
integers isn't defined, so you can't call .remove() on it. You should refer to numbers instead.
Here is a code snippet that resolves these issues:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while number > 0:
number = int(input())
if number > 0:
numbers.append(number)
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
I would build a function that would call itself again if the user enters a number larger or equal to 0, but will break itself and return a list once a user inputs a number smaller than 0. Additionally I would then sort in reverse (largest to smallest) and call only the first 2 items in the list
def user_input():
user_int = int(input('Please enter your desired integers'))
if user_int >= 0:
user_lst.append(user_int)
user_input()
else:
return user_lst
#Create an empty list
user_lst = []
user_input()
user_lst.sort(reverse=True)
user_lst[0:2]
You forgot to append the input number to the numbers list
numbers = []
while (True):
number = int(input())
if number < 0:
break
numbers.append(number)
print("First largest integer: ", end="")
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
print("Second largest integer: ", end="")
largestInteger2 = max(numbers)
print(largestInteger2)```
The above code will work, according to your **desire**

I have this code but whenever I input a word such as cow it stops working

Whenever I run this code it doesn't allow inputs such as cow. I have included the term float as I would like number and word input. I can enter numbers but not words. Has anyone got an idea where I am going wrong?
my output should look like :
How many strings do you want to enter:3
Enter string 1: 2
Enter string 2:-4
Enter string 3:cow
No of positive numbers entered is: 1
def main():
global countervalue
countervalue=0
string=int(input("How many strings do you want to enter? "))
for num in range(1,string+1):
value=float(input("Enter string %a: "%num))
IsPos(value)
print("No of positive whole numbers entered is:",countervalue)
def IsPos(val):
global countervalue
if val.is_integer() and val>=0:
countervalue+=1
return countervalue;
main()
I think you just need to test whether the input value is a number or not by converting to float and catching the resulting exception:
def main():
global countervalue
countervalue = 0
string = int(input("How many strings do you want to enter? "))
for num in range(1, string+1):
value = input("Enter string %a: " % num)
IsPos(value)
print("No of positive whole numbers entered is:", countervalue)
def IsPos(val):
global countervalue
try:
fval = float(val)
if fval.is_integer() and fval >= 0:
countervalue += 1
except ValueError:
pass
return countervalue
main()
Output as requested

How to use a for-loop/range to end a specific character input in Python?

If user entered anything other than an integer it should be ignored, whereas, if it were to be an integer it should be added to the lst (list)
the function should display the list of integers, ignoring anything that wasn't an integer and display the max and min number.
lst = []
n = int(input("Enter Integers: "))
for index in range(min(n), max(n)):
if index == ' ':
return
for i in range(min(n),max(n)):
elements = int(input())
lst.append(elements)
print(lst)
print(len(lst))
for num in lst:
if num % 2 == 0:
print(num, end= ' ')
I have a function here that prompts users to enter a list of integers, if SPACE is inputted: it should END the input.
I'm quite new at python and not sure how to go about this code.
The expression
input("Enter Integers: ")
evaluates to a string. Since you want to read strings until a space is inserted, you need a infinite loop:
numbers = []
while True:
value = input("Enter an integer: ")
If the user provides a space, stop reading numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
# Exit the loop
break
If you want to convert it to an integer, use the int function and append it to numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
numbers.append(int(value))
You can also add a validation, if the user provides a value that isn't a number:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
try:
number = int(value)
except ValueError:
print('The value is not a number!')
# Continue looping
continue
numbers.append(number)
Your code there is somewhat misleading and adds confusion to the question. My solution below is based off the question before the code.
lst = []
print("Enter Integers:")
while True:
n = input()
try:
# Try converting to an int, if can't ignore it
lst.append(int(n))
except ValueError:
pass
# If space input, break the loop
if n == ' ':
break
print("Integer list: ")
print(lst)
if len(lst) > 0:
print("Min: " + str(min(lst)))
print("Max: " + str(max(lst)))

Getting Attribute Error using is.integer() on user input for multiplication table

I am new to programming and I've been trying to run through a few practice exercises with Python. I am trying to create a multiplication table where the user can pick a number and how many different multiples they wish to see. I am running into an AttributeError when the user tries to input how many multiples they wish to see and I was wondering if there was any way to fix it. Any help would be much appreciated:
def multiple_generator(multiple, number):
if multiple.is_integer() or multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {multiple} = {number * multiple}")
else:
print("Please input a positive integer numb nuts")
try:
a = input("What number you want to multiply? ")
b = input("How many multiples you want to see? ")
multiple_generator(int(b), a)
except ValueError:
print("Please input a positive integer ")
Try this instead:
def multiple_generator(multiple, number):
if multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {i * multiple}")
else:
print("Please input a positive integer numb nuts")
try:
a = input("What number you want to multiply? ")
b = input("How many multiples you want to see? ")
multiple_generator(int(b), int(a))
except ValueError:
print("Please input a positive integer ")
The reason your code didn't work because you forgot to cast a to an integer as well. Also is_integer is not needed since b is already casted to an integer type.
From the docs:
Returns True if the float instance is finite with integral value, and False otherwise.
When you are converting b to an integer and passing it, it is getting assigned to multiple. But, is_integer() method only works for floats. So you get an error.
You can simply do:
def multiple_generator(multiple, number):
if float(multiple).is_integer() or multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {i * multiple}")
else:
print("Please input a positive integer numb nuts")
But since b is already an integer, you can just check if multiple > 0
def multiple_generator(multiple, number):
if multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {i * multiple}")
else:
print("Please input a positive integer numb nuts")
Also, you are printing multiples of a number. But input returns a string. When you multiply string with an integer, it creates n copies of itself.
While passing the argument a, convert it to an integer.
Also, you need to multiply with i instead of multiple:
def multiple_generator(multiple, number):
if multiple > 0:
for i in range(1, multiple + 1):
print(f" {number} x {i} = {number * i}") #=== Multiply by i
else:
print("Please input a positive integer numb nuts")
try:
a = input("What number you want to multiply? ")
b = input("How many multiples you want to see? ")
multiple_generator(int(b), int(a)) #=== pass as An integer
Output:
What number you want to multiply? 2
How many multiples you want to see? 2
2 x 1 = 2
2 x 2 = 4

Modify code to accept any real numbers(integer or float)

I can figure out how to make this code accept float points as well as integers.
What this code does is it: Accepts an unlimited amount of user inputs, must as non-negative integers. when a blank line is detected the input ends.
The code; prints the list in ascending order. prints a total of all the numbers and then prints the average number.
code:
nums = []
response = " "
total = 0
print("Type a positive integer: ")
while response != "":
response = input()
if response.isnumeric():
nums.append(int(response))
print("Next number: ")
elif response == '':
break
else:
print("Error, you have to type a non-negative integer.")
nums.sort()
for item in nums:
total = total + item
if nums != []:
print("The numbers in order: ",nums)
print("Total number: ",total)
print("The average is",sum(nums) / len(nums))
else:
print("There are no numbers in the list")
The line:
nums.append(int(response))
is casting your string input to integerss. Simply change it to:
nums.append(float(response))
If you want it to take integers as well as floats then you need to remove the cast entirely:
nums.append(response)
If you want to append integers as int and floats as float, you can use :
nums.append(float(response) if "." in number else int(response))
The float class has an .is_integer() function:
buf = float(response)
if buf.is_integer():
buf = int(buf)
nums.append(buf)

Categories