Hi I am a beginner for python. May I ask how do you write an input prompt that takes a single number as the input, which represents a new row. Thanks
In python, you can use input() to read the input from the keyboard so if you want to use it later you can use a variable to store the input
str_input = input("Enter the string")
so by using the variable str_input you can get the value for later use like for printing etc. for print the value use
print(str_input)
So if you need to read the number as input then you need to typecast because everything in python default as a string so for typecast use
num_int = int(input("Enter the number"))
So by this you can read the num
Related
I was under the impression that in Python it was necessary to write (str) when converting an int to a str, but in this case, if the user inputs a number, it still executes fine
print('Enter a name.')
name = input()
if name:
print('Thank you for entering a name, ' + name)
else:
print('You did not enter a name.')
I didn't need to write + str(name) on line 4 when the input entered was 1, for example (or any number).
If you read the docs on input then you will see this line that refers to your scenario:
The function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
We can also see this in the interpreter:
>>> type(input())
<class 'str'>
And, to clarify, Python will never return an int from input(), you always need to convert if you want to do arithmetic operations or otherwise.
Note that the behaviour is different in Python 2 which offers input() and raw_input(). The first of which will convert the input to the appropriate data type (such as int) whereas the latter will function the same as input() in Python 3.
This can again be tested in the interpreter:
>>> type(input())
5
<type 'int'>
>>> type(raw_input())
5
<type 'str'>
Because Python does some stuff in the background to figure out what the variable types are. Plus, the input from input is always a string. You just concatenated two strings.
The function input always returns a string. What you just witnessed is a string concatenation.
If you wanted to convert the results of input into a different type, say integers, then you can do:
x = int(input("Enter a number"))
This will raise an error if the input cannot be expressed as an int type though. You can do additional parsing or type testing (e.g. isinstance() or type() is...) depending on the complexity of the input you're expecting.
Write a python program to accept 2 "string" numbers for calculation.
Note : convert string number to an Integer before perform the calculation
Any examples answer?
You have to accept input in string, use raw_input(), and you have to parse them in int. And perform your calculation
This question already has answers here:
How to accept the input of both int and float types?
(6 answers)
Closed 5 years ago.
I'm trying to make a factorial calculator.
Input and Expected output:: If the user input is a positive integer, I want the program to give the outcome. And if the user input is not a positive integer(negative integer, float, or string), I want the program to ask for the input again. Also, I want the program to end when the user input is 0.
Problem: Since inputs are always perceived as string data, I am stuck with coding according to the type of input.
It would be of great help if someone would give answers to this problem, as I am studying by myself.
If you want to ensure it's a positive integer, and if you want to keep asking for input as specified in your question, you'll need a few more control structures:
from math import factorial
def get_input():
while True:
try:
inp = int(input("Enter a positive integer> "))
if inp < 0:
raise ValueError("not a positive integer")
except ValueError as ve:
print(ve)
continue
break
return inp
print(factorial(get_input()))
This works by just trying to convert the input to an integer, and retrying if this fails. The continue statement is used to skip past the break. The try/except structure catches the error if it's not an integer, or the error explicitly raised if it's less than 0. It also uses the as feature of except to print a better indication of the error. It's encapsulated in a function to make things easier - I find factorial(get_input()) to be pretty expressive, with the added bonus of being more reusable.
This currently doesn't end when the user input is 0, as 0 is a perfectly valid input for factorial, although it should be easy enough to adapt to this with an if statement.
This program might be used like this:
Enter a positive integer> abc
invalid literal for int() with base 10: 'abc'
Enter a positive integer> 0.2
invalid literal for int() with base 10: '0.2'
Enter a positive integer> -5
not a positive integer
Enter a positive integer> 6
720
By the way, this code works according to EAFP - it just tries to convert to an integer, and handles failure. This is more idiomatic Python than first trying to determine if it could be an integer (LBYL).
If you're using Python 2, you'll need to change input to raw_input.
Check if input is positive integer check this link out along with the link provided by user #cricket_007 above. Combining those two information should get you in the right direction.
Try to think of it as an algorithm problem not as a Python problem, you may find a solution because in general every language has its functions and they all almost the same only with different name.
In python they are a function call isnumeric() and it returns true if every single character is a number or false if it's not.
str.isnumeric()
us it with a statement condition like if
if str.isnumeric()==true // so it's numeric
// what to do!!!!!
the best choice it to use while and if
while true
//read data as string
if str.isnumeric()==true
break; // this to break the while loop
hope this can help you
I get the users Input with raw_input(). This Input is stored in a variable.
How can I cast this variable to be Unicode. I Need this for further executions.
userinput = raw_input("Hello. What is your Name?")
Jst call the "decode" method on the result of "raw_input". Matter is, you need to know the encoding of the terminal where the input was made:
import sys
value = raw_input("bla bla bla").decode(sys.stdin.encoding or 'utf-8')
But yu really should use Python 3
Python newbie here. I've been messing around with flow control and have come across a situation I don't quite understand related to exceptions.
In the following code I want the user to enter an integer in a given range and, in the case of non-compliance, keep asking them until they give a valid value:
while True:
try:
x = int(raw_input("Pick an integer between 2 and 9. "))
except ValueError:
print "Please enter an integer!"
continue
else:
if 2 <= x <= 9:
print("Your number is {0}.").format(x)
break
else:
print "That's not between 2 and 9!"
continue
As far as I can tell, this code works exactly as I want it to. I've thrown every other type of input I can think of at it and it only lets you exit the loop when an integer from 2-9 is entered. Not even floats are accepted.
My question is, given that int() can be successfully called on floats,
>>> int(2.1)
2
why does this try/except construct raise the exception when the input is a float? If I run the code without the try/except statements and enter anything other than an integer, it throws an error and exits.
I'm running python 2.7 from windows powershell.
This is because raw_input returns a string.
Under the hood, when you call int, it actually calls an objects object.__int__() method. This is different from object to object.
For a float, this truncates a value (Rounds towards 0).
On a string, it tries to parse an int according to https://docs.python.org/3/reference/lexical_analysis.html#integer-literals (Which can't have a .).
The issue here is that you are calling int() on a string that could potentially contain a period. To fix this I would recommend you change the int() to float(). This should fix your problem
x = float(raw_input("Pick an integer between 2 and 9. "))
Not sure what version of Python you are using but if it is Python 3.0 or above you might want to carefully check the print statements in the following clips
except ValueError:
print "Please enter an integer!"
else:
print "That's not between 2 and 9!"
they are not formatted for 3.0 but will probably work ok if you use version 2.x
I think the other answers covered your original problem adequately so I will defer to them.. they know that area better than I.
Good Luck,
Poe