I am in an intro to programming class which is using zyBooks so I'm not sure (due to the way this interpreter works) if my problem is just me doing something stupid or just not working properly with the zyBooks thing.
Its asking me to do a basic user input string. These are the instructions:
Assign user_str with a string from user input, with the prompt: 'Enter a string: '
Hint -- Replace the ? in the following code: user_str = ?('Enter a string: ')
I believe i've followed the instructions its given me but I'm getting this error. Thanks for any help!!!
1
2 '''Your Solution Goes here '''
3 user_str = int(input'Enter a string: '))
4 print()
5
6 print(user_str)
The error I'm getting:
Exited with return code 1
Traceback (most recent call last):
File "main.py", line 3, in <module>
user_str = int(input('Enter a string: '))
ValueError: invalid literal for int() with base 10: 'Hello!'
You cannot turn Hello! into an int. Get rid of the int(...) around input.
Note: You can turn strings into ints if the string is a valid number.
Im a little confused with your question, so I will answer both interpretations I can make.
If you want the user to enter a string (ex: Hello World), you want to save it as a string in a variable, so omit the int() function that will try (and fail) to convert it to a integer:
user_str = input('Enter a string: ')
If you want an integer instead (ex: 231) the problem is that you are asking the user for a string, so a better solution would be:
user_str = int(input('Enter a number: '))
or:
user_str = int(input('Enter a integer: '))
The correct way for this case would be to try to convert it to a integer, and print a message if it fails (Probably you haven't seen this in your class yet):
correct_inp = False
while not correct_inp:
inp_str = input('Enter a integer: ')
try:
user_str = int(imp_str)
correct_inp = True
except:
print("Ups, this is not an integer, try again")
print(user_str)
Related
I've been trying to work out why how the try-except statement works out but became stuck on the following code.
The input will be Enter Hours: 10 and Enter Rate: ten
sh = float(input("Enter Hours: "))
sr = float(input("Enter Rate: "))
try:
fh = float(sh)
fr = float(sr) # string rate
except:
print("Error, please enter numeric input")
quit()
print(fh, fr, sep='')
sp = fh * fr
print("Pay: ", round(sp, 2))
The code gives me a Traceback as the following:
Traceback (most recent call last):
File "C:\Users~~~~", line 2, in <module>
sr = float(input("Enter Rate: "))
ValueError: could not convert string to float: 'ten'
However, if I change the first 2 lines to ...
sh = input("Enter Hours: ")
sr = input("Enter Rate: ")
Then the code suddenly starts to work properly resulting as the following:
Enter Hours: 10
Enter Rate: ten
Error, please enter numeric input
What explanation is there for this to happen?
In the original code snippet, you attempt to cast the user input to float immediately, i.e. outside the try block. This throws a ValueError (as expected) but since it does so before the try, it cannot be caught and handled as you expect.
it looks like you are trying to convert string 'ten' to float 10.0
you cannot do that
your code is
sh = float(input("Enter Hours: "))
takes input in string format and then convert it in float value and then store it in a variable called sh
sr = float(input("Enter Rate: "))
this also do the same thing but insted of storing it to sh it store it to sr
the the try block starts
it says
do this if any error occur skip every thing and go to except block
fh = float(sh)
fr = float(sr)
and because you cannot convert string to float you get an error in the try block and then go to except block.
Traceback (most recent call last):
File "C:\Users~~~~", line 2, in <module>
sr = float(input("Enter Rate: "))
ValueError: could not convert string to float: 'ten'>
this error come because you are trying to convert string to float in line 2 because input is 'ten' which is a string
sh = input("Enter Hours: ")
sr = input("Enter Rate: ")
this is working because you are not converting anything just taking input
and converit it on the try block which gives an error and then go to excpt block and
print("Error, please enter numeric input")
I have a txt file with names of people.
I open it and want to get only the names with the length the user entered, using the filter and lambda functions.
The problem is that the list I get is empty [].
names_file = open('names.txt').read().split()
user_choice = input("Enter name length: ")
print(list(filter(lambda c : len(c) == user_choice, names_file)))
What is the problem ?
See this line
user_choice = input("Enter name length: ")
You are taking a string input. If you want to take an integer input you need to write int(input()). I hope this will solve the problem.
user_choice = int(input("Enter name length: "))
should fix it.
I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:
# Compare phone number
phone_pattern = '^\d{3} ?\d{3}-\d{4}$'
# phoneNumber = str(input("Please enter a phone number: "))
if re.search(phone_pattern, "258 494-3929"):
print "Pattern matches"
else:
print "Pattern doesn't match!"
Pattern does not match
Please enter a phone number: 258 494-3929
Traceback (most recent call last):
File "pattern_match.py", line 16, in <module>
phoneNumber = str(input("Please enter a phone number: "))
File "<string>", line 1
258 494-3929
^
SyntaxError: invalid syntax
C:\Users\Developer\Documents\PythonDemo>
By the way, I did import re and tried using rstrip in case of the \n
What else could I be missing?
You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself:
phoneNumber = raw_input("Please enter a phone number: ")
In Python version 2.x, input() does two things:
Reads a string of data. (You want this.)
Then it evaluates the string of data as if it were a Python expression. (This part is causing the error.)
The function raw_input() is better in this situation because it does #1 above but not #2.
If you change:
input("Please enter a phone number: ")
to read:
raw_input("Please enter a phone number: ")
you'll eliminate the error of the phone number not being a valid Python expression.
The input() function has tripped up so many people learning Python that starting with Python versions 3.x, the designers of the language removed the extra evaluation step. This makes input() in versions 3.x behave the same as raw_input() in versions 2.x.
See also a helpful wikibooks article.
The input() function actually evaluates the input that's typed into it:
>>> print str(input("input: "))
input: 258238
258238
>>> print str(input("input: "))
input: 3**3 + 4
31
It's trying to evaluate '258 494-3929' which is invalid Python.
Use sys.stdin.readline().strip() to do your read.
input() calls eval(raw_input(prompt)), so you want phoneNumber = raw_input("Please enter a phone number: ").strip()
See also http://docs.python.org/library/functions.html#input and http://docs.python.org/library/functions.html#raw_input
I have to create a program that lets the user enter a string and then, using range, the program outputs that same string backwards. I entered this into python, but it goes me an error, in the 4th line, it says 'int' object has no attribute '__getitem__'.
Can someone please help me correct it? (Using range)
user=raw_input("Please enter a string: ")
user1=len(user)-1
for user in range(user1,-1,-1):
user2=user[user1]
print user2
I think you have a mistake because you keep using the same words to describe very different data types. I would use a more descriptive naming scheme:
user = raw_input("Please enter a string: ")
user_length = len(user)
for string_index in range(user_length - 1, -1, -1):
character = user[string_index]
print(character)
For example, if the user input was foo, it would output:
o
o
f
You are overwriting the user string with your for-loop, fix it by changing the for-loop variable
Fix:
for ind in range(user1,-1,-1):
user2 = user[ind]
print (user2)
Alternative (without for-loop):
print user[::-1]
This is because you are overwriting the string user with an int in the line for user in range(...)
Perhaps you'd be better off with:
user=raw_input("Please enter a string: ")
for user1 in range(len(user)-1,-1,-1):
user2=user[user1]
print user2
your user has been overwrited in your for loop. Take this(Use range)
user=raw_input("Please enter a string: ")
print ''.join([user[i] for i in range(len(user)-1, -1, -1)])
Python 3 solution:
user=input("Please enter a string: ")
for ind in range(1,len(user)+1):
char = user[-ind]
print(char)
And another non for loop solution is:
''.join(reversed(user))
I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))