Python Middle String Print - string

I am relatively new to python and I have to create a program that prints the middle character of a user-inputted string. Here is what I have:
#accept string from user then print middle character
x = input("Enter a string: ")
print(x[len(x)/2-1])
However I keep getting this error when I try to run the program:
"TypeError: string indices must be integers".
Im not sure how to fix this or how to get this program to work. Please help!

From your error I infer that you are using python 3.
In python 3 division between two integers returns a float:
>>> 3/2
1.5
>>> 4/2
2.0
But a indeces must be integers, so you get the error. To force an integer division you must use the // operator:
>>> 3//2
1
>>> 4//2
2
Alternatively you can use math.ceil or math.floor if you want more control on the rounding of the floats.

This is a way:
x = raw_input("Enter a string: " )
print (x[:len(x)//2])

Related

invalid literal for int() with base 10: '1.0' [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed last month.
I wrote a program to solve y = a^x and then project it on a graph. The problem is that whenever a < 1 I get the error:
ValueError: invalid literal for int () with base 10.
Any suggestions?
Here's the traceback:
Traceback (most recent call last):
File "C:\Users\kasutaja\Desktop\EksponentfunktsioonTEST - koopia.py", line 13, in <module>
if int(a) < 0:
ValueError: invalid literal for int() with base 10: '0.3'
The problem arises every time I put a number that is smaller than one, but larger than 0. For this example it was 0.3 .
This is my code:
# y = a^x
import time
import math
import sys
import os
import subprocess
import matplotlib.pyplot as plt
print ("y = a^x")
print ("")
a = input ("Enter 'a' ")
print ("")
if int(a) < 0:
print ("'a' is negative, no solution")
elif int(a) == 1:
print ("'a' is equal with 1, no solution")
else:
fig = plt.figure ()
x = [-2,-1.75,-1.5,-1.25,-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1,1.25,1.5,1.75,2]
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
ax = fig.add_subplot(1,1,1)
ax.set_title('y = a**x')
ax.plot(x,y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.savefig("graph.png")
subprocess.Popen('explorer "C:\\Users\\kasutaja\\desktop\\graph.png"')
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
answer = input("Restart program? ")
if answer.strip() in "YES yes Yes y Y".split():
restart_program()
else:
os.remove("C:\\Users\\kasutaja\\desktop\\graph.png")
Answer:
Your traceback is telling you that int() takes integers, you are trying to give a decimal, so you need to use float():
a = float(a)
This should work as expected:
>>> int(input("Type a number: "))
Type a number: 0.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.3'
>>> float(input("Type a number: "))
Type a number: 0.3
0.3
Computers store numbers in a variety of different ways. Python has two main ones. Integers, which store whole numbers (ℤ), and floating point numbers, which store real numbers (ℝ). You need to use the right one based on what you require.
(As a note, Python is pretty good at abstracting this away from you, most other language also have double precision floating point numbers, for instance, but you don't need to worry about that. Since 3.0, Python will also automatically convert integers to floats if you divide them, so it's actually very easy to work with.)
Previous guess at answer before we had the traceback:
Your problem is that whatever you are typing is can't be converted into a number. This could be caused by a lot of things, for example:
>>> int(input("Type a number: "))
Type a number: -1
-1
>>> int(input("Type a number: "))
Type a number: - 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '- 1'
Adding a space between the - and 1 will cause the string not to be parsed correctly into a number. This is, of course, just an example, and you will have to tell us what input you are giving for us to be able to say for sure what the issue is.
Advice on code style:
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
This is an example of a really bad coding habit. Where you are copying something again and again something is wrong. Firstly, you use int(a) a ton of times, wherever you do this, you should instead assign the value to a variable, and use that instead, avoiding typing (and forcing the computer to calculate) the value again and again:
a = int(a)
In this example I assign the value back to a, overwriting the old value with the new one we want to use.
y = [a**i for i in x]
This code produces the same result as the monster above, without the masses of writing out the same thing again and again. It's a simple list comprehension. This also means that if you edit x, you don't need to do anything to y, it will naturally update to suit.
Also note that PEP-8, the Python style guide, suggests strongly that you don't leave spaces between an identifier and the brackets when making a function call.
As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:
With Python2, int(str(5/2)) gives you 2.
With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'
If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:
int(float(myStr))
As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.
It might be better to validate a right when it is input.
try:
a = int(input("Enter 'a' "))
except ValueError:
print('PLease input a valid integer')
This either casts a to an int so you can be assured that it is an integer for all later uses or it handles the exception and alerts the user
int() casting can't handle string numbers that have decimal points
- example --> int('13.5') will give you error , but int('13') will convert the
string to integer
Why : This considered as explicit casting required by the user as it prevents you from losing information like 0.5 if you read dataset and don't know it's had floating-point numbers
Work Around >
int(Float("13.5"))
A real-world example I faced: where I wanted the numbers as int while int(I["mpg"]) directly didn't work so I used float() then int()
sum([int(float(i["mpg"])) for i in file])//len(file)

error shows while using type casting for input in python3

I am trying to take multiple numbers as input and use those numbers as parameters as *args in function,but python interpreter shows it is a s error.I tried in different type and it works well.But i want to know the difference between them.?
#numbers = [int(x) for x in input("Enter multiple value: ").split(",")] # gives no error
numbers=int(input()).split(",") #Giving error
def add(*numbers):
sum=0
for number in numbers:
sum=sum+number
print(sum)
print(add(*numbers))
int(input()).split(",") -> of course this will return error.
The split() method splits a string into a list. Your code implies converting input into int type and split the integer.
numbers = [int(x) for x in input("Enter multiple value: ").split(",")]
this will not throw an error as you are creating a list of integers by iterating through list generated by split.

how to check if a string is in a certain format in python?

I will have a string and I want to check that it is in the format "float, float, float, float". There will be 3 commas and four floats, I don't know how many decimal places long the floats are gonna be. so I want to check it without using re class. I need to extract all four floats after checking the string. so 3 floats before a comma and 1 last after comma.
I can't find a string function to do that. I have checked my python reference book and still can't find a method. I usually code in C++ and recently begun Python. Thank you for your help.
Here's my attempt at your problem.
# Returns the list of four floating numbers if match and None otherwise
def four_float(str_input):
# Split into individual floats
lst = str_input.split(',')
for flt in lst:
# Check for the existence of a single dot
d_parts = flt.strip().split('.')
if len(d_parts) != 2:
return None
else:
# Check that the chars on both sides of the dot are all digits
for d in d_parts:
if not d.isdigit():
return None
return [float(n) for n in lst]

how do I call an element in a list?

a= int(input())
# I input 12345
b = a
list(map(int, b))
print (list[0]*2+list[3]*1)
#can't seem to get 6 as my answer
how do I attain my answer? I can't seem to call the elements in the list. Thank you for your help.
Since you're treating the input as individual digits, you should avoid converting the input to an integer as a whole, but map the individual digits to integers as a sequence of characters:
a= input()
b = list(map(int, a))
print(b[0] * 2 + b[3] * 1)
There are several reasons why your code won't work, including your use of the map function, the fact that you do not assign the result to a variable and the use of list (which is a keyword in Python).
However, consider this code snippet which calculates your desired output:
a = int(input('Enter a number: '))
b = [int(digit) for digit in str(a)]
res = 2 * b[0] + b[3]
print(res)
Basically you have to transform your integer into a string to be able to iterate over it. Afterwards you create your list of digits out of it and can do your calculations.
Generally speaking, you should learn the basics of Python properly. A good starting point would be the official documentation (LINK).

What's x for x in input()?

I am new to coding and is trying to solve this python question
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
This is the solution given. I have not seen 'x for x in input()'expression, may I know what does this expression do ?
import math
c=50
h=30
value = []
items=[x for x in input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print (','.join(value))
This is my own solution but somehow I got a syntax error.
def sr(D):
For item in D:
return ((2*50*D)/30)**0.5
try:
a=int(input())
j=a.split(",")
print(sr(j))
except:
print('Please enter an integers or intergers seperated by comma')
The x is just a variable that gets assigned to the input that comes in via the input() function.
If you're aware of C style language (or Java), it's similar to
for(int i=0;<some_condition>;<some_operation>){}
This is just a condensed, pythonic and easy to read way to do this.
You can read more Python loops here
https://wiki.python.org/moin/ForLoop

Resources