How to change a lower case to upper case using function? - python-3.x

I'm trying to convert a input parameter to capital case.
text = input("write anything you wish you change to capital case: ")
def case_change():
text.upper()
print(case_change(text))

You are not asking for an argument in the function case_change, but passing in text as an argument to it while calling case_change
Try:
text = input("write anything you wish you change to capital case: ")
def case_change(text):
return text.upper()
upper_case = case_change(text)
print("capital case is: "+upper_case)

Related

How would I print a string obtained from a user in reverse?

I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.
user_string = input("Please enter a string: ")
for letter in (user_string)[::-1]:
print(letter)
You can reverse and use str.join to rebuild the string.
print("\n".join(reversed(input("Please enter a string: "))))
If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:
while i < arr_length:
with i incrementing at the end of every round.
The rest of the code would be the same but using i as an index.
One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.
user_input = list(input())
while len(user_input) > 0:
print(user_input.pop())
list.pop() will remove the last item in the list and return it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Using index property we can easily reverse a given string
a = input()
print(a[::-1])

how can I get a program to run if the user has inputted at least one character?

how can I get a get a program to run if the user has inputted at least one character. For example:
userinput = input("Enter your age: ")
if (user input) > (at least one character/number):
print(blank)
To clarify, I am wondering how if a user input has more than one character, how to make the if statement run (or any other statement)
you can use len() function to check the length of the input. so your code will look like.
userinput = input("Enter your age: ")
if len(userinput) >= 1:
print(userinput)
In this case if the input contains any character or space the if statement will work. If your looking for only character or digits then you can use the re module to check for the input contents. In this case you write your code as.
import re
userinput = input("Enter your age: ")
if re.search(r'[0-9A-Za-z]+', userinput):
print(userinput)
This regular expression will search for any digit or character and if found will set the condition to True.

How do I figure out my issue with placing the "try" function?

So I have been struggling to find out what is wrong with my exception code which is to only accept strings but also display text whenever there are non string inputs between the brackets which depends on where I put the "try" and except functions.
The first code I have here which 'try' is before return, any strings entered in will be accepted into the function, however the except functions will not work whenever non-strings are entered between the bottom brackets.
'''
def string_processor(string):
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
try:
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except IndexError:
print("Please enter a string with quotation marks ")
else:
print("Please only enter a string")
string_processor("000")
'''
The second code I have which I put "try:" can sort out some things such as AttributeErrors, but only strings with letters can be inputted between the brackets and any string that contains non-numbers are omitted from the function.
'''
def string_processor(string):
try:
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except SyntaxError:
print("Please enter a string with quotation marks ")
else:
print("Please only put letters in your string")
string_processor("000")
'''
I request help to fix this problem so my program can get any type of string, and will process except functions for any non-string values.
I could be wrong understanding your question. But here are my suggestions to solve your problem.
First of all, I couldn't understand your code because the else statement is not reachable there, so I slightly changed it, but nothing dramatically changed.
def string_processor(string):
# This is a bad way to check the types and the value
try:
if string.isalpha():
# If string has a type "string" and contains only letters
return string.count('a')/len(string)
elif string.isnumeric():
# If string has numbers only
print("Please enter a string instead")
except:
if isinstance(string, list):
# If type of the "string" is actually a list
print('This is not a string, this is a list')
elif type(string) == tuple:
# If type of the "string" is actually a tuple
print('This is not a string, this is a tuple')
else:
# If none of the above worked
print('It is definitely not a pure string')
a = string_processor(234)
As I commented, this is not a good way to implement the solution, the better way may be this:
def string_processor_another(value):
# It is better to RAISE exceptions, not to print them
if not isinstance(value, str):
raise TypeError('This must be a string')
# So if we come to this step we can be sure that we work with strings, so we can use the methods
if value.isalpha():
# If string has a type "string" and contains only letters
return value.count('a')/len(value)
elif value.isnumeric():
# If string has numbers only
print("Please enter a string instead")
b = string_processor_another(234)
And if you are going to add some extra logics or you want to have a cleaner code, I'd suggest you to make this in oop way
class StringProcessor:
def __init__(self, string):
self.__check_for_str(string)
self.string = string
#staticmethod
def __check_for_str(string):
return isinstance(string, str)
# Here you can add short functions to make all of your logic statements
def check_is_numeric(self):
print(self.string.isnumeric())
def check_is_alpha(self):
print(self.string.isalpha())
sp = StringProcessor('1234')
sp.check_is_numeric() # True
sp.check_is_alpha() # False
Hope it helped.

How can I change upper case to lower and vice versa?

I am playing around with a small script, just for fun. I'm trying to reverse the items in a string and witch the upper case to lower and lower to upper. The reverse part works, but the case part doesn't. What am I doing wrong here?
def reverse(s):
if len(s) == 0:
return s
else:
if s.lower():
s.upper()
else:
s.lower()
return reverse(s[1:]) + s[0]
mytxt = reverse("I wonder how this text looks like Backwards")
print(mytxt)
Here is my current output.
sdrawkcab ekil skool txet siht woh rednow I
str.lower does not return a boolean of whether it's lowercase or not. It returns a string in lowercase. It also doesn't change a string in place.
Since that is the case you need to check the character you are currently interested in.
In this case s[0]. Additionally, strings aren't mutable so you can't change them in place. You'll need a temp variable.
def reverse(s):
if len(s) == 0:
return s
else:
# The character of interest
char = s[0]
# If it's equal to the lowercase version of it
if char == char.lower():
# Change it to upper
char = char.upper()
else:
# and vice versa
char = char.lower()
return reverse(s[1:]) + char
mytxt = reverse("I wonder how this text looks like Backwards")
print(mytxt)
s.lower() and s.upper() do not modify s but instead return another string with all letters converted to lowercase or uppercase, respectively. They don't return booleans, either (which is done by s.islower() and s.isupper()).
If you want to rewrite s, you must construct a new string from the return values.
def reverse(s):
if len(s) == 0:
return s
else:
s0 = s[0]
if s0.islower():
s0 = s0.upper()
elif s0.isupper():
s0 = s0.lower()
return reverse(s[1:]) + s0
mytxt = reverse("I wonder how this text looks like Backwards")
print(mytxt)
Here I checked for both islower and isupper, because both return False in the absence of cased characters (e.g. "0".islower() and "0".isupper() are both false).
str.lower() and str.upper() return a copy of the string converted to lower and upper case. To check whether a string is lower or uppercase, use str.islower() and str.isupper()
Python also has str.swapcase() to do exactly what you want.
Reversing a string can be done simply by using the slice notation, no need for recursion or loops. Your code could be simplified to something like:
def swapcasereverse(s):
return s[::-1].swapcase()
If you want to write your own code for swapcase as an exercise, here's a pythonic way:
def swapcasereverse(s):
newlist = [c.upper() if c.islower() else c.lower() for c in reversed(s)]
return "".join(newlist)
This function uses a list comprehension to
iterate over s in reverse order, with each character going in c
if c is lowercase, adds c.upper() to the list
otherwise, adds c.lower() to the list
Joins the list with "" to make a string, returns the joined string
def reverse(s):
if len(s) == 0:
return s
else:
if s.lower():
s.upper()
else:
s.lower()
return reverse(s[1:]) + s[0]
mytext = reverse("I wonder how this text looks like Backwards").swapcase()
print(mytext)

If statement get's a skipped, while only else statement get's printed .And how do I store a string or int in a single variable?

I was trying to do an exercise ,which asked us to solve this following problem
Exercise problem image
which I tried to do ,but by not using same exact keywords as shown in the exercise.
Here is my code
def StringLength(length_of_String):
return len(text)
text = input("length_of_String :")
if type(text) == int:
print ("python doesn't show length of integers")
else :
print (len(text))
But the problem I get here is , if I add any text say like"joker" .
It will output me length as "5",which is correct .
But when I type any integer or float , say "101" , it still prints it length as "3" because it is reading it as a string.
So how come I add Variable in which when I input a integer or string , it should recognise it as a string or an integer
some_variable = input() by default will give you string. You may want to modify your code:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def StringLength():
text = input('Enter:')
if is_number(text):
print ("python doesn't show length of integers")
else :
return(len(text))
#StringLength() #Remove the '#' at the start of the line to test the function
Edit: I have added a function to test if the entered value is a number or not

Resources