Python 3.3 Hello program - python

# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')
myName = input()
for Name in myName (1,10):
print('It is nice to meet you, ' + myName)
I was asked to create a program that uses a for loop and another program for while loop, I've got this for for loop but I'm trying to set how many times I want it to repeat myName. Please help me out if you can, thanks in advance!

# your code goes here
print('Hello world!')
print('What is your name?')
#I use raw_input() to read input instead
myName = raw_input()
#ask user how many times you would like to print the name
print('How many times would you like your name to repeat?')
#raw_input() reads as a string, so you must convert to int by using int()
counter = int(raw_input())
#your main issue is here
#you have to use the range() function to go a certain length for for-loops in Python
for x in range(counter):
print('It is nice to meet you, ' + myName)
Note: For your code, you should use input() instead of raw_input(). I only used raw_input() because I have an outdated compiler/interpreter.

python 3.x (3.5)
#Just the hello world
print('Hello world!')
#use input() to let the user assign a value to a variable named myName
myName = input('What is your name?:')
#now let the user assign an integer value to the variable counter for how many times their name should be repeated. Here i am enclosing the input of the user with an int() to tell python that the data type is an integer
counter = int(input('how many times do you want to repeat your name?:'))
#Use the Range function to repeat the names
for a in range(counter):
print('It is nice to meet you, ' + myName)

for Name in myName (1,10):
print('It is nice to meet you, ' + myName)
myName is a string, so you won’t be able to call it, which is what the parentheses do. If you want to repeat the name for a certain amount of times, you should iterate over a range:
for i in range(10):
print('It is nice to meet you, ' + myName)
This will print out the greeting 10 times.

Related

I cannot get rid of this space

I have the simple code:
answer= input("Have you started your first homework? ")
print("Your answer was:", answer,"!")
However every time I run this it prints the answer there is a space before the "!".
I cannot find a way to make the exclamation follow the answer directly. Why and how can I do that?
If you want to print the answer, you have a few options:
# Multiple args
print("Your answer was: ", answer, "!", sep="")
# String formatting
print("Your answer was: {}!".format(answer))
# String concatenation
print("Your answer was: " + answer + "!")
Python 3.6+:
# f-strings
print(f"Your answer was: {answer}!")
print has an argument called sep which, by default, is set to ' ' (a space). It will add that separator between every argument.
print function automatically adds a space between comma separated arguments.
So if you don't want that comma, don't pass them as separate arguments and use string formatting instead e.g.:
print("Your answer was:", "{}!".format(answer))
Here i've concatenated the strings using str.format:
"{}!".format(answer)
If you're in Python 3.6 or later, you can use f-strings:
f"{answer}!"
You can even use the printf style formatting:
"%s!" % answer
Try this:
print("Your answer was: "+answer"+"!")

Python - Can't get "string.isalnum():" to work properly

I cannot get the code below to work properly. It works if the user enters numbers for the name and it prints the theName.isdigit. But if the user enters both numbers and letters, it accepts this and moves onto a welcome message that follows. Looking at this, is there a reason you can find why theName.isalnum is not working here but the one above is?
theName = raw_input ("What is your name?? ")
while theName.isdigit ():
if theName.isdigit ():
print "What kind of real name has just numbers in it?? Try again..."
elif theName.isalnum ():
print "What kind of name has any numbers in it?? Please try again..."
elif theName.isalpha ():
print "Ok, great"
break
theName = raw_input ("What is your name?? ")
theName = raw_input ("What is your name?? ")
while not theName.isalpha ():
if theName.isdigit ():
print "What kind of real name has just numbers in it?? Try again..."
elif theName.isalnum ():
print "What kind of name has any numbers in it?? Please try again..."
theName = raw_input ("What is your name?? ")
print "Ok, great"
The while condition should tell you when to stop looping, that is, when the input isalpha. Then, because the while loop stops when the input is correct, you can move the logic for what to do in that case below the loop.
Looping on isdigit is problematic because the string abc123 doesn't meet that condition, so you break out of the loop even though the name doesn't meet your criteria.
As mentioned by others your code has a few problems.
First, if the theName contains anything other than digits, you will never enter the while loop, because isdigit() will return False.
Next, the order of your tests means that you will only reach the isalpha() test if the entered name contains something other than letters or digits.
However, it is also overly complex. Assuming your goal is to get the user to enter a name consisting only of letters (i.e. no spaces, digits, or special characters)
theName = "1" # preseed with invalid value
firstTime = True
while not theName.isalpha():
if not firstTime:
print "Your name should not contain anything other than letters"
theName = raw_input("Please enter your name: ")
firstTime = False
print "OK, great. Hi " + theName
This will repeatedly prompt until the user enters a valid name.

Python code, .rstrip isn't working?

I've searched answers on here and tried implementing them but I think that there is some tiny detail I'm missing. I have a very short python code for a program that is supposed to return the initials with periods of a persons input(for their full name). So for example, input is Atticus Leonard Beasley and output should be
A.L.B.
but instead I'm getting:
A.
L.
B.
Here's my code:
def main():
full_name = input("Enter your first, middle, and last name: ")
for ch in full_name:
if ch.isupper():
ch = ch.rstrip('\n')
print (ch,'.', sep='')
main()
FYI, you can do this using split and join:
def main():
full_name = input("Enter your first, middle, and last name: ")
initials = []
for name in full_name.split():
initials.append(name[0])
print('.'.join(initials) + '.')
main()
Or using list comprehension:
def main():
full_name = input("Enter your first, middle, and last name: ")
print('.'.join(name[0] for name in full_name.split())+'.')
main()
I think you can do that in a easier and "more pythonic" way.
full_name = input("Enter your first, middle, and last name: ")
print(''.join([ch[0].upper() + '.' for ch in full_name.split()]))
EXPLANATIONS
Instead of doing a for loop over each letters of the name, you can use split() function to be sure to took care of every words without the extra spaces.
sentence = "hello world"
for ch in sentence.split():
print(ch) # hello
break
Now, you try to verify if the first letter is an uppercase, but if the user enter his name without uppercase, your function does not work. An easier solution will be to extract the first letter of the word ch[0] and automatically add an uppercase: ch[0].upper()
Maybe the one-liner solution is confusing, but most of the python developers use list comprehension over for loops when the solution is easily readable.
EDIT
One more thing, even if you are writing a simple function such as print the initials of a name, you should always write tests accordingly.
A good way to start is to use doctests because it forces you to describe what your function does. Even if you think it's a waste of times, it helps to overcome many problems when your program is getting bigger. I'd be please to help you if you want to try to write your first doctest

Error "Can't convert 'int' object to str implicitly" [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
I just started Automate The Boring Stuff, I'm at chapter 1.
myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + lengthofname)
I ran this, it gave me Can't convert 'int' object to str implicitly.
My reasoning at line 3 is that I want the variable myname to be converted into an integer and then plugged into line 4.
Why would this be an erroneous way of coding?
When you have print ('your name is this many letters:' + lengthofname), python is trying to add an integer to a string (which of course is impossible).
There are 3 ways to resolve this problem.
print ('your name is this many letters:' + str(lengthofname))
print ('your name is this many letters: ', lengthofname)
print ('your name is this many letters: {}'.format(lengthofname))
You have problem because + can add two numbers or concatenate two strings - and you have string + number so you have to convert number to string before you can concatenate two strings - string + str(number)
print('your name is this many letters:' + str(lengthofname))
But you can run print() with many arguments separated with comma - like in other functions - and then Python will automatically convert them to string before print() displays them.
print('your name is this many letters:', lengthofname)
You have only remeber that print will add space between arguments.
(you could say "comma adds space" but print does it.)
Your code seems to be Python 3.x. The following is the corrected code; just convert the lengthofname to string during print.
myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + str(lengthofname))

How to count how many words are in a text string inputted by the user in python

I was wondering if anybody could help; I'm quite new to python.
I'm currently creating a tool which analyses the text inputted by a user and shows which feedback to which list that phrase belongs to.
So far the programme is on an infinite loop and counts how many expressions have been entered all together and then how many times something has occurred in a certain list.
if text in access:
accessno +=1
counter +=1
print ('This could be classed as speech act 1: Access')
print ("number of access hits ", accessno)
print ("number of total hits ", counter)
So my question is this: how does one also get the programme to count how many words are in a sentence inputted by the user?
Any help would be much appreciated!
You can do it in the following simple way.
s = input()
# input() is a function that gets input from the user
len(s.split())
# len() checks the length of a list, s.split() splits the users input into a word list.
Links:
input()
len()
split()
Example:
>>> s = input()
"hello world"
>>> s
'hello world'
>>> s.split()
['hello', 'world']
>>> len(s.split())
2
Bonus: Do it all in one line!
print('You wrote {} words!'.format(len(input("Enter some text, I will tell you how many words you wrote!: ").split())))
name = input ()
print len(name)

Categories

Resources